模仿如下:
import sys
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion:
#管理游戏资源和行为的类
def __init__(self):
#初始化游戏并创建游戏资源
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode(
(self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Alien Invasion")
self.ship = Ship(self)
#设备背景色
self.bg_color = (230, 230, 230)
def run_game(self):
#开设游戏的主循环
while True:
self._check_events()
self._update_screen()
#让最近绘制的屏幕可见
pygame.display.flip()
def _check_events(self):
#响应按键和鼠标事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
def _update_screen(self):
#更新屏幕上的图像,并切换到新屏幕
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
pygame.display.flip()
if __name__ == '__main__':
#创建游戏实例并运行游戏
ai = AlienInvasion()
ai.run_game()
自己的如下:
import sys
import pygame
from fish import Fish
class Bulesky:
"""管理游戏的类"""
def __init__(self):
"""初始化并创建资源"""
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption('Bulesky')
self.bg_color = (0, 0, 250)
self.fish = Fish(self)
def run_game(self):
"""开始游戏"""
while True:
#监视游戏行为
self._check_events()
self._update_screen()
#让最近绘制的屏幕可见
pygame.display.flip()
def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
def _update_screen(self):
"""更新屏幕上的图像,并切换屏幕"""
self.screen.fill(self.bg_color)
self.fish.blitme()
pygame.display.flip()
if __name__ =='__main__':
ai = Bulesky()
ai.run_game()
报错
pygame 2.1.2 (SDL 2.0.18, Python 3.9.0)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "E:\12-1\Bulesky.py", line 48, in <module>
ai.run_game()
File "E:\12-1\Bulesky.py", line 26, in run_game
self._update_screen()
File "E:\12-1\Bulesky.py", line 41, in _update_screen
self.fish.blitme()
AttributeError: 'Fish' object has no attribute 'blitme'
[Finished in 2.6s]
期望结果: