写一个飞机大战的python代码
时间: 2023-05-21 14:01:10 浏览: 172
以下是一个简单的飞机大战的 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()
bullet_speed = 10
bullet_list = []
# 加载敌机图片
enemy_img = pygame.image.load("images/enemy.png")
enemy_rect = enemy_img.get_rect()
enemy_speed = 5
enemy_list = []
# 设置游戏时钟
clock = pygame.time.Clock()
# 设置分数
score = 0
font = pygame.font.Font(None, 36)
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 移动飞机
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_SPACE]:
bullet_rect = bullet_img.get_rect()
bullet_rect.centerx = player_rect.centerx
bullet_rect.bottom = player_rect.top
bullet_list.append(bullet_rect)
# 移动子弹
for bullet_rect in bullet_list:
bullet_rect.y -= bullet_speed
if bullet_rect.y < 0:
bullet_list.remove(bullet_rect)
# 移动敌机
if len(enemy_list) < 5:
enemy_rect = enemy_img.get_rect()
enemy_rect.x = random.randint(0, screen_width - enemy_rect.width)
enemy_rect.y = -enemy_rect.height
enemy_list.append(enemy_rect)
for enemy_rect in enemy_list:
enemy_rect.y += enemy_speed
if enemy_rect.y > screen_height:
enemy_list.remove(enemy_rect)
# 检测碰撞
for bullet_rect in bullet_list:
for enemy_rect in enemy_list:
if bullet_rect.colliderect(enemy_rect):
bullet_list.remove(bullet_rect)
enemy_list.remove(enemy_rect)
score += 10
# 绘制画面
screen.blit(background, (0, 0))
screen.blit(player_img, player_rect)
for bullet_rect in bullet_list:
screen.blit(bullet_img, bullet_rect)
for enemy_rect in enemy_list:
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()
# 控制帧率
clock.tick(60)
```
希望这个代码能够帮助你开始编写自己的飞机大战游戏!
阅读全文