让电脑按下按钮

2024-04-24 22:04:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用tkinter做一个tic-tac-toe游戏,但是我的问题是,因为每次点击一个按钮时我都会运行一个函数(可以移动),它不会自动移动,直到我点击一个按钮(不管是哪个按钮),这会阻塞我的移动,也意味着你必须在电脑移动前点击。你知道吗

不管怎样,我是否可以让“计算机”自己假装点击一个按钮,从而启动该功能?你知道吗

以下是制作按钮位:

def make_button(n, row, col):
button_list[n]  = Button(tk,bg='gray', text = " ", fg='white',height=4,width=8,command=lambda:ttt(n, button_list))
button_list[n].grid(row=row,column=col,sticky = S+N+E+W)

这里是makemove位(它的在制品,所以不要介意当前计算机移动只会播放中间或角落的事实):

def computer_move(buttons, index):
 global bclick
 buttons["text"] = "O"
 COM.add(index)
 bclick = True



buttons=StringVar()
bclick = True 
corner_moves = {0,2,6,8}

def ttt(n, buttons):
 global bclick
 if n not in P and n not in COM and bclick == True:
     button_list[n]["text"] = "X"
     P.add(n)
     bclick = False

 elif bclick == False and 4 not in COM and 4 not in P:
     computer_move(button_list[4], 4)

 elif bclick == False: 
     corners_not_COM = (corner_moves.difference(COM))
     corners_not_P_or_COM = (corners_not_COM.difference(P))
     list_corners_not_P_or_COM = list(corners_not_P_or_COM)
     random_corner_index = random.randint(0,len(list_corners_not_P_or_COM))
     random_corner = list_corners_not_P_or_COM[random_corner_index]
     computer_move(button_list[random_corner], random_corner)

Tags: orandincomindexdefnotbutton