python - 如何在画布突破游戏中正确设置边界?
问题描述
我正在画布 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()
解决方案
为此,请获取矩形的坐标并检查边界:
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 块来显示它何时超出边界。如果有任何问题或错误,请告诉我。
推荐阅读
- javascript - 如何使用 Javascript 总共添加 10% 的折扣
- java - 如何使用java获取soapUI(Ready-API)测试覆盖率结果?
- html - 左边的前两个 div(一个在另一个下面)和右边的最后一个使用 Flexbox
- reactjs - 在 React 组件中以不断增加的速度调用 setInterval?
- arrays - 如何在不描述结构的情况下创建数组?
- python - 是否有类似于 tf.cond 但用于向量谓词的东西?
- docker - 运行 npm run start 时如何禁止 npm 自行升级?
- javascript - 我想将递归函数的结果附加到对象的子节点
- r - R:如何将多个 txt 文件合并到一个表格中,每个 txt 文件为一个“单元格”?
- android - 安卓车载蓝牙连接