0

I'm makin Tic Tac Toe game and I have already search for how to get 2 positions with onclick() of Python Turtle. The thing I got is just on this link : Python 3.0 using turtle.onclick. I want to get 2 positions but I have a problem with "turtle.mainloop()" My Solution is:

def getPosX(x_X, y_X):

    print("(", x_X, ",", y_X,")")

def getPosO(x_O, y_O):

    print("(", x_O, ",", y_O,")"

def choiceX():

      Xplay = turtle.getscreen()

      Xplay.onclick(getPosX)

      turtle.mainloop()

      return Xplay


def choiceO():

      Oplay = turtle.getscreen()

      Oplay.onclick(getPosO)

      turtle.mainloop()

      return Oplay

What I got just like it just takes the postion of Xplay.onclick().

And I also try to delete the " turtle.mainloop()" of each def to use the for loop in another def:

   def play():
       for i in range(3):
            choiceX()
            choiceO()
       return i

and it doesn't work. I think I need the better measure Thanks

Community
  • 1
  • 1
Eclipsor
  • 15
  • 3

1 Answers1

0

I'm assuming that you want your turtle clicks to alternate between X and O, that is between getPosX() and getPosO(). I believe this rearrangement of your code should do what you want:

import turtle

def getPosX(x, y):

    print("X: (", x, ",", y, ")")

    choiceO()

def getPosO(x, y):

    print("O: (", x, ",", y, ")")

    choiceX()

def choiceX():

    screen.onclick(getPosX)

def choiceO():

    screen.onclick(getPosO)

screen = turtle.Screen()

choiceX()  # X goes first

turtle.mainloop()

Clicking around the screen, I get:

> python3 test.py
X: ( -206.0 , 178.0 )
O: ( 224.0 , 31.0 )
X: ( -14.0 , -122.0 )
O: ( -41.0 , 159.0 )
X: ( 146.0 , 196.0 )
O: ( 105.0 , -70.0 )
X: ( -100.0 , -114.0 )
O: ( -179.0 , 184.0 )
X: ( 23.0 , 137.0 )

When I see more than one mainloop() call (or any mainloop() call not at the top level nor the last thing in the program) it usually indicates a misunderstanding of what mainloop() does.

You set up your event handlers to do what you want and then turn complete control over to mainloop() for the remainder of the program. It will arrange for your event handers to be called when the events of interest occur.

cdlane
  • 40,441
  • 5
  • 32
  • 81