做一个基于python的飞机大战代码,不需要添加其他东西
时间: 2023-06-14 14:03:10 浏览: 91
好的,下面是一个简单的飞机大战代码,仅供参考:
```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_plane = pygame.image.load("images/player.png")
# 加载子弹图片
bullet = pygame.image.load("images/bullet.png")
# 加载敌机图片
enemy_plane = pygame.image.load("images/enemy.png")
# 设置字体
font = pygame.font.SysFont(None, 36)
# 设置游戏状态
game_over = False
# 设置计分
score = 0
# 定义函数:绘制飞机
def draw_plane(x, y):
screen.blit(player_plane, (x, y))
# 定义函数:绘制子弹
def draw_bullet(x, y):
screen.blit(bullet, (x, y))
# 定义函数:绘制敌机
def draw_enemy(x, y):
screen.blit(enemy_plane, (x, y))
# 定义函数:显示分数
def show_score(score):
score_text = font.render("分数:" + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 初始化飞机位置
player_x = screen_width // 2 - 50
player_y = screen_height - 150
# 初始化子弹位置
bullet_x = player_x + 36
bullet_y = player_y - 20
bullet_speed = 10
bullet_state = "ready"
# 初始化敌机位置
enemy_x = random.randint(0, screen_width - 64)
enemy_y = -64
enemy_speed = 5
# 设置游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and bullet_state == "ready":
bullet_x = player_x + 36
bullet_y = player_y - 20
bullet_state = "fire"
elif event.key == pygame.K_LEFT:
player_x -= 10
elif event.key == pygame.K_RIGHT:
player_x += 10
# 绘制背景
screen.blit(background, (0, 0))
# 绘制飞机
draw_plane(player_x, player_y)
# 绘制子弹
if bullet_state == "fire":
draw_bullet(bullet_x, bullet_y)
bullet_y -= bullet_speed
if bullet_y < 0:
bullet_state = "ready"
# 绘制敌机
draw_enemy(enemy_x, enemy_y)
enemy_y += enemy_speed
if enemy_y > screen_height:
enemy_x = random.randint(0, screen_width - 64)
enemy_y = -64
# 碰撞检测
if bullet_state == "fire" and enemy_x < bullet_x < enemy_x + 64 and enemy_y < bullet_y < enemy_y + 64:
score += 10
bullet_state = "ready"
enemy_x = random.randint(0, screen_width - 64)
enemy_y = -64
if enemy_x < player_x < enemy_x + 64 and enemy_y < player_y < enemy_y + 64:
game_over = True
# 显示分数
show_score(score)
# 更新屏幕
pygame.display.update()
# 退出游戏
pygame.quit()
```
阅读全文