外星人入侵保卫家园游戏计划:
屏幕底部会出现飞船,玩家通过左右箭头控制飞船,空格键发射子弹。
屏幕上方不断有敌人入侵,玩家需要歼灭入侵者保护家园。
如果敌人到达了地面,则游戏失败退出。
开始配置
编码之前,首先要安装 Pygame
python3 -m pip install --user pygame
Collecting pygame
Downloading https://files.pythonhosted.org/packages/32/37/453bbb62f90feff2a2b75fc739b674319f5f6a8789d5d21c6d2d7d42face/pygame-1.9.6-cp37-cp37m-macosx_10_11_intel.whl (4.9MB)
|████████████████████████████████| 4.9MB 6.4MB/s
Installing collected packages: pygame
Successfully installed pygame-1.9.6
安装成功后便可以开始写代码,首先写一个空的窗口来展示这个游戏,新建文件 alien_invasion.py
import sys
import pygame
class AlienInvasion:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Alien Invasion")
def run_game(self):
while True:
for event in pygame.event.get()
if event.type == pygame.QUIT:
sys.exit()
pygame.display.flip()
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
总共16行代码:
前两行,我们引入 sys 和 pygame 模块,pygame 模块里包含了我们创造游戏要用到的方法,sys 模块帮助我们退出游戏。
第3行 我们定义一个类 AlienInvasion
第4-7行到在类的初始化方法__init__里,设置游戏的背景和标题,随后在第6行设置的背景上我们会添加其他的游戏元素。参数 (1200, 800) 是一个tuple类型,表示长1200pixel 宽800pixel
新建设置类
设置类是管