找回密码
 中文实名注册
查看: 63|回复: 1

恐怖严思宇1.0 沈熠

[复制链接]

4

主题

29

帖子

707

积分

高级会员

Rank: 4

积分
707
发表于 2025-1-11 15:33:13 | 显示全部楼层 |阅读模式
[Python] 纯文本查看 复制代码
import pygame
import sys
import random
import math
import time  # 引入 time 模块

# 初始化 pygame
pygame.init()

# 窗口参数
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("乱飞子弹打怪升级游戏")

# 颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)  # 添加黄色

# 玩家参数
PLAYER_SIZE = 40
PLAYER_X = WIDTH // 2 - PLAYER_SIZE // 2
PLAYER_Y = HEIGHT - PLAYER_SIZE - 20
PLAYER_SPEED = 5
PLAYER_HEALTH = 100
PLAYER_MAX_HEALTH = 100

# 子弹参数
BULLET_SIZE = 10
BULLET_SPEED = 7
BULLET_COLOR = GREEN
bullets = []
BULLET_INTERVAL = 5
BULLET_TIMER = 0

# 怪物参数
MONSTER_SIZE = 30
MONSTER_SPEED = 2
MONSTERS = []
MONSTER_SPAWN_RATE = 60
MONSTER_SPAWN_TIMER = 0
MONSTERS_KILLED = 0
MONSTERS_TO_SPAWN_BOSS = 5  # 修改为 5 以便测试

# Boss 参数
BOSS_SIZE = 80
BOSS_X = WIDTH // 2 - BOSS_SIZE // 2
BOSS_Y = 50
BOSS_HEALTH = 100
BOSS_MAX_HEALTH = 100
BOSS_ACTIVE = False  # 初始设置为False
BOSS = None
BOSS_BULLETS = []
BOSS_BULLET_SPEED = 5
BOSS_ATTACK_INTERVAL = 120  # BOSS攻击频率
BOSS_ATTACK_TIMER = 0

# 游戏状态
PLAYER_LEVEL = 1
PLAYER_EXP = 0
EXP_PER_LEVEL = 5
BULLET_ROWS = 1
GAME_STATE = "PLAYING"

# 其他参数
FPS = 60
clock = pygame.time.Clock()


def draw_player(x, y):
    pygame.draw.rect(screen, WHITE, (x, y, PLAYER_SIZE, PLAYER_SIZE))


def draw_bullet(x, y):
    pygame.draw.rect(screen, BULLET_COLOR, (x, y, BULLET_SIZE, BULLET_SIZE))


def draw_monster(x, y):
    pygame.draw.rect(screen, RED, (x, y, MONSTER_SIZE, MONSTER_SIZE))


def draw_boss(x, y):
    pygame.draw.rect(screen, BLUE, (x, y, BOSS_SIZE, BOSS_SIZE))


def draw_boss_bullet(x, y):
    pygame.draw.rect(screen, YELLOW, (x, y, BULLET_SIZE,
                     BULLET_SIZE))  # 使用黄色绘制BOSS子弹


def create_bullet(player_x, player_y):
    global bullets
    start_y = player_y
    for row in range(BULLET_ROWS):
        y = start_y - row * BULLET_SIZE * 1.5
        angle = random.uniform(0, 2 * math.pi)
        bullet = {
            "x": player_x + PLAYER_SIZE // 2 - BULLET_SIZE // 2,
            "y": y,
            "angle": angle,
            "speed": BULLET_SPEED
        }
        bullets.append(bullet)


def create_monster():
    x = random.randint(0, WIDTH - MONSTER_SIZE)
    y = 0
    MONSTERS.append({"x": x, "y": y})


def create_boss():
    global BOSS_ACTIVE, BOSS
    BOSS = {
        "x": BOSS_X,
        "y": BOSS_Y,
        "health": BOSS_HEALTH,
        "speed": 1,  # 初始化BOSS的速度
        "bullets": []  # 初始化 BOSS 的子弹列表
    }
    BOSS_ACTIVE = True


def create_boss_bullet(boss_x, boss_y):
    global BOSS_BULLETS
    angle = math.pi/2
    bullet = {
        "x": boss_x + BOSS_SIZE // 2 - BULLET_SIZE // 2,
        "y": boss_y + BOSS_SIZE,
        "angle": angle,
        "speed": BOSS_BULLET_SPEED
    }
    BOSS_BULLETS.append(bullet)


def handle_bullets():
    global bullets
    bullets_to_remove = []
    for bullet in bullets:
        bullet["x"] += bullet["speed"] * math.cos(bullet["angle"])
        bullet["y"] += bullet["speed"] * math.sin(bullet["angle"])
        if bullet["x"] < 0 or bullet["x"] > WIDTH or bullet["y"] < 0 or bullet["y"] > HEIGHT:
            bullets_to_remove.append(bullet)
    for bullet in bullets_to_remove:
        if bullet in bullets:
            bullets.remove(bullet)


def handle_monsters():
    global MONSTERS
    monsters_to_remove = []
    for monster in MONSTERS:
        monster["y"] += MONSTER_SPEED
        if monster["y"] > HEIGHT:
            monsters_to_remove.append(monster)
    for monster in monsters_to_remove:
        if monster in MONSTERS:
            MONSTERS.remove(monster)

    # 每次刷新怪物后增加计数,确保BOSS可以正常出现
    global MONSTERS_KILLED
    MONSTERS_KILLED += 1


def handle_boss():
    global BOSS, BOSS_ACTIVE, BOSS_ATTACK_TIMER, BOSS_BULLETS
    if BOSS_ACTIVE and BOSS:  # 确保 BOSS 对象存在
        BOSS["x"] += BOSS["speed"]
        if BOSS["x"] <= 0 or BOSS["x"] >= WIDTH - BOSS_SIZE:
            BOSS["speed"] *= -1

        BOSS_ATTACK_TIMER += 1
        if BOSS_ATTACK_TIMER >= BOSS_ATTACK_INTERVAL:
            create_boss_bullet(BOSS["x"], BOSS["y"])
            BOSS_ATTACK_TIMER = 0

        bullets_to_remove = []
        for bullet in BOSS_BULLETS:
            bullet["y"] += bullet["speed"]
            if bullet["y"] < 0 or bullet["y"] > HEIGHT:
                bullets_to_remove.append(bullet)
        for bullet in bullets_to_remove:
            if bullet in BOSS_BULLETS:
                BOSS_BULLETS.remove(bullet)


def check_collisions():
    # 添加 player_x, player_y 为全局变量
    global MONSTERS, PLAYER_EXP, PLAYER_LEVEL, BULLET_ROWS, MONSTERS_KILLED, BOSS, BOSS_ACTIVE, GAME_STATE, PLAYER_HEALTH, BOSS_BULLETS, player_x, player_y

    bullets_to_remove = []
    monsters_to_remove = []

    if GAME_STATE == "PLAYING":
        for bullet in bullets:
            for monster in MONSTERS:
                if (bullet["x"] < monster["x"] + MONSTER_SIZE and
                    bullet["x"] + BULLET_SIZE > monster["x"] and
                    bullet["y"] < monster["y"] + MONSTER_SIZE and
                        bullet["y"] + BULLET_SIZE > monster["y"]):
                    bullets_to_remove.append(bullet)
                    monsters_to_remove.append(monster)
                    PLAYER_EXP += 1
                    break

        for monster in MONSTERS:
            if (player_x < monster["x"] + MONSTER_SIZE and
                player_x + PLAYER_SIZE > monster["x"] and
                player_y < monster["y"] + MONSTER_SIZE and
                    player_y + PLAYER_SIZE > monster["y"]):
                PLAYER_HEALTH -= 5  # 玩家与怪物碰撞减血

        for bullet in bullets_to_remove:
            if bullet in bullets:
                bullets.remove(bullet)
        for monster in monsters_to_remove:
            if monster in MONSTERS:
                MONSTERS.remove(monster)

    elif GAME_STATE == "BOSS_FIGHT":
        for bullet in bullets:
            if (bullet["x"] < BOSS["x"] + BOSS_SIZE and
                bullet["x"] + BULLET_SIZE > BOSS["x"] and
                bullet["y"] < BOSS["y"] + BOSS_SIZE and
                    bullet["y"] + BULLET_SIZE > BOSS["y"]):
                bullets_to_remove.append(bullet)
                BOSS["health"] -= 1

        for bullet in BOSS_BULLETS:
            if (player_x < bullet["x"] + BULLET_SIZE and
                player_x + PLAYER_SIZE > bullet["x"] and
                player_y < bullet["y"] + BULLET_SIZE and
                    player_y + PLAYER_SIZE > bullet["y"]):
                PLAYER_HEALTH -= 10

        for bullet in bullets_to_remove:
            if bullet in bullets:
                bullets.remove(bullet)
        if BOSS["health"] <= 0:
            GAME_STATE = "WIN"
            BOSS_ACTIVE = False

    if PLAYER_EXP >= EXP_PER_LEVEL:
        PLAYER_LEVEL += 1
        PLAYER_EXP = 0
        BULLET_ROWS += 1
        print(f"Level up to {PLAYER_LEVEL}, Bullet Rows: {BULLET_ROWS}")


def draw_text(text, x, y, color, font_size):
    font = pygame.font.Font(None, font_size)
    text_surface = font.render(text, True, color)
    text_rect = text_surface.get_rect(topleft=(x, y))
    screen.blit(text_surface, text_rect)


def draw_health_bar(x, y, health, max_health):
    BAR_WIDTH = 100
    BAR_HEIGHT = 10
    fill = (health / max_health) * BAR_WIDTH
    outline_rect = pygame.Rect(x, y, BAR_WIDTH, BAR_HEIGHT)
    fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)
    pygame.draw.rect(screen, RED, fill_rect)
    pygame.draw.rect(screen, WHITE, outline_rect, 2)


def draw_player_health(x, y, health, max_health):
    BAR_WIDTH = 150
    BAR_HEIGHT = 15
    fill = (health / max_health) * BAR_WIDTH
    outline_rect = pygame.Rect(x, y, BAR_WIDTH, BAR_HEIGHT)
    fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)
    pygame.draw.rect(screen, GREEN, fill_rect)
    pygame.draw.rect(screen, WHITE, outline_rect, 2)

回复

使用道具 举报

4

主题

29

帖子

707

积分

高级会员

Rank: 4

积分
707
 楼主| 发表于 2025-1-11 15:34:19 | 显示全部楼层
[Python] 纯文本查看 复制代码
def main():
    global MONSTER_SPAWN_TIMER, BULLET_TIMER, PLAYER_Y, MONSTERS_KILLED, BOSS_ACTIVE, GAME_STATE, MONSTERS, bullets, BOSS, PLAYER_HEALTH, BOSS_BULLETS, player_x, player_y  # 添加全局变量声明
    player_x = PLAYER_X
    player_y = PLAYER_Y

    running = True

    # 在游戏开始时初始化几个小怪
    for _ in range(3):
        create_monster()

    while running:
        try:  # 异常处理
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

            keys = pygame.key.get_pressed()
            if keys[pygame.K_LEFT]:
                player_x -= PLAYER_SPEED
            if keys[pygame.K_RIGHT]:
                player_x += PLAYER_SPEED
            if keys[pygame.K_UP]:
                player_y -= PLAYER_SPEED
            if keys[pygame.K_DOWN]:
                player_y += PLAYER_SPEED

            # 保持玩家在屏幕内
            player_x = max(0, min(player_x, WIDTH - PLAYER_SIZE))
            player_y = max(0, min(player_y, HEIGHT - PLAYER_SIZE))

            # 长按空格持续发射子弹
            if keys[pygame.K_SPACE]:
                BULLET_TIMER += 1
                if BULLET_TIMER >= BULLET_INTERVAL:
                    create_bullet(player_x, player_y)
                    BULLET_TIMER = 0

            screen.fill(BLACK)

            if GAME_STATE == "PLAYING":
                draw_player(player_x, player_y)
                handle_bullets()
                for bullet in bullets:
                    draw_bullet(bullet["x"], bullet["y"])

                handle_monsters()
                for monster in MONSTERS:
                    draw_monster(monster["x"], monster["y"])

                MONSTER_SPAWN_TIMER += 1
                if MONSTER_SPAWN_TIMER >= MONSTER_SPAWN_RATE:
                    create_monster()
                    MONSTER_SPAWN_TIMER = 0

                # 修改此处, 增加条件判断,只有当列表为空时,并且击杀数量达到要求,才会生成 BOSS
                if MONSTERS_KILLED >= MONSTERS_TO_SPAWN_BOSS and not MONSTERS:
                    GAME_STATE = "BOSS_FIGHT"
                    create_boss()
                    MONSTERS = []

            elif GAME_STATE == "BOSS_FIGHT":
                draw_player(player_x, player_y)
                handle_bullets()
                for bullet in bullets:
                    draw_bullet(bullet["x"], bullet["y"])

                handle_boss()
                if BOSS_ACTIVE and BOSS:  # 确保 BOSS 对象存在
                    draw_boss(BOSS["x"], BOSS["y"])
                    draw_health_bar(BOSS["x"], BOSS["y"] -
                                    20, BOSS["health"], BOSS_MAX_HEALTH)
                    for bullet in BOSS_BULLETS:
                        draw_boss_bullet(bullet["x"], bullet["y"])

            elif GAME_STATE == "WIN":
                draw_text("You Win!!!", WIDTH // 2 -
                          100, HEIGHT // 2, WHITE, 60)

            check_collisions()

            if GAME_STATE != "WIN":
                draw_text(
                    f"Level: {PLAYER_LEVEL}  Exp: {PLAYER_EXP}/{EXP_PER_LEVEL}", 10, 10, WHITE, 24)
                draw_player_health(10, 40, PLAYER_HEALTH, PLAYER_MAX_HEALTH)

            if PLAYER_HEALTH <= 0:
                GAME_STATE = "GAME_OVER"
                draw_text("GAME OVER", WIDTH // 2 -
                          100, HEIGHT // 2, WHITE, 60)

            if GAME_STATE == "GAME_OVER":
                pygame.display.flip()
                time.sleep(3)
                break

            pygame.display.flip()
            clock.tick(FPS)

        except Exception as e:
            print(f"An error occurred: {e}")
            # 不再直接退出循环,而是继续运行,避免一闪而过

    # 主循环结束后等待一段时间
    time.sleep(3)  # 等待3秒
    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 中文实名注册

本版积分规则

小黑屋|东台市机器人学会 ( 苏ICP备2021035350号-1;苏ICP备2021035350号-2;苏ICP备2021035350号-3 )

GMT+8, 2025-2-12 12:53 , Processed in 0.041002 second(s), 28 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表