Pygame小游戏练习三
@Python编程从入门到实践 Python项目练习
七、创建Passenger类
创建passenger.py文件,创建Passenger类,控制乘客属性和行为
# passenger.py
import pygame
from pygame.sprite import Sprite
class Passenger(Sprite):
"""表示单个乘客的类"""
def __init__(self, ai_settings, screen):
"""初始乘客并设置其起始位置"""
super(Passenger, self).__init__()
self.screen = screen
self.ai_settings = ai_settings
# 加载乘客图像,并设置其rect属性
self.images = [pygame.image.load('images/passenger{}.png'.format(i))
for i in range(1, 9)]
# self.rect = self.images[1].get_rect()
# self.image = pygame.image.load('images/passenger1.bmp')
self.image = pygame.transform.scale(self.images[0], (50, 50))
self.image_squence = 0
self.rect = self.image.get_rect()
# 每个乘客最初都在屏幕左上角附近
self.rect.x = self.rect.centerx - 20
self.rect.y = self.rect.centery - 20
# 存储乘客的准确位置
self.x = float(self.rect.x)
def blitme(self):
"""在指定位置绘制乘客"""
self.image = pygame.transform.scale(self.images[self.image_squence], (50, 50))
self.image_squence += 1
if self.image_squence > 7:
self.image_squence = 0
self.screen.blit(self.image, self.rect)
# self.image = self.images[1]
def check_edges(self):
"""如果外星人位于屏幕边缘,就放回True"""
screen_rect = self.screen.get_rect()
if self.rect.right >= screen_rect.right:
return True
elif self.rect.left <= 0:
return True
def update(self):
"""向右或向左移动外星人"""
self.x += (self.ai_settings.passenger_speed_factor *
self.ai_settings.fleet_direction)
self.rect.x = self.x
八、创建game_stats类
创建game_stats.py,game_stats类用于跟踪游戏统计信息,记录飞机和乘客发生的碰撞
class GameStats():
"""跟踪游戏的统计信息"""
def __init__(self, ai_settings):
"""初始化统计信息"""
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = True
def reset_stats(self):
"""初始化在游戏运行期间可能变化的统计信息"""
self.ships_left = self.ai_settings.ship_limit
企鹅号:1272420336,一起学习,一起进步~