You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
2.3 KiB
90 lines
2.3 KiB
4 months ago
|
import pygame
|
||
|
import random
|
||
|
|
||
|
# 初始化pygame
|
||
|
pygame.init()
|
||
|
|
||
|
# 设置屏幕尺寸
|
||
|
screen_width = 800
|
||
|
screen_height = 600
|
||
|
screen = pygame.display.set_mode((screen_width, screen_height))
|
||
|
pygame.display.set_caption("飞机大战游戏")
|
||
|
|
||
|
# 定义颜色
|
||
|
WHITE = (255, 255, 255)
|
||
|
BLACK = (0, 0, 0)
|
||
|
RED = (255, 0, 0)
|
||
|
|
||
|
# 加载飞机图像
|
||
|
player_img = pygame.image.load("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("bullet.png")
|
||
|
bullets = []
|
||
|
bullet_speed = 10
|
||
|
|
||
|
# 敌机设置
|
||
|
enemy_img = pygame.image.load("enemy.png")
|
||
|
enemies = []
|
||
|
enemy_speed = 5
|
||
|
|
||
|
# 游戏循环控制
|
||
|
clock = pygame.time.Clock()
|
||
|
running = True
|
||
|
|
||
|
while running:
|
||
|
for event in pygame.event.get():
|
||
|
if event.type == pygame.QUIT:
|
||
|
running = False
|
||
|
|
||
|
# 控制飞机移动
|
||
|
keys = pygame.key.get_pressed()
|
||
|
if keys[pygame.K_LEFT] and player_rect.left > 0:
|
||
|
player_rect.x -= 5
|
||
|
if keys[pygame.K_RIGHT] and player_rect.right < screen_width:
|
||
|
player_rect.x += 5
|
||
|
if keys[pygame.K_SPACE]:
|
||
|
bullet_rect = bullet_img.get_rect(center=player_rect.center)
|
||
|
bullets.append(bullet_rect)
|
||
|
|
||
|
# 更新子弹位置
|
||
|
for bullet in bullets[:]:
|
||
|
bullet.y -= bullet_speed
|
||
|
if bullet.bottom < 0:
|
||
|
bullets.remove(bullet)
|
||
|
|
||
|
# 生成敌机
|
||
|
if random.randint(1, 30) == 1:
|
||
|
enemy_rect = enemy_img.get_rect(x=random.randint(0, screen_width - enemy_img.get_width()), y=0)
|
||
|
enemies.append(enemy_rect)
|
||
|
|
||
|
# 更新敌机位置
|
||
|
for enemy in enemies[:]:
|
||
|
enemy.y += enemy_speed
|
||
|
if enemy.top > screen_height:
|
||
|
enemies.remove(enemy)
|
||
|
|
||
|
# 碰撞检测
|
||
|
for bullet in bullets[:]:
|
||
|
for enemy in enemies[:]:
|
||
|
if bullet.colliderect(enemy):
|
||
|
bullets.remove(bullet)
|
||
|
enemies.remove(enemy)
|
||
|
break
|
||
|
|
||
|
# 绘制
|
||
|
screen.fill(WHITE)
|
||
|
screen.blit(player_img, player_rect)
|
||
|
for bullet in bullets:
|
||
|
screen.blit(bullet_img, bullet)
|
||
|
for enemy in enemies:
|
||
|
screen.blit(enemy_img, enemy)
|
||
|
pygame.display.flip()
|
||
|
|
||
|
clock.tick(60)
|
||
|
|
||
|
pygame.quit()
|