有一款最伟大的游戏,那就是太空入侵者,它的英文名为space invader。自1978年发售已来,不知被移植,模仿多少遍。游戏的剧情很简单,一群邪恶的异星人,有组织有秩序地排成了一个大方阵,向地球袭来.玩家的目标就是在它们冲到屏幕底端前消灭它们。太空入侵者的成功是空前绝后的。.在日本,机厅里摆放的除了<太空入侵者>还是<太空入侵者>,而生意照样异常火爆。这个游戏甚至导致了日圆硬币的短缺,以致于日本政府不得不将日圆硬币的流通量加大了四倍! 下面只是用海龟画图模块稍微模拟一下。
下面是部分代码预览:
"""
太空入侵者.py
2019年6月17日版。
space invader是一个经典的街机游戏,这里用turtle模块稍微模拟了一下。
本人3年前采用turtle模块,使用面向过程的方法编写过这个游戏。
这是采用面向对象方法,全部重新编程的更新版本。
这一版本的激光威力更大哦,能直接穿透任何物体。
"""
import time
from turtle import Turtle,Screen
from winsound import PlaySound,SND_ASYNC
def write_result(string):
"""当游戏胜利或失败的汉字"""
tmp = Turtle(visible=False)
tmp.penup()
tmp.color("yellow")
tmp.write(string,align='center',font=('',32,'normal'))
class Laser(Turtle):
"""激光类,继承自海龟,实例化后会自行在定时器作用下移动"""
group = []
def __init__(self,position):
pass
def move(self):
"""不断地移动"""
self.fd(10)
class Alien(Turtle):
"""外星飞船类,实例化后会每隔2秒向下移动,超过玩家飞船的坐标
则游戏失败!所有飞船被消灭则游戏成功!
"""
beyond = False
group = []
def __init__(self,image,position,player):
"""image:造型,position:坐标"""
Turtle.__init__(self,shape=image,visible=False)
self.penup()
self.player_top = player.ycor()+25
self.goto(position)
self.st()
self.movedown()
Alien.group.append(self) # 加入到组中
def movedown(self):
"""不断地向下移动"""
class Plane(Turtle):
"""玩家飞船类"""
发射声音='laser.wav'
def __init__(self,image,position,keys):
"""image:造型,position:坐标,keys:按键表"""
pass
def move(self):
"""不断地在水平方向上移动"""
pass
def moveleft(self):
self.dx = -5
def moveright(self):
self.dx = 5
def bounce_on_edge(self):
"""中心点碰到屏幕边缘就反弹"""
if abs(self.xcor()) > self.sw//2:
self.dx = -self.dx
def shoot(self):
"""如果超过上次发射的时间则发射"""
pass
def _delay(self):
"""超时才可以再次发射"""
if time.time() - self.start_time > self.shoot_interval:
self.can_shoot = True
self.screen.onkeypress(self.shoot,self.keys[2])
else:
self.screen.ontimer(self._delay,500)
def main():
width,height = 800,600
screen = Screen()
screen.delay(0)
screen.bgcolor("black")
screen.setup(width,height)
screen.title("太空入侵,海龟画图版,作者:李兴球 www.lixingqiu.com")
战机 = "战机.gif"
screen.addshape(战机)
敌人 = "敌人.gif"
screen.addshape(敌人)
player1 = Plane(战机,(0,50-height//2),("Left","Right","Up"))
# 生成外星人队列
for x in range(50-width//2,width//2,70):
for y in range(height//2-30,00,-50):
Alien(敌人,(x,y),player1)
def collide_check():
"""每隔10毫秒检测激光和外星飞船的碰撞"""
for laser in Laser.group:
for alien in Alien.group:
if laser.distance(alien) < 25:
alien.ht()
for index in range(len(Alien.group)):
alien = Alien.group[index]
if alien.isvisible() == False:
Alien.group.remove(alien)
break
if len(Alien.group) == 0 :
write_result("成功!")
return
screen.ontimer(collide_check,10)
collide_check()
screen.listen()
screen.mainloop()
if __name__ == "__main__":
main()
下载完整源代码与素材,请
需要浏览更多吗?
成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)

