[python]代码库
import pygame
import random
# 初始化游戏
pygame.init()
screen = pygame.display.set_mode((400, 600))
pygame.display.set_caption("飞机大战")
# 加载图片资源 背景图,玩家飞机,子弹,敌人飞机
background = pygame.image.load("bg.png")
player_img = pygame.image.load("player.png")
bullet_img = pygame.image.load("bullet.png")
enemy_img = pygame.image.load("enemy.png")
# 设置游戏对象
player_x = 200
player_y = 500
player_speed = 5
player_rect = player_img.get_rect()
player_rect.x = player_x
player_rect.y = player_y
bullets = []
enemies = []
for i in range(5):
enemy_x = random.randint(50, 350)
enemy_y = random.randint(-200, -50)
enemy_speed = random.randint(1, 3)
enemy_rect = enemy_img.get_rect()
enemy_rect.x = enemy_x
enemy_rect.y = enemy_y
enemies.append((enemy_rect, enemy_speed))
score = 0
font = pygame.font.Font(None, 36)
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x -= player_speed
elif event.key == pygame.K_RIGHT:
player_x += player_speed
elif event.key == pygame.K_SPACE:
bullet_x = player_x + player_rect.width // 2
bullet_y = player_y
bullet_rect = bullet_img.get_rect()
bullet_rect.x = bullet_x
bullet_rect.y = bullet_y
bullets.append(bullet_rect)
# 更新游戏状态
for bullet_rect in bullets:
bullet_rect.y -= 5
if bullet_rect.y < -bullet_rect.height:
bullets.remove(bullet_rect)
for enemy_rect, enemy_speed in enemies:
enemy_rect.y += enemy_speed
if enemy_rect.y > screen.get_height():
enemy_rect.x = random.randint(50, 350)
enemy_rect.y = random.randint(-200, -50)
enemy_speed = random.randint(1, 3)
enemies[enemies.index((enemy_rect, enemy_speed))] = (enemy_rect, enemy_speed)
elif enemy_rect.colliderect(player_rect):
pygame.quit()
quit()
else:
for bullet_rect in bullets:
if enemy_rect.colliderect(bullet_rect):
bullets.remove(bullet_rect)
enemy_rect.x = random.randint(50, 350)
enemy_rect.y = random.randint(-200, -50)
enemy_speed = random.randint(1, 3)
enemies[enemies.index((enemy_rect, enemy_speed))] = (enemy_rect, enemy_speed)
score += 1
player_rect.x = player_x
player_rect.y = player_y
# 绘制游戏界面
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("得分:"+str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 更新
pygame.display.update()