Python飞机小游戏代码
时间: 2024-04-19 07:22:10 浏览: 66
当然可以!以下是一个简单的Python飞机小游戏代码示例:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏窗口大小
screen_width = 480
screen_height = 600
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_img.get_width()
player_height = player_img.get_height()
player_x = (screen_width - player_width) // 2
player_y = screen_height - player_height - 20
# 加载敌机图片
enemy_img = pygame.image.load("enemy.png")
enemy_width = enemy_img.get_width()
enemy_height = enemy_img.get_height()
enemy_x = random.randint(0, screen_width - enemy_width)
enemy_y = -enemy_height
enemy_speed = 3
# 设置玩家飞机移动速度
player_speed = 5
# 游戏主循环
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
# 更新敌机位置
enemy_y += enemy_speed
if enemy_y > screen_height:
enemy_x = random.randint(0, screen_width - enemy_width)
enemy_y = -enemy_height
# 绘制背景
screen.blit(background, (0, 0))
# 绘制玩家飞机
screen.blit(player_img, (player_x, player_y))
# 绘制敌机
screen.blit(enemy_img, (enemy_x, enemy_y))
# 更新屏幕显示
pygame.display.update()
# 退出游戏
pygame.quit()
```
这是一个简单的飞机小游戏,玩家可以通过左右箭头键控制飞机移动,避开从上方飞来的敌机。你可以根据自己的需求进行修改和扩展。
阅读全文