接着上次的继续学习。
每次给游戏添加新功能时,通常也将引入一些新设置。下面来编写一个名为 settings 的模块,其中包含一个名为 Settings 的类,用于将所有设置存储在一个地方,以免在代码中到处添加设置。这样,我们就能传递一个设置对象,而不是众多不同的设置。另外,这让函数调用更简单,且在项目增大时修改游戏的外观更容易:要修改游戏,只需修改 settings.py 中的一些值,而无需查找散布在文件中的不同设置
下面是最初的 Settings 类:
- class Settings():
- '''存储《外星人入侵》的所有设置的类'''
- def __init__(self):
- '''初始化游戏的设置'''
- self.screen_width=1200
- self.screen_height=800
- self.bg_color = (230,230,230)
为创建 Settings 实例并使用它来访问设置,将 alien_invasion.py 修改成下面这样:
- import sys
- from settings import Settings
- from ship import Ship
- import pygame
- def run_game():
- # 初始化游戏并建立一个屏幕对象
- pygame.init()
- # screen = pygame.display.set_mode((1200,800))
- ai_settings=Settings()
- screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
- pygame.display.set_caption("Alien Invasion")
- #开始游戏的主循环
- while True:
- # 监视键盘和鼠标事件
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- sys.exit()
- screen.fill(ai_settings.bg_color)
- # 让最近描绘的屏幕可见
- pygame.display.flip()
- run_game()
二 添加飞船的图像
使用 ship.bm 图片加载飞船:如下图
创建 Ship 类:
- import pygame
- class Ship():
- def __init__(self, screen):
- """初始化飞船并设置其初始位置"""
- self.screen = screen
- # 加载飞船图像并获取其外接矩形
- self.image = pygame.image.load('images/ship.bmp')
- self.rect = self.image.get_rect()
- self.screen_rect = screen.get_rect()
- # 将每艘新飞船放在屏幕底部中央
- self.rect.centerx = self.screen_rect.centerx
- self.rect.bottom = self.screen_rect.bottom
- def blitme(self):
- """在指定位置绘制飞船"""
- self.screen.blit(self.image, self.rect)
注意几个重要的函数:
(1)为加载图像,我们调用了 pygame.image.load()(见)。这个函数返回一个表示飞船的 surface,而我们将这个 surface 存储到了 self.image 中。
(2)加载图像后,我们使用 get_rect() 获取相应 surface 的属性 rect
(3)处理 rect 对象时,可使用矩形四角和中心的 x 和 y 坐标。可通过设置这些值来指定矩形的位置。
(4)在 Pygame 中,原点 (0, 0) 位于屏幕左上角,向右下方移动时,坐标值将增大。在 1200×800 的屏幕上,原点位于左上角,而右下角的坐标为(1200, 800)。
三 在屏幕上绘制飞船
下面更新 alien_invasion.py:
- import sys
- from settings import Settings
- from ship import Ship
- import pygame
- def run_game():
- # 初始化游戏并建立一个屏幕对象
- pygame.init()
- # screen = pygame.display.set_mode((1200,800))
- ai_settings=Settings()
- screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
- pygame.display.set_caption("Alien Invasion")
- # 创建一艘飞船
- ship = Ship(screen)
- #开始游戏的主循环
- while True:
- # 监视键盘和鼠标事件
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- sys.exit()
- screen.fill(ai_settings.bg_color)
- ship.blitme()
- # 让最近描绘的屏幕可见
- pygame.display.flip()
- run_game()
运行之后效果如下图:
来源: http://www.cnblogs.com/majianchao/p/8108880.html