【问题标题】:Limiting the ship's range in alien invasion [closed]在外星人入侵中限制船的范围[关闭]
【发布时间】: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 &gt; 0?这表达了什么?

【问题讨论】:

  • 像你说的那样,为了防止飞船移动到屏幕左边框之外?
  • 不,我的意思是 self.rect.left 的值 > 0 如何阻止它?你能详细解释一下吗?我无法理解它背后的逻辑。 self.rect.left 给出了船矩形左边缘的坐标。但是为什么我们只比较它大于 0 呢?屏幕最左边的坐标不是0,为什么要和0比较?
  • 我假设屏幕的左边框为0。如果这不是真的,那我不知道。
  • 据我所知,在 pygame 中,原点 (0,0) 位于屏幕的左上角。
  • 那为什么你认为0不是最左边的坐标呢?

标签: python python-3.x pygame game-development rect


【解决方案1】:

屏幕左边缘为水平0位置。

如果从 10 开始绘制一些东西,那么它将非常靠近左边缘。

如果从 0 开始绘制,则图像的左边缘将与屏幕的左边缘完美对齐。

如果从 0 以下开始绘制某些内容,则意味着它部分(或全部)在屏幕外绘制。

if self.moving_left and self.rect.left > 0:
    self.x -= self.settings.ship_speed

在第二行,我们将船进一步向左移动。但是,如果船已经在屏幕的左边缘,我们不想这样做,因为那样它就会离开屏幕。因此,在我们移动船之前,会检查船是否比屏幕的左边缘更靠右。如果是这样,将船移到左侧是安全的。

值得注意的是,这段代码不是完成这项任务的好方法,但这就是代码的意图。

另一种你可以理解的方式:删除线的那部分,然后玩游戏。您可以将飞船移出屏幕左侧。

【讨论】:

  • Tysm @Robson 现在知道了!
猜你喜欢
  • 2020-10-22
  • 2022-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多