class HeroPlane(pygame.sprite.Sprite): def __init__(self,screen): pygame.sprite.Sprite.__init__(self) #初始化精灵类 self.image1 = pygame.image.load("D:/PYTHON/pointgame/hero1.jpg") self.rect = self.image1.get_rect() #获取图片大小 self.rect.topleft = [300,700] #获取飞机左上角坐标 self.speed = 10 # 飞机速度 self.screen = screen self.screen_rect = self.screen.get_rect() self.bullets = pygame.sprite.Group() #group方法 类似列表 def key_control(self): # 键盘输入 key_pressed = pygame.key.get_pressed() if key_pressed[K_w] or key_pressed[K_UP]: self.rect.top -= self.speed if key_pressed[K_s] or key_pressed[K_DOWN]: self.rect.bottom += self.speed if key_pressed[K_a] or key_pressed[K_LEFT]: self.rect.left -= self.speed if key_pressed[K_d] or key_pressed[K_RIGHT]: self.rect.right += self.speed if key_pressed[K_SPACE]: bullet = Bullet(self.screen,self.rect.left,self.rect.top) #飞机参数调用 self.bullets.add(bullet) #把子弹放入列表 if self.rect.left < 0:# 控制player不能离开屏幕 self.rect.left = 0 elif self.rect.right > self.screen.rect.right: self.rect.right = self.screen.rect.right 错误是 File "D:/PYTHON/pointgame/pointgame.py", line 124, in <module> main() File "D:/PYTHON/pointgame/pointgame.py", line 117, in main player.key_control() File "D:/PYTHON/pointgame/pointgame.py", line 33, in key_control elif self.rect.right > self.screen.rect.right: AttributeError: 'pygame.surface.Surface' object has no attribute 'rect'怎么修改
时间: 2024-02-19 22:00:08 浏览: 167
问题出在第21行,应该将`self.screen_rect = self.screen.get_rect()`改为`self.screen_rect = self.screen.get_rect()`,即将`screen`改为`screen_rect`。代码如下:
```
class HeroPlane(pygame.sprite.Sprite):
def __init__(self,screen):
pygame.sprite.Sprite.__init__(self) #初始化精灵类
self.image1 = pygame.image.load("D:/PYTHON/pointgame/hero1.jpg")
self.rect = self.image1.get_rect() #获取图片大小
self.rect.topleft = [300,700] #获取飞机左上角坐标
self.speed = 10 # 飞机速度
self.screen = screen
self.screen_rect = self.screen.get_rect()
self.bullets = pygame.sprite.Group() #group方法 类似列表
def key_control(self):
# 键盘输入
key_pressed = pygame.key.get_pressed()
if key_pressed[K_w] or key_pressed[K_UP]:
self.rect.top -= self.speed
if key_pressed[K_s] or key_pressed[K_DOWN]:
self.rect.bottom += self.speed
if key_pressed[K_a] or key_pressed[K_LEFT]:
self.rect.left -= self.speed
if key_pressed[K_d] or key_pressed[K_RIGHT]:
self.rect.right += self.speed
if key_pressed[K_SPACE]:
bullet = Bullet(self.screen,self.rect.left,self.rect.top) #飞机参数调用
self.bullets.add(bullet) #把子弹放入列表
if self.rect.left < 0:# 控制player不能离开屏幕
self.rect.left = 0
elif self.rect.right > self.screen_rect.right: # 修改这行
self.rect.right = self.screen_rect.right
```
这样应该就能解决报错问题了。
阅读全文