pycharm小游戏飞机射击
导入pygame模块
下载成功
图片略显粗糙
python
复制
import pygame
import random
# 初始化 pygame
pygame.init()
# 屏幕大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 飞机速度
PLANE_SPEED = 5
# 子弹速度
BULLET_SPEED = 10
# 敌机速度
ENEMY_SPEED = 3
# 初始化屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("飞机射击游戏")
# 游戏时钟
clock = pygame.time.Clock()
# 加载飞机图片
plane_image = pygame.image.load("plane.png")
plane_rect = plane_image.get_rect()
plane_rect.x = (SCREEN_WIDTH - plane_rect.width) / 2
plane_rect.y = SCREEN_HEIGHT - plane_rect.height
# 加载子弹图片
bullet_image = pygame.image.load("bullet.png")
bullet_list = []
# 敌机列表
enemy_list = []
# 得分
score = 0
# 游戏结束标志
game_over = False
# 生成敌机函数
def generate_enemy():
enemy_image = pygame.image.load("enemy.png")
enemy_rect = enemy_image.get_rect()
enemy_rect.x = random.randint(0, SCREEN_WIDTH - enemy_rect.width)
enemy_rect.y = -enemy_rect.height
enemy_list.append([enemy_image, enemy_rect])
# 游戏主循环
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_LEFT] and plane_rect.x > 0:
plane_rect.x -= PLANE_SPEED
if keys_pressed[pygame.K_RIGHT] and plane_rect.x < SCREEN_WIDTH - plane_rect.width:
plane_rect.x += PLANE_SPEED
if keys_pressed[pygame.K_SPACE]:
bullet_rect = bullet_image.get_rect()
bullet_rect.x = plane_rect.x + plane_rect.width / 2 - bullet_rect.width / 2
bullet_rect.y = plane_rect.y
bullet_list.append([bullet_image, bullet_rect])
# 移动子弹
for bullet in bullet_list:
bullet[1].y -= BULLET_SPEED
if bullet[1].y < 0:
bullet_list.remove(bullet)
# 移动敌机
for enemy in enemy_list:
enemy[1].y += ENEMY_SPEED
if enemy[1].y > SCREEN_HEIGHT:
enemy_list.remove(enemy)
# 检测子弹与敌机的碰撞
for bullet in bullet_list:
if enemy[1].colliderect(bullet[1]):
enemy_list.remove(enemy)
bullet_list.remove(bullet)
score += 10
# 检测敌机与飞机的碰撞
if plane_rect.colliderect(enemy[1]):
game_over = True
# 生成敌机
if random.randint(0, 100) < 5:
generate_enemy()
# 绘制背景
screen.fill(BLACK)
# 绘制飞机
screen.blit(plane_image, plane_rect)
# 绘制子弹
for bullet in bullet_list:
screen.blit(bullet[0], bullet[1])
# 绘制敌机
for enemy in enemy_list:
screen.blit(enemy[0], enemy[1])
# 显示得分
font = pygame.font.SysFont(None, 36)
text = font.render("Score: " + str(score), 1, WHITE)
screen.blit(text, (10, 10))
# 刷新屏幕
pygame.display.flip()
# 控制游戏帧率
clock.tick(60)
# 退出游戏
pygame.quit()
请注意,上述代码中需要您准备飞机、子弹和敌机的图片,并将文件名修改为代码中的相应名称。这个游戏实现了飞机的控制、子弹的发射、敌机的生成和碰撞检测等功能。