所以我是python的新手,我编写了一个带有Ai的tic tac toe来对抗你。所以一切都正常,但我使用文本框来通知Ai玩家选择了什么。现在我想升级我的游戏,这样玩家就可以点击他想要填充的框,而不是在文本框中键入它。所以我的想法是使用onscreenclick(),但我遇到了一些问题。onscreenclick()返回已在画布上单击的坐标,我想使用一个函数来确定玩家在哪个框中单击,我得到的结果如下:
from turtle import *
def whichbox(x,y): #obviously i got 9 boxes but this is just an example for box 1
if x<-40 and x>-120:
if y>40 and y<120:
return 1
else:
return 0
else:
return 0
box=onscreenclick(whichbox)
print(box)很明显,在本例中,我希望box为0或1,但是box的值是None。有人知道怎么解决这个问题吗?它必须对变量box做些什么,因为如果我用print("1")替换return 1,它就能工作。我假设变量被快速定义为。我的第二个问题是,是否有可能暂停程序员,直到玩家点击一个框,但更重要的是首先查看第一个问题。提前感谢:)
发布于 2019-02-23 10:07:58
假设您已经在turtle模块中命名了Screen(),那么您应该将
screen.onscreenclick(whichbox)而不是:
onscreenclick(whichbox)示例:
from turtle import Turtle, Screen
turtle = Turtle()
screen = Screen()
def ExampleFunction():
return 7
screen.onscreenclick(ExampleFunction)此外,jasonharper说onscreenclick()函数无法返回任何值的说法是正确的。因此,您可以在函数中包含一个打印函数,以便打印出一个值,例如:
def whichbox(x,y):
if x<-40 and x>-120:
if y>40 and y<120:
print(1)
return 1
else:
print(0)
return 0
else:
print(0)
return 0或者,如果您希望将print语句保留在whichbox()之外,还可以执行以下操作:
screen.onscreenclick(lambda x, y: print(whichbox(x, y)))它创建了一个lambda函数,该函数将(x,y)从onscreenclick()提供给包含哪个from ()的print语句。
发布于 2019-02-24 02:16:36
这是一个来自the code I linked to in my comment的简化示例。如果您单击一个正方形,它将在控制台窗口中打印其编号,从0到8:
from turtle import Turtle, mainloop
CURSOR_SIZE = 20
SQUARE_SIZE = 60
def drawBoard():
for j in range(3):
for i in range(3):
square = Turtle('square', visible=False)
square.shapesize(SQUARE_SIZE / CURSOR_SIZE)
square.fillcolor('white')
square.penup()
square.goto((i - 1) * (SQUARE_SIZE + 2), (j - 1) * (SQUARE_SIZE + 2))
number = j * 3 + i
square.onclick(lambda x, y, number=number: whichsquare(number))
square.showturtle()
def whichsquare(number):
print(number)
drawBoard()
mainloop()不涉及位置解码--我们让turtle为我们处理这一点。
https://stackoverflow.com/questions/54816434
复制相似问题