如何在Tkinter中向窗口的两侧添加碰撞检测? [Python 3]

时间:2016-09-01 17:57:12

标签: python tkinter collision-detection python-3.4 tkinter-canvas

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

如何将碰撞检测添加到窗口的两侧?

我正在使用绑定到箭头键的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)

2 个答案:

答案 0 :(得分:1)

您可以像这样获得画布的大小:

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:
    ...

答案 1 :(得分:0)

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

在pygame中,rectange位置为left_top corner,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中也需要非常相似的逻辑。