飞机大战游戏python代码
时间: 2023-07-09 08:29:28 浏览: 102
以下是一个简单的飞机大战游戏的 Python 代码示例:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 设置屏幕大小
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# 设置游戏标题
pygame.display.set_caption("飞机大战")
# 加载图片
player_img = pygame.image.load("player.png").convert()
enemy_img = pygame.image.load("enemy.png").convert()
# 设置字体
font = pygame.font.Font(None, 36)
# 游戏结束标志
game_over = False
# 玩家
player_x = 300
player_y = 400
player_speed = 5
# 敌人
enemies = []
enemy_speed = 3
# 得分
score = 0
# 生成敌人
def create_enemy():
enemy_x = random.randint(0, SCREEN_WIDTH - enemy_img.get_width())
enemy_y = -enemy_img.get_height()
enemies.append([enemy_x, enemy_y])
# 更新敌人位置
def update_enemies():
for i, enemy in enumerate(enemies):
enemy[1] += enemy_speed
if enemy[1] > SCREEN_HEIGHT:
del enemies[i]
# 检查碰撞
def check_collision():
global game_over, score
for i, enemy in enumerate(enemies):
if (player_x < enemy[0] + enemy_img.get_width() and
player_x + player_img.get_width() > enemy[0] and
player_y < enemy[1] + enemy_img.get_height() and
player_y + player_img.get_height() > enemy[1]):
game_over = True
score_text = font.render("得分: {}".format(score), True, WHITE)
screen.blit(score_text, [SCREEN_WIDTH // 2 - score_text.get_width() // 2, SCREEN_HEIGHT // 2 - score_text.get_height() // 2])
pygame.display.flip()
pygame.time.wait(3000)
break
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x -= player_speed
elif event.key == pygame.K_RIGHT:
player_x += player_speed
# 更新玩家位置
if player_x < 0:
player_x = 0
elif player_x > SCREEN_WIDTH - player_img.get_width():
player_x = SCREEN_WIDTH - player_img.get_width()
# 更新敌人位置
if len(enemies) < 10:
create_enemy()
update_enemies()
# 检查碰撞
check_collision()
# 绘制背景
screen.fill(BLACK)
# 绘制玩家
screen.blit(player_img, [player_x, player_y])
# 绘制敌人
for enemy in enemies:
screen.blit(enemy_img, enemy)
# 显示得分
score += len(enemies)
score_text = font.render("得分: {}".format(score), True, WHITE)
screen.blit(score_text, [10, 10])
# 更新屏幕
pygame.display.flip()
# 退出 Pygame
pygame.quit()
```
这个示例中,玩家可以使用左右键来移动飞机,敌人会从顶部随机位置出现并向下移动,玩家需要躲避敌人并尽可能地击败他们来获得更高的分数。当玩家与敌人发生碰撞时,游戏将结束,并显示最终得分。
阅读全文