猿问

蟒龟井字游戏

所以我是 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因为 i 如果return 1用print("1")它替换它可以工作。我假设变量被定义得很快。我的第二个问题是是否有可能暂停程序直到玩家点击一个框,但首先看看第一个问题更重要。提前致谢:)


郎朗坤
浏览 175回答 2
2回答

犯罪嫌疑人X

假设您已经在海龟模块中命名了 Screen(),那么您应该将screen.onscreenclick(whichbox)代替:onscreenclick(whichbox)例子:from turtle import Turtle, Screenturtle = Turtle()screen = Screen()def ExampleFunction():&nbsp; &nbsp; return 7screen.onscreenclick(ExampleFunction)此外,当 jasonharper 说 onscreenclick() 函数无法返回任何值时,他是正确的。因此,您可以在函数 whichbox() 中包含一个打印函数以打印出一个值,例如:def whichbox(x,y):&nbsp;&nbsp; &nbsp; if x<-40 and x>-120:&nbsp; &nbsp; &nbsp; &nbsp; if y>40 and y<120:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 1&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print(0)&nbsp; &nbsp; &nbsp; &nbsp; return 0或者,如果您想将打印语句保留在 whichbox() 之外,您还可以执行以下操作:screen.onscreenclick(lambda x, y: print(whichbox(x, y)))它创建了一个 lambda 函数,该函数将 (x, y) 从 onscreenclick() 提供给包含 whichbox() 的打印语句。

qq_花开花谢_0

这是我在评论中链接到的代码中的一个精简示例。如果您单击一个方块,它将在控制台窗口中打印其编号,从 0 到 8:from turtle import Turtle, mainloopCURSOR_SIZE = 20SQUARE_SIZE = 60def drawBoard():&nbsp; &nbsp; for j in range(3):&nbsp; &nbsp; &nbsp; &nbsp; for i in range(3):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; square = Turtle('square', visible=False)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; square.shapesize(SQUARE_SIZE / CURSOR_SIZE)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; square.fillcolor('white')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; square.penup()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; square.goto((i - 1) * (SQUARE_SIZE + 2), (j - 1) * (SQUARE_SIZE + 2))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; number = j * 3 + i&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; square.onclick(lambda x, y, number=number: whichsquare(number))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; square.showturtle()def whichsquare(number):&nbsp; &nbsp; print(number)drawBoard()mainloop()不涉及位置解码——我们让乌龟为我们处理。
随时随地看视频慕课网APP

相关分类

Python
我要回答