python 写一个飞机大战游戏源码
时间: 2023-05-14 16:06:36 浏览: 127
非常感谢您的提问,以下是一个简单的飞机大战游戏的 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()
# 设置字体
font = pygame.font.SysFont(None, 48)
# 设置游戏状态
game_over = False
# 设置计分
score = 0
# 设置敌机列表
enemies = []
for i in range(5):
enemy_rect = enemy_img.get_rect()
enemy_rect.left = random.randint(0, screen_width - enemy_rect.width)
enemy_rect.top = random.randint(-screen_height, 0)
enemies.append(enemy_rect)
# 游戏循环
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]:
player_rect.move_ip(-5, 0)
if keys[pygame.K_RIGHT]:
player_rect.move_ip(5, 0)
if keys[pygame.K_UP]:
player_rect.move_ip(0, -5)
if keys[pygame.K_DOWN]:
player_rect.move_ip(0, 5)
# 移动子弹
for bullet_rect in bullets:
bullet_rect.move_ip(0, -10)
if bullet_rect.bottom < 0:
bullets.remove(bullet_rect)
# 移动敌机
for enemy_rect in enemies:
enemy_rect.move_ip(0, 5)
if enemy_rect.top > screen_height:
enemy_rect.left = random.randint(0, screen_width - enemy_rect.width)
enemy_rect.top = random.randint(-screen_height, 0)
# 检测碰撞
for enemy_rect in enemies:
if player_rect.colliderect(enemy_rect):
game_over = True
for bullet_rect in bullets:
if bullet_rect.colliderect(enemy_rect):
score += 1
enemies.remove(enemy_rect)
bullets.remove(bullet_rect)
# 绘制游戏界面
screen.blit(background, (0, 0))
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: " + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
pygame.display.update()
# 结束游戏
pygame.quit()
```
希望这个源码能够帮助到您!
阅读全文