如果 canvas 对象到达某个坐标,如何设置 if 语句? tkinter

How to set an if statement if a canvas object reaches a certain coordinate? tkinter

我正在用 tkinter 制作蛇游戏,如果蛇碰到 window,我会尝试打印一条 'game over' 消息。我该怎么做?

这是我到目前为止得到的:

from tkinter import *
# import random, disregard random module, unused

def up(event):
    canvas.move(snakebody, 0, -20)

def down(event):
    canvas.move(snakebody, 0, 20)

def left(event):
    canvas.move(snakebody, -20, 0)

def right(event):
    
    canvas.move(snakebody, 20, 0)

# root
window = Tk()

window.config(bg='darkgreen')
window.geometry('450x450')
window.resizable(0, 0)

# canvas
canvas = Canvas(window, bg='darkgreen', borderwidth=0)
canvas.pack(fill=BOTH, expand=1)

# snake body/head
snakebody = canvas.create_rectangle(100, 50, 50, 100, outline='lightgreen', fill='lightgreen')

# game over message
if canvas.coords(snakebody) == canvas.coords(snakebody, 50, 50, 100, 100):
    print('game over')

# control binds
window.bind('<Up>', up)
window.bind('<Down>', down)
window.bind('<Left>', left)
window.bind('<Right>', right)

window.mainloop()

请帮忙

我认为你的问题现在为时过早。您之前需要回答不同的问题。你的动作决不允许蛇 咬伤 自己。你的蛇也不会在拐角处移动。因此,您很可能必须更改该功能。无论如何,向您展示我在评论部分提到的概念。

我实现了一个名为 after_tick() 的函数。在函数内部,我通过询问 canvas 的 属性 来定义从 (0,0) = 左上角开始的边界以及宽度和高度的最大坐标。之后我向 canvas 询问这个 box 里面的物品,如果 snakebody 的 id 不在里面,打印 game over.

补充建议:

  • 实现一个功能tick,tick 通常是自动化的下一步
  • 为你的蛇使用多个矩形并为头部和 body
  • 使用标签
  • 不要使用通配符导入以避免名称冲突

from tkinter import *

def after_tick():
    max_w = canvas.winfo_width()
    max_h = canvas.winfo_height()
    in_cnvs = canvas.find_enclosed(0,0,max_w,max_h)
    if snakebody not in in_cnvs:
        print('game over')    

def move_event(event):
    key = str(event.keysym)
    if key == 'Up':
        canvas.move(snakebody, 0, -20)
    elif key == 'Down':
        canvas.move(snakebody, 0, 20)
    elif key == 'Left':
        canvas.move(snakebody, -20, 0)
    elif key == 'Right':
        canvas.move(snakebody, 20, 0)
    after_tick()


window = Tk()
window.config(bg='darkgreen')
window.geometry('450x450')
window.resizable(0, 0)

canvas = Canvas(window, bg='darkgreen', borderwidth=0)
canvas.pack(fill=BOTH, expand=1)

snakebody = canvas.create_rectangle(100, 50, 50, 100,
                                    outline='lightgreen',
                                    fill='lightgreen')

window.bind('<Up>', move_event)
window.bind('<Down>', move_event)
window.bind('<Left>', move_event)
window.bind('<Right>', move_event)

window.mainloop()