python打飞机游戏
时间: 2023-08-23 07:06:37 浏览: 107
用python写的一个打飞机游戏.7z
好的,Python打飞机游戏的实现可以使用Pygame库来完成。以下是一个简单的示例代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义游戏窗口大小
WINDOW_WIDTH = 480
WINDOW_HEIGHT = 600
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# 加载游戏背景
bg_img = pygame.image.load("background.png")
# 加载玩家飞机图片
player_img = pygame.image.load("player.png")
player_width, player_height = player_img.get_size()
# 加载敌机图片
enemy_img = pygame.image.load("enemy.png")
enemy_width, enemy_height = enemy_img.get_size()
# 设置游戏帧率
clock = pygame.time.Clock()
FPS = 60
# 定义玩家飞机的初始位置
player_x = (WINDOW_WIDTH - player_width) // 2
player_y = WINDOW_HEIGHT - player_height - 50
# 定义敌机的初始位置和速度
enemy_x = random.randint(0, WINDOW_WIDTH - enemy_width)
enemy_y = -enemy_height
enemy_speed = 5
# 定义玩家飞机的移动速度
player_speed = 5
# 定义游戏结束标志
game_over = False
# 游戏主循环
while not game_over:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 检测玩家键盘输入
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x >= player_speed:
player_x -= player_speed
if keys[pygame.K_RIGHT] and player_x <= WINDOW_WIDTH - player_width - player_speed:
player_x += player_speed
if keys[pygame.K_UP] and player_y >= player_speed:
player_y -= player_speed
if keys[pygame.K_DOWN] and player_y <= WINDOW_HEIGHT - player_height - player_speed:
player_y += player_speed
# 移动敌机
enemy_y += enemy_speed
# 检测敌机是否与玩家飞机相撞
if enemy_y + enemy_height >= player_y and enemy_y <= player_y + player_height and \
enemy_x + enemy_width >= player_x and enemy_x <= player_x + player_width:
game_over = True
# 检测敌机是否超出屏幕
if enemy_y >= WINDOW_HEIGHT:
enemy_x = random.randint(0, WINDOW_WIDTH - enemy_width)
enemy_y = -enemy_height
# 绘制游戏场景
window.blit(bg_img, (0, 0))
window.blit(player_img, (player_x, player_y))
window.blit(enemy_img, (enemy_x, enemy_y))
# 更新屏幕显示
pygame.display.update()
# 控制游戏帧率
clock.tick(FPS)
# 退出 Pygame
pygame.quit()
```
在运行该代码前,需要准备好游戏背景、玩家飞机和敌机的图片文件,并将其放置在与代码文件相同的目录下。运行代码后,玩家可以通过方向键控制飞机移动,避免与从上方不断飞来的敌机相撞,直到游戏结束。
阅读全文