用户:
码客_CoderGroup查看:0 回复:0 评论:0 创建时间:2021-01-10T13:48:37
【作品展示】

【作品介绍】
玩一玩海龟之星际迷航吧!
【作品源代码】
import pgzrun
import random
import math
WIDTH = 450
HEIGHT = 650
score = 0
game_state = 'start'
# 钻石下落速度
speed = 6
# 飞船是否发喵弹
shoot = False
t = 0
spaceship = Actor('spaceship', (200, 550))
diamond = Actor('diamond', (100, -200))
enermy = Actor('enermy2', (300, -200))
bullet = Actor('bullet', (200, -100))
def draw():
global game_state, shoot, score
# 设置开始画面
if game_state == 'start':
screen.blit('space', (0, 0))
screen.draw.text('Spacecraft', (115, 260), fontsize=60)
screen.draw.text('Press SPACE to start!',
(85, 320), fontsize=40)
if keyboard.space:
game_state = 'play'
# 循环播放背景音乐
sounds.bg_music.play(-1)
# 游戏开始后,显示角色和得分
elif game_state == 'play':
screen.blit('space', (0, 0))
screen.draw.text('score: ' + str(score),
(10, 10), fontsize=30)
spaceship.draw()
diamond.draw()
enermy.draw()
bullet.draw()
# 显示游戏结束画面
else:
screen.blit('space', (0, 0))
spaceship.draw()
sounds.bg_music.stop() # 停止音乐
screen.draw.text('GAME OVER!', (90, 230),
color='red', fontsize=60)
screen.draw.text('Your score: ' + str(score),
(125, 280), fontsize=40)
screen.draw.text('Press SPACE to restart!',
(70, 320), fontsize=40)
# 按下空格键,重新开始游戏
if keyboard.space:
game_state = 'play'
place_object(enermy)
place_object(diamond)
sounds.bg_music.play(-1)
score = 0
# 重置角色位置
def place_object(obj):
obj.x = random.randint(20, WIDTH - 20)
obj.y = random.randint(-200, -40)
def update():
global score, game_state, shoot, t
if game_state == 'play':
# 让飞船以正弦轨迹移动
enermy.y += speed - 3
enermy.x = WIDTH / 2 * (1 + math.sin(t))
t += 0.02
diamond.y += speed
# 如果敌机或钻石移出屏幕,重置它们的位置
if enermy.y > HEIGHT + 100:
place_object(enermy)
if diamond.y > HEIGHT + 100:
place_object(diamond)
# 左右键控制飞船左右移动
if keyboard.left:
spaceship.x -= 5
elif keyboard.right:
spaceship.x += 5
if spaceship.x < 0:
spaceship.x = 0
elif spaceship.x > WIDTH:
spaceship.x = WIDTH
# 按 A 键发喵弹
if keyboard.a:
shoot = True
sounds.bullet.play()
# 将炮弹移到飞船附近
init_pos = spaceship.x, spaceship.y - 60
bullet.pos = init_pos[0], init_pos[1]
if shoot:
if bullet.y > -20:
bullet.y -= 10
else:
shoot = False
bullet.x = -160
# 如果敌机被炮弹击中,敌机重置位置,得分增加
if enermy.collidepoint(bullet.pos):
place_object(enermy)
score += 10
if spaceship.collidepoint(diamond.pos):
place_object(diamond)
sounds.powerup.play()
score += 10
# 如果飞船碰到敌机,游戏结束
if spaceship.collidepoint(enermy.pos):
sounds.hit.play()
game_state = 'game over'
pgzrun.go()
【提示】
部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:
https://python.codemao.cn