
在太空中,飞船飞速地向前飞行,但小心不要碰到了陨石!如果碰到了则会粉身碎骨。这是为了教学目的而开发的一个小游戏。它采用了Python精灵模块开发。在程序中主要有三个角色,一个是star,其实代表的障碍物。另一个是plane,即玩家操作的飞机。star会盖几十个图章。这些图章不断地向下运动,从而衬托了飞机向上飞的效果。还有一个用于显示秒数的miao角色。当然,本程序需要sprites模块支持,请用cmd命令打开管理员窗口,输入pip install sprites进行安装。以下是星空避障游戏所有代码:
"""
动态星空_显示秒数.py
练习: 请把星星改成从右边出来,向左移动,而飞机则在左边,朝右
"""
import time
from sprites import *
star = Sprite('star')
star.scale(0.1)
star.color('white')
screen = star.getscreen()
screen.setup(480,360)
screen.bgcolor('black')
screen.title('星空避障游戏')
for x in range(30): # 盖30个图章
star.gotorandom(-240,240,180,540) # 在这个范围内盖图章
star.stamp() # 正式盖图章
plane = Sprite('res/thunder.png') # 新建飞船角色
plane.scale(0.2) # 缩小比例
upk = Key("Up") # 向上方向箭头
downk = Key("Down")
rightk = Key("Right")
leftk = Key("Left")
screen.listen()
exp = ['res/explosion0.png','res/explosion1.png']# 爆炸效果要用到的图片
miao = Sprite(visible=False,pos=(0,100))# 显示时间的miao角色
miao.color('white')
mmm = 0
ft = ('',44,'normal')
start_time = time.time()
miao.write(mmm,align='center',font=ft)
while True:
# 这一段是显示程序运行的时间的
if time.time() - start_time>=1:
miao.clear()
miao.write(mmm,align='center',font=ft)
mmm += 1
start_time = time.time()
for st in star.stampItems: # 每一个图章
star.movestamp(st,0,-1) # 移动st这个图章
x,y = star.stampcors(st) # 获取st的坐标
# 如果st的y坐标小于-180则移到最上面
x = random.randint(-240,240)
if y<= -180:star.stampgoto(st,x,180)
if upk.down():plane.addy(1) # 如果按了向上方向箭头,飞船y坐标增加1
if downk.down():plane.addy(-1)
if rightk.down():plane.addx(1)
if leftk.down():plane.addx(-1)
item = plane.find_overlapping() # 查找和飞机有没有重叠的项目
if item: # 如果有,则表示飞机碰到了星星
explode(plane,exp) # 显示爆炸效果
plane.hide() # 飞机隐藏
break # 中断循环
screen.update()
