python实现飞机大战代码
时间: 2023-03-25 16:02:31 浏览: 118
使用python实现飞机大战游戏
5星 · 资源好评率100%
以下是 Python 实现飞机大战的代码示例:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小
screen_width = 480
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("飞机大战")
# 加载背景图片
background = pygame.image.load("images/background.png")
# 加载飞机图片
player_img = pygame.image.load("images/player.png")
player_rect = player_img.get_rect()
player_rect.centerx = screen_width // 2
player_rect.bottom = screen_height - 10
# 加载子弹图片
bullet_img = pygame.image.load("images/bullet.png")
bullet_rect = bullet_img.get_rect()
# 加载敌机图片
enemy_img = pygame.image.load("images/enemy.png")
enemy_rect = enemy_img.get_rect()
# 设置游戏时钟
clock = pygame.time.Clock()
# 设置游戏分数
score =
font = pygame.font.SysFont(None, 36)
# 设置敌机列表
enemies = []
enemy_speed = 1
enemy_frequency = 60
enemy_frequency_counter =
# 设置子弹列表
bullets = []
bullet_speed = 5
# 游戏循环
running = True
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bullet_rect.centerx = player_rect.centerx
bullet_rect.bottom = player_rect.top
bullets.append(bullet_rect.copy())
# 移动飞机
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_rect.left > :
player_rect.move_ip(-5, )
if keys[pygame.K_RIGHT] and player_rect.right < screen_width:
player_rect.move_ip(5, )
if keys[pygame.K_UP] and player_rect.top > :
player_rect.move_ip(, -5)
if keys[pygame.K_DOWN] and player_rect.bottom < screen_height:
player_rect.move_ip(, 5)
# 移动子弹
for bullet_rect in bullets:
bullet_rect.move_ip(, -bullet_speed)
if bullet_rect.top < :
bullets.remove(bullet_rect)
# 生成敌机
enemy_frequency_counter += 1
if enemy_frequency_counter == enemy_frequency:
enemy_rect.centerx = random.randint(, screen_width)
enemy_rect.top =
enemies.append(enemy_rect.copy())
enemy_frequency_counter =
# 移动敌机
for enemy_rect in enemies:
enemy_rect.move_ip(, enemy_speed)
if enemy_rect.bottom > screen_height:
enemies.remove(enemy_rect)
# 检测子弹和敌机的碰撞
for bullet_rect in bullets:
for enemy_rect in enemies:
if bullet_rect.colliderect(enemy_rect):
bullets.remove(bullet_rect)
enemies.remove(enemy_rect)
score += 10
# 绘制游戏元素
screen.blit(background, (, ))
screen.blit(player_img, player_rect)
for bullet_rect in bullets:
screen.blit(bullet_img, bullet_rect)
for enemy_rect in enemies:
screen.blit(enemy_img, enemy_rect)
score_text = font.render("Score: {}".format(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 更新游戏画面
pygame.display.update()
# 控制游戏帧率
clock.tick(60)
# 退出 Pygame
pygame.quit()
```
希望能对你有所帮助!
阅读全文