Skip to content

Commit d28691e

Browse files
committed
[学习内容]外星人入侵项目实践
1.创建游戏窗口 2.创建飞船类和方法 3.初始化游戏
0 parents  commit d28691e

File tree

4 files changed

+79
-0
lines changed

4 files changed

+79
-0
lines changed

alien_invasion.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#coding: utf-8
2+
3+
4+
import sys
5+
import pygame
6+
from settings import Settings
7+
from ship import Ship
8+
9+
10+
def run_game():
11+
"""初始化游戏并创建一个屏幕对象"""
12+
pygame.init()
13+
ai_settings = Settings()
14+
scrren = pygame.display.set_mode((ai_settings.scrren_width, ai_settings.scrren_height))
15+
pygame.display.set_caption("Alien Invasion")
16+
17+
# 设置背景颜色
18+
bg_color = (230, 230, 230)
19+
20+
# 创建一艘飞船
21+
ship = Ship(scrren)
22+
23+
# 开始游戏的主循环
24+
while True:
25+
26+
# 监视键盘和鼠标事件
27+
for event in pygame.event.get():
28+
if event.type == pygame.QUIT:
29+
sys.exit()
30+
31+
# 每次循环时都重绘屏幕
32+
scrren.fill(ai_settings.bg_color)
33+
ship.blitme()
34+
35+
# 让最近绘图的屏幕可见
36+
pygame.display.flip()
37+
38+
39+
print run_game.__doc__
40+
run_game()
41+
42+

settings.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# coding: utf-8
2+
3+
4+
class Settings():
5+
"""存储《外星人入侵》的所有设置的类"""
6+
7+
def __init__(self):
8+
"""初始化游戏设置"""
9+
10+
# 屏幕设置
11+
self.scrren_width = 1200
12+
self.scrren_height = 800
13+
self.bg_color = (100, 100, 100)
14+
15+

ship.png

2.46 KB
Loading

ship.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# coding: utf-8
2+
3+
import pygame
4+
5+
6+
class Ship():
7+
8+
def __init__(self, scrren):
9+
"""初始化飞船并设置其初始位置"""
10+
self.scrren = scrren
11+
self.image = pygame.image.load('ship.png')
12+
self.rect = self.image.get_rect()
13+
self.scrren_rect = scrren.get_rect()
14+
15+
# 将每艘飞船防止在屏幕底部中央
16+
self.rect.centerx = self.scrren_rect.centerx
17+
self.rect.bottom = self.scrren_rect.bottom
18+
19+
def blitme(self):
20+
"""在指定位置放置飞船"""
21+
self.scrren.blit(self.image, self.rect)
22+

0 commit comments

Comments
 (0)