用python做飞机大战
时间: 2023-09-17 20:15:01 浏览: 89
Sure, 我很乐意为您解答。要用Python做飞机大战游戏,您需要使用Pygame库来处理图形和事件。以下是一个简单的示例代码:
```
import pygame
# 初始化 Pygame 库
pygame.init()
# 设置游戏屏幕尺寸
screen_width, screen_height = 480, 700
screen = pygame.display.set_mode((screen_width, screen_height))
# 加载背景图片
background = pygame.image.load("background.png")
# 加载飞机图片
player_plane = pygame.image.load("plane.png")
player_width, player_height = player_plane.get_rect().size
# 设置飞机初始位置
player_x = screen_width // 2 - player_width // 2
player_y = screen_height - player_height - 50
# 飞机移动速度
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
elif keys[pygame.K_RIGHT] and player_x < screen_width - player_width:
player_x += player_speed
elif keys[pygame.K_UP] and player_y > 0:
player_y -= player_speed
elif keys[pygame.K_DOWN] and player_y < screen_height - player_height:
player_y += player_speed
# 绘制画面
screen.blit(background, (0, 0))
screen.blit(player_plane, (player_x, player_y))
pygame.display.update()
# 退出游戏
pygame.quit()
```
这只是一个基本的示例代码,您可以根据自己的需要进行修改和扩展。希望对您有所帮助。
阅读全文