首页 > 解决方案 > 如何在画布突破游戏中正确设置边界?

问题描述

我正在画布 tkinter 中进行游戏突破,但是当我设置条件来做 baundaries 时,托盘不会移动。如何正确写出它移动的语句?

from tkinter import *
root = Tk()
root.title("Move Objects in canvas")

root.resizable(False,False)
height = 500
width = 700
x = width//2
y= height//2
can = Canvas(height = height, width=width,bg = "blue")
can.pack(pady = 30,padx=50)

rect = can.create_rectangle(height//2,700,width//2,490,fill = "green")



def keypress(event):
    x,y = 0,0
    if event.char == "a" and x > x: 
        x= -10
    if event.char == "d" and x < 700 - width -x:
        x= 10
    can.move(rect,x,y)

root.bind("<Key>", keypress)
root.mainloop()

标签: pythontkinter

解决方案


为此,请获取矩形的坐标并检查边界:

from tkinter import *
root = Tk()
root.title("Move Objects in canvas")

root.resizable(False,False)
height = 500
width = 700
x = width//2
y= height//2
can = Canvas(height = height, width=width,bg = "blue")
can.pack(pady = 30,padx=50)

rect = can.create_rectangle(height//2,700,width//2,490,fill = "green")



def keypress(event):
    x1 = can.coords(rect)[0]
    x2 = can.coords(rect)[2]
    if event.char == "a" and x1 > 0: 
        x= -10
    if event.char == "d" and x2 < 700:
        x= 10
    try:
        can.move(rect,x,0)
    except UnboundLocalError:
        print('out of bounderies')

root.bind("<Key>", keypress)
root.mainloop()

我还添加了一个 try 和 except 块来显示它何时超出边界。如果有任何问题或错误,请告诉我。


推荐阅读