怎么用python写飞机大战
时间: 2023-12-01 20:02:51 浏览: 73
python 编写飞机大战
5星 · 资源好评率100%
以下是一个简单的Python飞机大战游戏的示例代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("飞机大战")
# 加载背景图
background = pygame.image.load("background.png")
# 加载玩家飞机图
player_img = pygame.image.load("player.png")
player_width, player_height = player_img.get_rect().size
player_x = (screen_width - player_width) // 2
player_y = screen_height - player_height - 50
# 加载敌机图
enemy_img = pygame.image.load("enemy.png")
enemy_width, enemy_height = enemy_img.get_rect().size
# 定义敌机列表
enemies = []
for i in range(5):
enemy_x = random.randint(0, screen_width - enemy_width)
enemy_y = random.randint(-500, -enemy_height)
enemies.append([enemy_x, enemy_y])
# 设置玩家飞机移动速度
player_speed = 5
# 设置敌机移动速度
enemy_speed = 3
# 设置游戏帧率
clock = pygame.time.Clock()
fps = 60
# 游戏主循环
running = True
while running:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 玩家飞机移动
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= player_speed
if keys[pygame.K_RIGHT] and player_x < screen_width - player_width:
player_x += player_speed
if keys[pygame.K_UP] and player_y > 0:
player_y -= player_speed
if keys[pygame.K_DOWN] and player_y < screen_height - player_height:
player_y += player_speed
# 敌机移动
for enemy in enemies:
enemy[1] += enemy_speed
if enemy[1] > screen_height:
enemy[0] = random.randint(0, screen_width - enemy_width)
enemy[1] = random.randint(-500, -enemy_height)
# 碰撞检测
for enemy in enemies:
if (player_x + player_width > enemy[0] and player_x < enemy[0] + enemy_width
and player_y + player_height > enemy[1] and player_y < enemy[1] + enemy_height):
running = False
# 绘制游戏元素
screen.blit(background, (0, 0))
screen.blit(player_img, (player_x, player_y))
for enemy in enemies:
screen.blit(enemy_img, (enemy[0], enemy[1]))
pygame.display.update()
# 控制游戏帧率
clock.tick(fps)
# 退出 Pygame
pygame.quit()
```
运行以上代码,可以看到一个简单的飞机大战游戏。在这个游戏中,玩家飞机可以通过键盘上下左右键进行移动,敌机会从屏幕顶部不断向下移动,玩家飞机与敌机碰撞时游戏结束。
阅读全文