用python写一个飞机大战小游戏代码
时间: 2023-12-17 21:19:48 浏览: 81
好的,以下是一个简单的飞机大战小游戏代码,仅供参考:
```python
import pygame
import random
# 初始化游戏
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")
player_plane_rect = player_plane.get_rect()
player_plane_rect.midbottom = (screen_width // 2, screen_height - 20)
# 加载子弹图片
bullet = pygame.image.load("images/bullet.png")
bullet_rect = bullet.get_rect()
# 加载敌机图片
enemy_plane = pygame.image.load("images/enemy.png")
enemy_planes = []
# 初始化得分
score = 0
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义函数:创建敌机
def create_enemy():
enemy_plane_rect = enemy_plane.get_rect()
enemy_plane_rect.left = random.randint(0, screen_width - enemy_plane_rect.width)
enemy_plane_rect.top = -enemy_plane_rect.height
enemy_planes.append(enemy_plane_rect)
# 定义函数:移动敌机
def move_enemy():
for enemy_plane_rect in enemy_planes:
enemy_plane_rect.top += 5
if enemy_plane_rect.top > screen_height:
enemy_planes.remove(enemy_plane_rect)
# 定义函数:检测子弹碰撞敌机
def check_bullet_hit_enemy():
global score
for enemy_plane_rect in enemy_planes:
if bullet_rect.colliderect(enemy_plane_rect):
enemy_planes.remove(enemy_plane_rect)
score += 10
# 定义函数:检测飞机碰撞敌机
def check_plane_hit_enemy():
for enemy_plane_rect in enemy_planes:
if player_plane_rect.colliderect(enemy_plane_rect):
return True
return False
# 游戏循环
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.midbottom = player_plane_rect.midtop
bullet_shot = True
# 移动飞机
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_plane_rect.move_ip(-5, 0)
elif keys[pygame.K_RIGHT]:
player_plane_rect.move_ip(5, 0)
if player_plane_rect.left < 0:
player_plane_rect.left = 0
elif player_plane_rect.right > screen_width:
player_plane_rect.right = screen_width
# 移动子弹
if bullet_rect.bottom > 0:
bullet_rect.move_ip(0, -10)
else:
bullet_shot = False
# 检测子弹碰撞敌机
if bullet_shot:
check_bullet_hit_enemy()
# 创建敌机
if random.randint(1, 50) == 1:
create_enemy()
# 移动敌机
move_enemy()
# 检测飞机碰撞敌机
if check_plane_hit_enemy():
running = False
# 绘制游戏
screen.blit(background, (0, 0))
screen.blit(player_plane, player_plane_rect)
if bullet_shot:
screen.blit(bullet, bullet_rect)
for enemy_plane_rect in enemy_planes:
screen.blit(enemy_plane, enemy_plane_rect)
score_font = pygame.font.Font(None, 36)
score_text = score_font.render("得分:" + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
pygame.display.update()
# 设置游戏帧率
clock.tick(60)
# 结束游戏
pygame.quit()
```
需要注意的是,此代码仅为一个简单的示例,游戏玩法和细节需要根据需求自行修改和完善。
阅读全文