python-3.x - 嘿,我不能在我的 pygame 程序中使用 midbottom 函数。每次我运行我的程序时,我都会在左下角看到我的 rect 对象
问题描述
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()
# Store a decimal value for the ship's horizontal position
self.x = float(self.rect.x)
# Start each ship at the bottom centre of the screen
self.rect.midbottom = self.screen_rect.midbottom
# 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)
这是 ai_game 是主类的实例的代码。每次我运行我的代码时,我都会在屏幕的左下角看到我的 rect 对象,而 midbottom 函数应该将我的 rect 对象(即此处的船)放在屏幕的中下部分
解决方案
设置是不够的self.rect.midbottom = self.screen_rect.midbottom
。您还需要self.x
设置self.screen_rect.centerx
self.rect.midbottom = self.screen_rect.midbottom
self.x = self.screen_rect.centerx
请注意,在update
方法中, self.rect.x
由 设置self.x
。因此self.x
需要正确初始化属性
如果您不需要浮点精度,则可以完全删除该self.x
属性并slef.rect.centerx
改用。
类Ship
:
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
# 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.centerx += self.settings.ship_speed
if self.moving_left and self.rect.left > 0:
self.centerx -= self.settings.ship_speed
def blitme(self):
"""Draw the ship at the current location."""
self.screen.blit(self.image, self.rect)
推荐阅读
- javascript - 用 JavaScript 填充 CSS 网格
- java - 处理:使用四元数旋转 3D 对象适用于 x 轴,但不适用于 y 或 z 轴?
- c - 使用 char 数据类型打印字符
- python-3.x - python3字节构造添加杂散字节
- android - Android:使用命令 --prod:语句不起作用
- c# - Xamarin Froms Android 手机摄像头无法打开
- r - 重复将相同的命令应用于 R 中的许多变量
- excel - 编译错误帮助并在用户窗体上居中标题
- batch-file - 在 .CMD 中格式化结果
- mysql - 如何将 mysql 数据库内容传递到不同的页面?