基于pygame的飞机大战游戏代码
时间: 2023-08-31 17:25:53 浏览: 135
使用pygame实现飞机大战python代码+png图标
5星 · 资源好评率100%
### 回答1:
下面是一份基于pygame的飞机大战游戏代码的简要实现:
```
import pygame
import random
# 初始化游戏
pygame.init()
# 设置窗口大小
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
# 加载飞机图片
player_image = pygame.image.load("player.png")
player_rect = player_image.get_rect()
player_rect.centerx = width // 2
player_rect.bottom = height - 10
# 加载敌机图片
enemy_image = pygame.image.load("enemy.png")
# 存储敌机的位置和移动速度
enemies = []
for i in range(5):
enemy_rect = enemy_image.get_rect()
enemy_rect.x = random.randint(0, width - enemy_rect.width)
enemy_rect.y = random.randint(0, height // 2)
enemies.append((enemy_image, enemy_rect))
# 游戏主循环
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]:
player_rect.x -= 5
if keys[pygame.K_RIGHT]:
player_rect.x += 5
if keys[pygame.K_UP]:
player_rect.y -= 5
if keys[pygame.K_DOWN]:
player_rect.y += 5
# 限制飞机在窗口内
player_rect.clamp_ip(screen.get_rect())
# 绘制背景
screen.fill((0, 0, 0))
# 绘制飞机
screen.blit(player_image, player_rect)
# 绘制敌机
for enemy_image, enemy_rect in enemies:
screen.blit(enemy_image, enemy_rect)
# 更新屏幕
pygame.display.update()
# 退出游戏
pygame.quit()
```
这份代码实现了飞机大战的基本逻辑,包括加载图片、控制飞机的移动、绘制背景和敌机等。你可以
### 回答2:
Pygame是一个非常流行的Python模块,用于创建2D游戏。下面是一个基于Pygame的飞机大战游戏的示例代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口尺寸
screen_width = 500
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("飞机大战")
# 加载背景图像
background = pygame.image.load("background.jpg")
# 加载飞机图像
player_img = pygame.image.load("player.png")
player_width = player_img.get_width()
player_height = player_img.get_height()
# 加载敌机图像
enemy_img = pygame.image.load("enemy.png")
enemy_width = enemy_img.get_width()
enemy_height = enemy_img.get_height()
# 初始化玩家的位置
player_x = (screen_width - player_width) / 2
player_y = screen_height - player_height - 10
# 初始化敌机的位置和速度
enemy_x = random.randint(0, screen_width - enemy_width)
enemy_y = -enemy_height
enemy_speed = 3
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.blit(background, (0, 0))
# 检测键盘输入移动玩家
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_x -= 5
if keys[pygame.K_RIGHT]:
player_x += 5
# 更新玩家位置
screen.blit(player_img, (player_x, player_y))
# 更新敌机位置
enemy_y += enemy_speed
screen.blit(enemy_img, (enemy_x, enemy_y))
# 检查是否敌机与玩家碰撞
if player_x < enemy_x + enemy_width and player_x + player_width > enemy_x and player_y < enemy_y + enemy_height and player_y + player_height > enemy_y:
running = False
pygame.display.flip()
# 退出游戏
pygame.quit()
```
这是一个简单的飞机大战游戏,玩家可以使用左右箭头键控制飞机移动,敌机从上方自动降落。游戏循环检测玩家和敌机的碰撞,如果发生碰撞,游戏结束。
阅读全文