Python小游戏——雷霆战机

import pygame
import random

# 初始化
pygame.init()

# 定义游戏窗口大小
window_width = 800
window_height = 600

# 创建游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("雷霆战机")

# 加载图片
player_img = pygame.image.load("player.png")
enemy_img = pygame.image.load("enemy.png")
bullet_img = pygame.image.load("bullet.png")

# 获取图片大小
player_width = player_img.get_width()
player_height = player_img.get_height()
enemy_width = enemy_img.get_width()
enemy_height = enemy_img.get_height()
bullet_width = bullet_img.get_width()
bullet_height = bullet_img.get_height()

# 设置游戏速度
clock = pygame.time.Clock()
game_speed = 30

# 定义玩家、敌人和子弹的初始位置
player_x = window_width / 2 - player_width / 2
player_y = window_height - player_height
enemy_x = random.randint(0, window_width - enemy_width)
enemy_y = 0
bullet_x = 0
bullet_y = window_height
bullet_state = "ready"

# 定义玩家、敌人和子弹的移动速度
player_speed = 5
enemy_speed = 3
bullet_speed = 7

# 定义得分
score = 0

# 定义字体
font = pygame.font.Font(None, 36)

# 定义游戏结束标志
game_over = False

# 游戏循环
while not game_over:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

        # 处理玩家移动事件
        if 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 and bullet_state == "ready":
                # 发射子弹
                bullet_x = player_x + player_width / 2 - bullet_width / 2
                bullet_y = player_y
                bullet_state = "fire"

    # 更新玩家、敌人和子弹的位置
    player_x = max(0, min(window_width - player_width, player_x))
    enemy_y += enemy_speed
    bullet_y -= bullet_speed

    # 检测碰撞
    if bullet_state == "fire" and bullet_y <= enemy_y + enemy_height:
        if bullet_x >= enemy_x and bullet_x <= enemy_x + enemy_width:
            # 子弹击中敌人
            bullet_state = "ready"
            enemy_x = random.randint(0, window_width - enemy_width)
            enemy_y = 0
            score += 1

    if enemy_y >= window_height:
        # 敌人飞过屏幕底部
        enemy_x = random.randint(0, window_width - enemy_width)
        enemy_y = 0
        score -= 1

    # 绘制画面
    window.fill((255, 255, 255))
    window.blit(player_img, (player_x, player_y))
    window.blit(enemy_img, (enemy_x, enemy_y))
    window.blit(bullet_img, (bullet_x, bullet_y))

    # 绘制得分
    score_text = font.render("Score: " + str(score), True, (0, 0, 0))
    window.blit(score_text, (10, 10))

    pygame.display.update()
    clock.tick(game_speed)

# 退出游戏
pygame.quit()

以上代码是一个简单的雷霆战机小游戏的Python代码

请注意,以上代码仅为一个简单的示例,实际游戏可以根据需求进行更复杂的设置和功能。另外,游戏中使用的图片需要事先准备好并保存在与代码文件相同的目录下,分别命名为"player.png"、"enemy.png"和"bullet.png"。

你可能感兴趣的:(pygame,python,开发语言)