import pygame
SCREEN_RECT =pygame.Rect(0,0,480,700)
FRAME = 60
class GameSprite(pygame.sprite.Sprite):
'''飞机大战精灵'''
def __init__(self, image, speed=1):
#调用父类的初始化办法
super().__init__()
#定义对象属性
self.image = self.image.load(image)
self.rect =self.image.get_rect()
self.speed = speed
def update(self):
self.rect.y+=self.speed
class BackGound(GameSprite):
'''游戏背景精灵'''
# def __init__(self,is_alt=False):
# super().__init__('./images/images/background.png')
# if is_alt:
# self.rect.y=-self.rect.height
def update(self):
#调用父类方法
super().update()
if self.rect.y>=SCREEN_RECT.height:
self.rect.y=-self.rect.height
import pygame
from 飞机大战tool import *
pygame.init()
#定义飞机大战大类
class PlaneGame(object):
'''飞机大战主游戏'''
#初始化游戏
def __init__(self):
print('游戏初始化')
#创建游戏窗口
self.screen=pygame.display.set_mode(SCREEN_RECT.size)
#创建游戏时钟
self.clock =pygame.time.Clock()
#调用私有方法 创建精灵和精灵组
self.__create_sprites()
def __create_sprites(self):
bg1 = BackGound('./images/images/background.png')
# bg1 = BackGound
# bg2 = BackGound(True)
self.back_group = pygame.sprite.Group(bg1)
def startgame(self):
print('游戏开始了')
while True:
pass
#1设置刷新帧率
self.clock.tick(FRAME)
#2事件监听
self.__eventhandler()
#3碰撞检测
self.__checkcollide()
#4更新绘制精灵
self.__updatesprites()
#5更新显示
pygame.display.update()
def __eventhandler(self):
for event in pygame.event.get():
if event.type ==pygame.QUIT:
PlaneGame.__gameover()
def __checkcollide(self):
pass
def __updatesprites(self):
self.back_group.update()
self.back_group.draw(self.screen)
@staticmethod
def __gameover():
print('游戏结束')
pygame.quit()
exit()
if __name__ == '__main__':
#创建游戏对象
game = PlaneGame()
#启动游戏
game.startgame()
报错:
D:\PycharmProjects\pythonProject\learnpython\venv\Scripts\python.exe D:/PycharmProjects/pythonProject/learnpython/飞机大战/飞机大战实践main.py
pygame 2.0.1 (SDL 2.0.14, Python 3.8.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
游戏初始化
Traceback (most recent call last):
File "D:/PycharmProjects/pythonProject/learnpython/飞机大战/飞机大战实践main.py", line 61, in <module>
game = PlaneGame()
File "D:/PycharmProjects/pythonProject/learnpython/飞机大战/飞机大战实践main.py", line 19, in __init__
self.__create_sprites()
File "D:/PycharmProjects/pythonProject/learnpython/飞机大战/飞机大战实践main.py", line 22, in __create_sprites
bg1 = BackGound('./images/images/background.png')
File "D:\PycharmProjects\pythonProject\learnpython\飞机大战\飞机大战tool.py", line 10, in __init__
self.image = self.image.load(image)
AttributeError: 'BackGound' object has no attribute 'image'
进程已结束,退出代码为 1
pycharm