飞机大战带积分关卡的pyhton代码
时间: 2023-09-21 19:08:27 浏览: 81
飞机大战Python代码
好的,以下是一个简单的飞机大战游戏的Python代码,它包含了积分和关卡系统:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏界面大小、背景颜色
screen = pygame.display.set_mode((480, 700))
pygame.display.set_caption('飞机大战')
bg_color = (230, 230, 230)
# 加载图片
bg_img = pygame.image.load('background.png')
player_img = pygame.image.load('player.png')
bullet_img = pygame.image.load('bullet.png')
enemy_img = pygame.image.load('enemy.png')
# 设置字体
font = pygame.font.SysFont('arial', 24)
# 飞机初始位置
player_pos = [200, 600]
player_speed = 5
player_score = 0
# 子弹初始位置
bullet_pos = []
bullet_speed = 10
# 敌人初始位置
enemy_pos = []
enemy_speed = 2
# 创建敌人
def create_enemy():
enemy_x = random.randint(0, 400)
enemy_y = random.randint(0, 50)
enemy_pos.append([enemy_x, enemy_y])
# 移动子弹和敌人
def move_bullet_enemy():
for i in range(len(bullet_pos)):
bullet_pos[i][1] -= bullet_speed
for i in range(len(enemy_pos)):
enemy_pos[i][1] += enemy_speed
# 画出所有元素
def draw():
screen.blit(bg_img, (0, 0))
screen.blit(player_img, player_pos)
for bullet in bullet_pos:
screen.blit(bullet_img, bullet)
for enemy in enemy_pos:
screen.blit(enemy_img, enemy)
score_text = font.render('Score: ' + str(player_score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
# 判断游戏是否结束
def is_game_over():
for enemy in enemy_pos:
if enemy[1] > 600:
return True
if abs(enemy[0] - player_pos[0]) < 50 and abs(enemy[1] - player_pos[1]) < 50:
return True
return False
# 游戏循环
for i in range(5):
create_enemy()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_pos[0] -= player_speed
elif event.key == pygame.K_RIGHT:
player_pos[0] += player_speed
elif event.key == pygame.K_SPACE:
bullet_pos.append([player_pos[0] + 20, player_pos[1] - 20])
move_bullet_enemy()
draw()
# 判断子弹是否击中敌人
for bullet in bullet_pos:
for enemy in enemy_pos:
if bullet[1] < enemy[1] + 50 and bullet[1] > enemy[1] and bullet[0] > enemy[0] and bullet[0] < enemy[0] + 50:
enemy_pos.remove(enemy)
bullet_pos.remove(bullet)
player_score += 10
# 创建新敌人
if len(enemy_pos) < 5:
create_enemy()
# 判断游戏是否结束
if is_game_over():
game_over_text = font.render('Game Over', True, (0, 0, 0))
screen.blit(game_over_text, (200, 300))
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
exit()
pygame.display.update()
```
这是一个非常简单的游戏,只有一个关卡和一个积分系统。如果您想要更复杂的游戏,可以考虑添加更多的关卡、更多的敌人类型和更多的游戏元素。
阅读全文