如何在 Tkinter 中将碰撞检测添加到 window 的两侧? [Python 3]

How do I add collision detection to the sides of the window in Tkinter? [Python 3]

我正在用 Tkinter 制作一个简单的游戏,我正在研究基本动作。除了玩家可以离开屏幕外,它运行良好。

如何在 window 的两侧添加碰撞检测?

我正在使用绑定到箭头键的 move 函数移动播放器,如下所示:

def move(event):
    if event.keysym == 'Up':
        self.canvas.move(self.id, 0, -5)
    elif event.keysym == 'Down':
        self.canvas.move(self.id, 0, 5)
    elif event.keysym == 'Left':
        self.canvas.move(self.id, -5, 0)
    else:
        self.canvas.move(self.id, 5, 0)

我假设您想检测矩形与屏幕边缘的碰撞。我对 tkinter 很陌生,但是我有使用 pygame 的经验,让我尽可能地解释一下。

在pygame中,一个矩形的位置被给定为left_top角,a(一侧),b(另一侧)。比如,

(x, y)    b
   ...............
   .             .
   .             .
  a.             .
   .             .
   ...............

如果你想检测碰撞,你必须检查所有的边,使用这些值。

假设屏幕是 (width, height)

# Top side collision
if y < 0:
    print "Touched top"
# Right side collision
if x + b > width:
    print "Touched right"
# Bottom side collision
if y + a > height:
    print "Touched bottom"
# Left side collision
if x < 0:
    print "Touched left"

我很确定 tkinter 也需要非常相似的逻辑。

您可以像这样获得 canvas 的尺码:

size, _ = self.canvas.winfo_geometry().split('+', maxsplit=1)
w, h = (int(_) for _ in size.split('x'))

你的 Squarey 的位置是这样的:

x, y, _, __ = self.canvas.coords(self.id)

(当然还有更好的方法)

然后像这样调整你的运动函数:

if event.keysym == 'Up':
    if y > 0:
        self.canvas.move(self.id, 0, -5)
elif event.keysym == 'Down':
    if y+50 < h:
        self.canvas.move(self.id, 0, 5)
elif event.keysym == 'Left':
    if x > 0:
        self.canvas.move(self.id, -5, 0)
else:
    if x+50 < w:
        self.canvas.move(self.id, 5, 0)

这应该对你有用(至少对我有用)。但是您不应该就此止步,您可以进行一些改进。

我要做的第一个是这样的:

def __init__(self, canvas, color, width=50, height=50):
    self.canvas = canvas
    self.width = width
    self.height = height
    self.id = canvas.create_rectangle(10, 10, width, height, fill=color)

那么你可以改变你的着法:

left_edge = x
right_edge = left_edge + self.width
top_edge = y
bottom_edge = top_edge + self.height

if event.keysym == 'Up' and top_edge > 0:
    ...
elif event.keysym == 'Down' and bottom_edge < h:
    ...
elif event.keysym == 'Left' and left_edge > 0:
    ...
elif event.keysym == 'Right' and right_edge < w:
    ...