找回密码
 中文实名注册
搜索
查看: 1212|回复: 2

恐怖严思宇1.0 沈熠

[复制链接]

5

主题

29

回帖

1248

积分

金牌会员

积分
1248
发表于 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)

回复

使用道具 举报

5

主题

29

回帖

1248

积分

金牌会员

积分
1248
 楼主| 发表于 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()
回复

使用道具 举报

5

主题

29

回帖

1248

积分

金牌会员

积分
1248
 楼主| 发表于 2026-4-19 10:07:22 | 显示全部楼层
import tkinter as tkfrom tkinter import ttk, messageboximport timeimport random# 主窗口设置root = tk.Tk()root.title("🇨🇳 红军二万五千里长征模拟器")root.geometry("900x600")root.resizable(False, False)root.configure(bg="#f0f5ff")# 长征关键节点(按时间顺序)long_march_nodes = [    "瑞金出发", "突破湘江", "四渡赤水", "巧渡金沙江",    "强渡大渡河", "飞夺泸定桥", "翻越夹金山", "懋功会师",    "过草地", "吴起镇会师", "会宁会师"]# 节点坐标(对应画布位置)node_positions = [(50, 500), (150, 480), (250, 420), (350, 380),                  (450, 350), (550, 320), (650, 280), (700, 250),                  (750, 300), (800, 350), (850, 400)]# 画布(地图区域)canvas = tk.Canvas(root, width=900, height=500, bg="#e6f2ff")canvas.pack(pady=10)# 绘制长征路线(灰色虚线)for i in range(len(node_positions)-1):    x1, y1 = node_positions    x2, y2 = node_positions[i+1]    canvas.create_line(x1, y1, x2, y2, fill="#666666", dash=(5, 5), width=2)# 绘制关键节点(圆形标记+文字)node_tags = []for i, (name, (x, y)) in enumerate(zip(long_march_nodes, node_positions)):    # 节点圆    node = canvas.create_oval(x-15, y-15, x+15, y+15, fill="#c0392b", outline="white", width=2)    node_tags.append(node)    # 节点文字    canvas.create_text(x, y-25, text=name, font=("宋体", 9, "bold"), fill="#2c3e50")# 红军队伍(用小红点表示,初始在瑞金)army = []for _ in range(15):    x = node_positions[0][0] + random.randint(-10, 10)    y = node_positions[0][1] + random.randint(-10, 10)    dot = canvas.create_oval(x-2, y-2, x+2, y+2, fill="#e74c3c", tag="army")    army.append(dot)# 国旗元素(初始隐藏)flag = Noneflag_pole = Nonecurrent_node_index = 0  # 当前行进到的节点索引march_state = "ready"   # ready: 准备, marching: 行军中, finished: 会师完成, flag: 升国旗# 状态标签status_label = ttk.Label(root, text="准备开始红军二万五千里长征模拟", font=("黑体", 12))status_label.pack(pady=5)# 行军动画函数def march_army():    global current_node_index, march_state    if march_state != "ready":        return    march_state = "marching"    status_label.config(text=f"正在行军:{long_march_nodes[0]} → {long_march_nodes[1]}")        while current_node_index < len(long_march_nodes)-1:        # 目标节点坐标        target_x, target_y = node_positions[current_node_index+1]        # 移动红军队伍        for dot in army:            dx = (target_x - canvas.coords(dot)[0]) / 50            dy = (target_y - canvas.coords(dot)[1]) / 50            for _ in range(50):                canvas.move(dot, dx, dy)                root.update()                time.sleep(0.01)        # 点亮当前节点        canvas.itemconfig(node_tags[current_node_index+1], fill="#27ae60")        current_node_index += 1        # 更新状态        if current_node_index < len(long_march_nodes)-1:            status_label.config(text=f"成功抵达:{long_march_nodes[current_node_index]} → 下一站:{long_march_nodes[current_node_index+1]}")        else:            status_label.config(text=f"🎉 成功抵达:{long_march_nodes[current_node_index]},长征胜利会师!")        root.update()        time.sleep(1)        march_state = "finished"    time.sleep(2)    raise_flag()  # 会师完成后升国旗# 升国旗函数def raise_flag():    global flag, flag_pole, march_state    march_state = "flag"    status_label.config(text="🇨🇳 升起五星红旗,致敬长征英雄!")        # 清空画布多余元素,突出国旗    canvas.delete("army")    for i in range(len(node_tags)):        canvas.itemconfig(node_tags, fill="#95a5a6")        # 绘制旗杆    flag_pole = canvas.create_line(450, 450, 450, 100, fill="#7f8c8d", width=5)    # 绘制国旗(红色旗面+黄色五角星)    flag_width = 120    flag_height = 80    flag_y_start = 450 - flag_height    # 红旗面    flag = canvas.create_rectangle(        450, flag_y_start, 450 + flag_width, flag_y_start + flag_height,        fill="#e74c3c", outline="white", width=1    )    # 大五角星    canvas.create_text(470, flag_y_start + 20, text="★", fill="yellow", font=("Arial", 20, "bold"))    # 小五角星    small_stars_pos = [(520, 120), (530, 150), (520, 180), (500, 160)]    for x, y in small_stars_pos:        canvas.create_text(x, y, text="★", fill="yellow", font=("Arial", 10, "bold"))        # 升旗动画    for _ in range(175):        canvas.move(flag, 0, -2)        for x, y in small_stars_pos:            star = canvas.create_text(x, y - _*2, text="★", fill="yellow", font=("Arial", 10 if x!=470 else 20, "bold"))        root.update()        time.sleep(0.02)        status_label.config(text="🎖️ 长征精神永垂不朽!五星红旗永远飘扬!")    messagebox.showinfo("模拟完成", "红军二万五千里长征模拟成功!\n铭记历史,致敬先烈!")# 重置模拟函数def reset_simulation():    global current_node_index, march_state, army    current_node_index = 0    march_state = "ready"    status_label.config(text="准备开始红军二万五千里长征模拟")        # 清空画布    canvas.delete("all")    # 重新绘制路线和节点    for i in range(len(node_positions)-1):        x1, y1 = node_positions        x2, y2 = node_positions[i+1]        canvas.create_line(x1, y1, x2, y2, fill="#666666", dash=(5, 5), width=2)    node_tags.clear()    for i, (name, (x, y)) in enumerate(zip(long_march_nodes, node_positions)):        node = canvas.create_oval(x-15, y-15, x+15, y+15, fill="#c0392b", outline="white", width=2)        node_tags.append(node)        canvas.create_text(x, y-25, text=name, font=("宋体", 9, "bold"), fill="#2c3e50")    # 重新生成红军队伍    army = []    for _ in range(15):        x = node_positions[0][0] + random.randint(-10, 10)        y = node_positions[0][1] + random.randint(-10, 10)        dot = canvas.create_oval(x-2, y-2, x+2, y+2, fill="#e74c3c", tag="army")        army.append(dot)# 按钮区域btn_frame = ttk.Frame(root)btn_frame.pack(pady=5)start_btn = ttk.Button(btn_frame, text="🚩 开始长征模拟", command=march_army)start_btn.pack(side="left", padx=10)reset_btn = ttk.Button(btn_frame, text="🔄 重置模拟", command=reset_simulation)reset_btn.pack(side="left", padx=10)# 启动主循环root.mainloop()
回复

使用道具 举报

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

本版积分规则

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