Python 速成班第 2 版练习 12-4

Python Crash Course 2nd Edition exercise 12-4

有3个文件。 rocket_game.py、rocket.py、settings.py。 rocket.py 的内容。 键“向上”箭头什么都不做。键“向下”箭头将船向上移动。 如果我将最后一行更改为“self.y += self.settings.ship_speed”,向下箭头会使船向下移动。但是为什么游戏不勾上向上箭头呢?

def update(self):
    """Update the ship's position based on the moving flag."""

    if self.moving_right and self.rect.right < self.screen_rect.right:
        self.x += self.settings.ship_speed
    elif self.moving_left and self.rect.left > 0:
        self.x -= self.settings.ship_speed
    if self.moving_up and self.rect.top < self.screen_rect.top:
        self.y += self.settings.ship_speed
    elif self.moving_down and self.rect.bottom > 0:
        self.y -= self.settings.ship_speed

“向上”键没有任何作用。键“向下”箭头将船向上移动。 如果我更改 self.y += self.settings.ship_speed,向下箭头会使船向上移动,我明白为什么。但是为什么向上箭头没有?

如果我打印事件,它会看到我按下了向上箭头,但火箭没有移动。

另一个问题,顶部和底部边界似乎不存在。

屏幕左下角分别描述为坐标0、0。我确实尝试将底部边界设置为 0,但船仍然在屏幕下方飞行。左右边界工作正常。 python 编程的新手,我尝试阅读 pygame API for rect 但它似乎没有我需要的参考。它确实列出了顶部和底部而不是向上和向下。 我在 rocket_game.py 和 rocket.py.

中尝试了多种方法

没有错误消息,最终目标是添加在 screen_rect 边界内上下左右移动的功能。

在pygame坐标系中,top左坐标为(0, 0),bottom右为(宽度, 高度).
改变移动方向和阻止物体移出屏幕的条件:

if self.moving_up and self.rect.top > 0:
    self.y -= self.settings.ship_speed
elif self.moving_down and self.rect.botom < self.screen_rect.bottom:
    self.y += self.settings.ship_speed