【发布时间】:2021-08-09 18:33:03
【问题描述】:
import pygame
class Ship:
"""A class to manage the ship."""
def __init__(self, ai_game):
"""Initialize the ship and see its starting position."""
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
self.settings = ai_game.settings
# Load the ship image and get its rect.
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
# Start each ship at the bottom centre of the screen
self.rect.midbottom = self.screen_rect.midbottom
# Store a decimal value for the ship's horizontal position
self.x = float(self.rect.x)
# Movement flag
self.moving_right = False
self.moving_left = False
def update(self):
""""Update the ship's position based on movement flag."""
# Update the ship's x value and not the rect.
if self.moving_right and self.rect.right < self.screen_rect.right:
self.x += self.settings.ship_speed
if self.moving_left and self.rect.left > 0:
self.x -= self.settings.ship_speed
# Update rect object from self.x
self.rect.x = self.x
def blitme(self):
"""Draw the ship at the current location."""
self.screen.blit(self.image, self.rect)
在update 方法中,我们声明了if 语句,以便飞船停留在屏幕的边界内。但是为什么要验证self.rect.left > 0?这表达了什么?
【问题讨论】:
-
像你说的那样,为了防止飞船移动到屏幕左边框之外?
-
不,我的意思是 self.rect.left 的值 > 0 如何阻止它?你能详细解释一下吗?我无法理解它背后的逻辑。 self.rect.left 给出了船矩形左边缘的坐标。但是为什么我们只比较它大于 0 呢?屏幕最左边的坐标不是0,为什么要和0比较?
-
我假设屏幕的左边框为0。如果这不是真的,那我不知道。
-
据我所知,在 pygame 中,原点 (0,0) 位于屏幕的左上角。
-
那为什么你认为0不是最左边的坐标呢?
标签: python python-3.x pygame game-development rect