所以我是蟒蛇新手,我用一个对你不利的艾来编写了一个tic tac toe。所以一切正常,但我使用文本框告知Ai玩家选择了什么。现在我想升级我的游戏,以便玩家可以点击他想要填充的Box,而不是在文本框中输入。所以我的想法是使用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
做一些事情,因为我如果用return 1
替换print("1")
它的工作原理。我假设变量被快速定义。我的第二个问题是,如果它可能暂停程序直到玩家点击一个盒子,但更重要的是首先看第一个问题。提前致谢:)
假设您已经在龟模块中命名了Screen(),那么您应该放置
screen.onscreenclick(whichbox)
代替:
onscreenclick(whichbox)
例:
from turtle import Turtle, Screen
turtle = Turtle()
screen = Screen()
def ExampleFunction():
return 7
screen.onscreenclick(ExampleFunction)
此外,当他说onscreenclick()函数无法返回任何值时,jasonharper是正确的。因此,您可以在函数whichbox()中包含打印功能,以便打印出一个值,例如:
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函数,它将onscreenclick()的(x,y)赋予包含whichbox()的print语句。
这是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()
没有涉及位置解码 - 我们让乌龟为我们处理。