写一个飞机大战的游戏 python代码
时间: 2023-12-20 13:03:46 浏览: 85
当然可以!下面是一个简单的飞机大战游戏的Python代码示例:
```python
import pygame
import random
# 游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 飞机大小
PLANE_WIDTH = 60
PLANE_HEIGHT = 45
# 子弹大小
BULLET_WIDTH = 5
BULLET_HEIGHT = 15
# 敌机大小
ENEMY_WIDTH = 50
ENEMY_HEIGHT = 38
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 初始化Pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("飞机大战游戏")
# 加载游戏图片
background_img = pygame.image.load("background.jpg")
plane_img = pygame.image.load("plane.png")
enemy_img = pygame.image.load("enemy.png")
# 游戏时钟
clock = pygame.time.Clock()
# 飞机初始位置
plane_x = WINDOW_WIDTH // 2 - PLANE_WIDTH // 2
plane_y = WINDOW_HEIGHT - PLANE_HEIGHT - 10
# 子弹列表
bullets = []
# 敌机列表
enemies = []
# 游戏结束标志位
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 监听键盘事件,控制飞机移动和发射子弹
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
plane_x -= 10
elif event.key == pygame.K_RIGHT:
plane_x += 10
elif event.key == pygame.K_SPACE:
bullet_x = plane_x + PLANE_WIDTH // 2 - BULLET_WIDTH // 2
bullet_y = plane_y
bullets.append([bullet_x, bullet_y])
# 移动子弹
for bullet in bullets:
bullet[1] -= 10
# 移除超出窗口范围的子弹
bullets = [bullet for bullet in bullets if bullet[1] > 0]
# 生成敌机
if len(enemies) < 5 and random.randint(1, 100) < 5:
enemy_x = random.randint(0, WINDOW_WIDTH - ENEMY_WIDTH)
enemy_y = -ENEMY_HEIGHT
enemies.append([enemy_x, enemy_y])
# 移动敌机
for enemy in enemies:
enemy[1] += 5
# 移除超出窗口范围的敌机
enemies = [enemy for enemy in enemies if enemy[1] < WINDOW_HEIGHT]
# 检测击中敌机
for bullet in bullets:
for enemy in enemies:
if (enemy[0] <= bullet[0] <= enemy[0] + ENEMY_WIDTH or
enemy[0] <= bullet[0] + BULLET_WIDTH <= enemy[0] + ENEMY_WIDTH) and (
enemy[1] <= bullet[1] <= enemy[1] + ENEMY_HEIGHT or
enemy[1] <= bullet[1] + BULLET_HEIGHT <= enemy[1] + ENEMY_HEIGHT):
enemies.remove(enemy)
bullets.remove(bullet)
# 检测飞机被击中
for enemy in enemies:
if (enemy[0] <= plane_x <= enemy[0] + ENEMY_WIDTH or
enemy[0] <= plane_x + PLANE_WIDTH <= enemy[0] + ENEMY_WIDTH) and (
enemy[1] <= plane_y <= enemy[1] + ENEMY_HEIGHT or
enemy[1] <= plane_y + PLANE_HEIGHT <= enemy[1] + ENEMY_HEIGHT):
game_over = True
# 绘制游戏窗口
window.blit(background_img, (0, 0))
window.blit(plane_img, (plane_x, plane_y))
for bullet in bullets:
pygame.draw.rect(window, RED, pygame.Rect(bullet[0], bullet[1], BULLET_WIDTH, BULLET_HEIGHT))
for enemy in enemies:
window.blit(enemy_img, (enemy[0], enemy[1]))
# 刷新游戏窗口
pygame.display.flip()
# 控制游戏帧率
clock.tick(60)
# 退出游戏
pygame.quit()
```
在这个示例中,你需要准备一些游戏所需的图片素材,然后将图片文件名更新到代码中的相应位置。这个代码实现了一个简单的飞机大战游戏,你可以运行它来尝试玩一下。希望对你有帮助!
阅读全文