我正在尝试在python中创建Connect 4,但我无法弄清楚如何获取屏幕的坐标点击以便我可以使用它们。现在,我想画板,然后有人点击,画一个点,然后回到while循环的顶部,擦拭屏幕再试一次。我尝试了几种不同的选择,但似乎没有一种方法适合我。
def play_game():
"""
When this function runs, allows the user to play a game of Connect 4
against another person
"""
turn = 1
is_winner = False
while is_winner == False:
# Clears screen
clear()
# Draws empty board
centers = draw_board()
# Decides whose turn it is, change color appropriately
if turn % 2 == 0:
color = RED
else:
color = BLACK
# Gets coordinates of click
penup()
onscreenclick(goto)
dot(HOLE_SIZE, color)
turn += 1
答案 0 :(得分:1)
与其他答案一样善意,我也不相信解决实际问题。您通过在代码中引入无限循环来锁定事件:
is_winner = False
while is_winner == False:
您无法使用乌龟图形执行此操作 - 您设置了事件处理程序和初始化代码,但将控制权交给主循环事件处理程序。我的以下返工显示了您可能会这样做:
import turtle
colors = ["red", "black"]
HOLE_SIZE = 2
turn = 0
is_winner = False
def draw_board():
pass
return (0, 0)
def dot(color):
turtle.color(color, color)
turtle.stamp()
def goto(x, y):
global turn, is_winner
# add code to determine if we have a winner
if not is_winner:
# Clears screen
turtle.clear()
turtle.penup()
# Draws empty board
centers = draw_board()
turtle.goto(x, y)
# Decides whose turn it is, change color appropriately
color = colors[turn % 2 == 0]
dot(color)
turn += 1
else:
pass
def start_game():
"""
When this function runs, sets up a new
game of Connect 4 against another person
"""
global turn, is_winner
turn = 1
is_winner = False
turtle.shape("circle")
turtle.shapesize(HOLE_SIZE)
# Gets coordinates of click
turtle.onscreenclick(goto)
start_game()
turtle.mainloop()
运行它,您将看到所描述的所需行为。
答案 1 :(得分:0)
我假设您在python中使用 Turtle (因此名称。) 如果是这种情况,请点击以下链接:Turtle in python- Trying to get the turtle to move to the mouse click position and print its coordinates 我知道我知道。我讨厌只是链接答案和下一个人一样多。但是我发布链接的帖子可能会比我能更好地回答你的问题。
〜Mr.Python
答案 2 :(得分:0)
假设您正在使用标题中提到的turtle
:
>>> import turtle
>>> help(turtle.onscreenclick)
Help on function onscreenclick in module turtle:
onscreenclick(fun, btn=1, add=None)
Bind fun to mouse-click event on canvas.
Arguments:
fun -- a function with two arguments, the coordinates of the
clicked point on the canvas.
num -- the number of the mouse-button, defaults to 1
Example (for a TurtleScreen instance named screen)
>>> onclick(goto)
>>> # Subsequently clicking into the TurtleScreen will
>>> # make the turtle move to the clicked point.
>>> onclick(None)
这意味着您的回调函数(显然名为goto
)将采用两个参数,即X和Y位置。
import turtle
def goto(x, y):
print('Moving to {}, {}'.format(x,y))
turtle.goto(x, y)
turtle.onscreenclick(goto)
turtle.goto(0,0)
您所做的每次点击都会将乌龟移动到其他位置。请注意turtle
已经有一个事件循环 - 您不需要自己的一个。只需回复点击次数。