1

I'm making a tic tac toe game using tkinter for the GUI but my issue is, since i've got a function (that makes the moves) to run each time a button is clicked, it won't automatically make a move until I click a button (it doesn't matter which one) which hence stuffs up my moves indexing, and also means you have to click before the computer makes a move.

Is there anyway I can get the 'computer' itself to pretend to click a button, hence initiating the function?

Here's the make button bit:

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)

and here's the make move bit (its wip so don't mind the fact that currently computer move will only play the middle or the corners):

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)
Xantium
  • 11,201
  • 10
  • 62
  • 89
staplegun
  • 79
  • 10
  • 3
    Have you considered that a click could actually represent 2 moves? One for the player who clicked, then another for the computer? – pythomatic Sep 24 '18 at 20:02
  • thanks @Eqomatic ! got rid of the bclick thing altogether and just made them sequential if statements. now it works :) – staplegun Sep 24 '18 at 20:27
  • Possible duplicate of [Is there a way to press a button without touching it on tkinter / python?](https://stackoverflow.com/questions/23839982/is-there-a-way-to-press-a-button-without-touching-it-on-tkinter-python) – ivan_pozdeev Sep 24 '18 at 22:17

1 Answers1

0

Try using:

computer_move.invoke()

it has the same effect as clicking on the button it should work in your case. It calls the function. You can call it after you have moved and it will call computer_move for you. Happy coding!

Jimmy Lin
  • 163
  • 1
  • 1
  • 10