序
做梦也没想到能再次开始这个系列……
正文
我实在太想玩游戏了,但微软神秘的未成年学生账户有网站限制,没有HTTPS安全标就要向家长申请站点.(见图1)

于是我一咬牙一跺脚,打开我几百年没打开的python 3.14。想用TA来编写游戏,但是蒟蒻能力有限,DEV-C++(见文章AI创游_迷失森林寻宝记)纯文本编写已经很累了,那我该如何做一个小游戏呢?
这么点困难一下就难倒了我,上网一搜教程,python竟然有专门的2D游戏编写库(pygame),让AI传授我如何下载,接下来就是AI头疼我也头疼的AI编写过程。
不过没关系,好歹从小刷视频的蒟蒻非常有游戏经验,知道恐怖游戏才有神秘感,才能“打动”玩家。
计划有了,那就展开讲讲,打开TRAE(问小白夯完了,建议都别用了),兴致冲冲让TA给我生成一个恐怖游戏,果不其然,这样的问法换任何一个AI都只能吐出一堆垃圾,毫无营养和价值。
还是得写文案,仔细写提示词。
TWO HOURS LATER……
我是这么构思的,做一个《黑暗欺骗》的2D版,加入《玩具熊的午夜后宫》里的元素(这是我非常喜欢的经典恐怖游戏),所以我很快就搓出来近300字的提示词。
后续还陆陆续续写了300字左右的提示词,用来修正代码功能和优化性能等。
OK,总而言之言而总之,这次用正规游戏编写工具编写游戏就是正规(废话)。
代码呈现
import pygame
import sys
import random
import math
from collections import defaultdict
# ================= 1. 初始化与常量 =================
pygame.init()
pygame.font.init()
SCREEN_W, SCREEN_H = 960, 720
FPS_TARGET = 30
TILE = 40
# 颜色定义 (复古/恐怖风格)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
WALL_COL = (35, 35, 45)
FLOOR_COL = (18, 18, 22)
PLAYER_COL = (0, 180, 120)
SHARD_COL = (0, 200, 255)
EXIT_COL_LOCKED = (60, 60, 60)
EXIT_COL_OPEN = (255, 180, 0)
RED_TINT = (200, 0, 0)
ITEM_BATTERY = (0, 220, 80)
ITEM_RADAR = (180, 100, 255)
ITEM_EAGLE = (220, 220, 220)
ENEMY_VISUAL = (180, 40, 40)
ENEMY_AUDIO = (40, 60, 180)
BOSS_COL = (100, 0, 0)
UI_BG = (10, 10, 15)
UI_BORDER = (50, 50, 60)
# ================= 2. 多语言与剧情系统 =================
LANG = {"current": "zh"}
STORY_TEXTS = {
"zh": {
"night_intro": [
"第一夜:入职培训",
"第二夜:深入黑暗",
"第三夜:机械之心",
"第四夜:绝望回响",
"第五夜:终极逃脱"
],
"night_desc": [
"你是一名新来的夜间保安。这里以前是个儿童乐园,但三年前发生了一场大火。那些被烧毁的玩偶,好像... 在黑暗中重新活了过来。它们在寻找什么?",
"你活过了第一夜。但这些玩偶开始记住你的气味了。迷宫变得更大,出口也更远。你注意到墙上有奇怪的符文——这不是普通的乐园。",
"一个巨大的红色身影出现在走廊尽头。它是乐园曾经的吉祥物,现在却成了最恐怖的存在。它虽然笨拙,但一旦锁定你,就绝不放手。那些碎片似乎和它有关。",
"电量在飞速流失。你发现了一个惊人的秘密:这些玩偶不是普通的机械玩具。它们体内流淌着某种黑暗能量,而碎片就是能量的容器。不要相信你的眼睛。",
"这是最后一晚。你终于明白真相了——这个地方根本不是乐园,而是一个被诅咒的实验基地。那些玩偶是实验失败的产物。如果你能活着离开,你就自由了。但它们不会让你走。"
],
"shard_hints": [
"你拾起一块冰冷的碎片。它在掌心微微震颤,像某种沉睡之物的呼吸。碎片表面刻着奇怪的符文,似乎在诉说着什么。",
"第二块碎片。拼凑的图案让你不愿再看第二眼——那像是一张扭曲的脸。你听见远处传来齿轮转动的声音。",
"第三块。你听见墙后传来窸窣声——它们也在寻找这些碎片。这些碎片似乎有某种力量,能唤醒... 什么东西。",
"第四块。空气越来越沉重,玩偶们的关节在黑暗中咔咔作响。碎片发出微弱的光芒,照亮了周围的黑暗。",
"最后一块!出口的低吼撕裂了寂静。跑,趁它们还没有完全醒来。你感觉到一股强大的力量正在苏醒——那是被碎片封印的东西。"
],
"item_hints": {
"battery": "一节老旧的电池。电量缓缓回升,但你能听见远处有东西被电流声吸引。这电池上刻着和碎片一样的符文。",
"radar": "雷达发出刺耳的嗡鸣。屏幕上出现了红色的光点——它们在移动。也许你不该让它发出这么大的声音。",
"eagle": "夜视药剂滑入喉咙。视野清晰了,可你分明看见黑暗中有更多眼睛睁开了。这药剂似乎让你能看到... 不该看到的东西。"
},
"endings": {
"good": "你逃出了黑暗回廊。大门在你身后轰然关闭,将那些恐怖的玩偶永远锁在了里面。但当你回头望去,门上那只巨大的红色眼睛似乎还在注视着你。那些玩偶的眼睛,会永远留在你的噩梦中...",
"bad": "黑暗吞没了你。玩偶们围拢过来,用空洞的眼眶注视着你。你听见它们低语:很快,你就会成为我们中的一员... 永远。你的意识逐渐模糊,最后看到的是那些红色的眼睛——和你自己的眼睛一样空洞。",
"secret": "你集齐了所有碎片,发现了乐园的真相。原来,你也曾是这里的孩子。那场大火夺走了你的生命,但某种黑暗力量将你复活,成为了新的保安——一个永远无法逃脱的保安。你被困在这里,永远重复着同样的夜晚..."
}
},
"en": {
"night_intro": [
"Night 1: Orientation",
"Night 2: Into the Dark",
"Night 3: Mechanical Heart",
"Night 4: Desperate Echoes",
"Night 5: Final Escape"
],
"night_desc": [
"You are a new night guard. This used to be a playground, but three years ago a fire destroyed everything. Those burned toys... they seem to have come alive again in the darkness. What are they searching for?",
"You survived the first night. But these toys are starting to remember your scent. The maze is bigger, and the exit is further away. You notice strange runes on the walls—this isn't an ordinary playground.",
"A huge red figure appears at the end of the corridor. It was the park's once-beloved mascot, now transformed into something terrifying. It's clumsy, but once it locks on, it never lets go. Those shards seem connected to it.",
"Power is draining fast. You discover a terrifying secret: these toys aren't ordinary machines. Something dark flows within them, and the shards are containers for that energy. Don't trust your eyes.",
"This is the last night. You finally understand the truth—this place was never a playground, but a cursed research facility. The toys are failed experiments. If you can leave alive, you are free. But they won't let you go."
],
"shard_hints": [
"You pick up a cold shard. It trembles in your palm, like the breath of something sleeping. Strange runes cover its surface, as if telling a story.",
"A second shard. The pattern it forms is not one you want to look at twice—it resembles a twisted face. You hear gears turning in the distance.",
"A third. You hear rustling behind the walls—they are searching for these too. The shards seem to possess some kind of power, capable of awakening... something.",
"A fourth. The air grows heavy; joints of the toys click in the dark. The shard emits a faint glow, illuminating the darkness around you.",
"The last one! The exit roars through the silence. Run, before they fully wake. You feel a powerful force stirring—the thing sealed within the shards is awakening."
],
"item_hints": {
"battery": "An old battery. Power returns slowly, but you hear something far away drawn to the current. This battery bears the same runes as the shards.",
"radar": "The radar emits a harsh hum. Red dots appear on the screen—they are moving. Perhaps you shouldn't have made so much noise.",
"eagle": "The night-vision tonic slides down your throat. Your sight clears, yet more eyes open in the dark. This tonic seems to let you see... things you weren't meant to see."
},
"endings": {
"good": "You escaped the Dark Corridor. The massive doors slam shut behind you, locking those horrifying toys away forever. But as you look back, the giant red eye on the door seems to be watching you. Those eyes will haunt your dreams forever...",
"bad": "Darkness swallows you. The toys gather, gazing with hollow sockets. You hear them whisper: soon, you will become one of us... forever. Your consciousness fades, and the last thing you see is those red eyes—empty, just like yours.",
"secret": "You collected all shards and discovered the truth. You were once a child here too. The fire took your life, but something dark resurrected you as a new security guard—a guard who can never escape. You're trapped here, repeating the same night forever..."
}
}
}
TEXTS = {
"en": {
"power": "POWER", "shards": "SHARDS", "time": "TIME",
"hint": "[F] Flashlight [SHIFT] Run [H] Map(5s) [T] Lang",
"find": "Find 5 Shards. Beware of Animatronics.",
"exit_open": "EXIT OPEN! ESCAPE!",
"caught": "THE DARKNESS CLAIMS YOU", "escaped": "SURVIVED!",
"play_again": "Press R to Retry / N for Next Night", "eagle": "NIGHT VISION",
"radar": "RADAR ACTIVE!", "night": "NIGHT",
"map_cd": "MAP COOLDOWN", "map_on": "MAP ACTIVE",
"start_game": "PRESS ENTER TO START", "game_title": "DARK CORRIDOR",
"press_enter_continue": "PRESS ENTER TO CONTINUE",
"night_x": "NIGHT", "of": "OF",
"map_cooldown_hint": "Map cooling down, please wait...",
"enemy_nearby": "WARNING: Enemy nearby!",
"boss_nearby": "DANGER: Giant approaching!",
"power_low": "WARNING: Low battery!",
"radar_spotted": "Radar detected enemy signals!"
},
"zh": {
"power": "电量", "shards": "碎片", "time": "用时",
"hint": "[F] 手电 [SHIFT] 奔跑 [H] 地图(5s) [T] 语言",
"find": "收集5个碎片。它们醒着,它们在听。",
"exit_open": "出口已开启!快逃!",
"caught": "你倒下了... 黑暗中有东西在笑。", "escaped": "逃脱成功!",
"play_again": "按 R 重试 / N 下一夜", "eagle": "夜视模式",
"radar": "雷达扫描中!", "night": "第",
"map_cd": "地图冷却中", "map_on": "地图显示中",
"start_game": "按回车键开始", "game_title": "黑暗回廊",
"press_enter_continue": "按回车键继续",
"night_x": "第", "of": "夜",
"map_cooldown_hint": "地图冷却中,请等待...",
"enemy_nearby": "警告:附近有敌人!",
"boss_nearby": "危险:巨物正在靠近!",
"power_low": "警告:电量不足!",
"radar_spotted": "雷达探测到敌人信号!"
}
}
def t(key):
return TEXTS[LANG["current"]].get(key, key)
# ================= 3. 字体安全加载 =================
def get_font(size):
font_names = ["microsoftyahei", "msyh.ttc", "SimHei", "Arial Unicode MS", "Microsoft YaHei UI", "Courier New"]
for name in font_names:
try:
f = pygame.font.SysFont(name, size)
if f and f.size("Test")[0] > 0: return f
except Exception: continue
try: return pygame.font.SysFont(None, size)
except Exception: return pygame.font.Font(None, size)
FONT_SM = get_font(18)
FONT_MD = get_font(26)
FONT_LG = get_font(42)
FONT_XL = get_font(64)
# ================= 4. 地图生成:房间+走廊 (高连通性) =================
def generate_connected_maze(cols, rows, num_rooms=8):
"""生成带有多个环路的迷宫,适合追逐战"""
maze = [[1] * cols for _ in range(rows)]
# 1. 生成随机房间
rooms = []
for _ in range(num_rooms):
w = random.randint(3, 6)
h = random.randint(3, 6)
x = random.randint(1, cols - w - 1)
y = random.randint(1, rows - h - 1)
rooms.append((x, y, w, h))
for ry in range(y, y + h):
for rx in range(x, x + w):
if 0 < rx < cols - 1 and 0 < ry < rows - 1:
maze[ry][rx] = 0
# 2. 连接房间 (确保连通性)
def connect_rooms(r1, r2):
c1 = (r1[0] + r1[2]//2, r1[1] + r1[3]//2)
c2 = (r2[0] + r2[2]//2, r2[1] + r2[3]//2)
cx, cy = c1
while cx != c2[0]:
if 0 < cx < cols - 1 and 0 < cy < rows - 1: maze[cy][cx] = 0
cx += 1 if c2[0] > cx else -1
while cy != c2[1]:
if 0 < cx < cols - 1 and 0 < cy < rows - 1: maze[cy][cx] = 0
cy += 1 if c2[1] > cy else -1
for i in range(len(rooms) - 1):
connect_rooms(rooms[i], rooms[i+1])
# 额外连接一些房间形成环路
if len(rooms) > 2:
connect_rooms(rooms[0], rooms[-1])
connect_rooms(rooms[random.randint(0, len(rooms)//2)], rooms[-1])
# 3. 预处理空间哈希
walls = []
segments = []
vertices = set()
SPATIAL_GRID_SIZE = TILE * 2
spatial_grid = defaultdict(list)
seg_spatial_grid = defaultdict(list)
for r in range(rows):
for c in range(cols):
if maze[r][c] == 1:
rect = pygame.Rect(c*TILE, r*TILE, TILE, TILE)
walls.append(rect)
pts = [(rect.left, rect.top), (rect.right, rect.top),
(rect.right, rect.bottom), (rect.left, rect.bottom)]
for i in range(4):
p1, p2 = pts[i], pts[(i+1)%4]
seg = (p1[0], p1[1], p2[0], p2[1])
segments.append(seg)
vertices.add(p1)
gx, gy = int(p1[0] // SPATIAL_GRID_SIZE), int(p1[1] // SPATIAL_GRID_SIZE)
spatial_grid[(gx, gy)].append(p1)
seg_spatial_grid[(gx, gy)].append(seg)
gx2, gy2 = int(p2[0] // SPATIAL_GRID_SIZE), int(p2[1] // SPATIAL_GRID_SIZE)
if (gx2, gy2) != (gx, gy):
seg_spatial_grid[(gx2, gy2)].append(seg)
return maze, walls, segments, list(vertices), spatial_grid, seg_spatial_grid
# ================= 5. 核心类 =================
class Player:
def __init__(self, pos):
self.rect = pygame.Rect(pos[0]*TILE+8, pos[1]*TILE+8, 24, 24)
self.speed = 2.4
self.run_speed = 4.2
self.power = 100.0
self.flashlight = True
self.shards = 0
self.max_shards = 5
self.running = False
self.noise_level = 0
self.facing = (0, 1)
self.eagle_time = 0
self.radar_time = 0
# 小地图独立电力系统
self.map_power = 225 # 5秒上限 (45fps)
self.MAX_MAP_POWER = 225
self.map_cooldown = 0
self.MAP_COOLDOWN_MAX = 225 # 5秒冷却
class Enemy:
def __init__(self, pos, etype, is_boss=False):
self.rect = pygame.Rect(pos[0]*TILE+4, pos[1]*TILE+4, 32, 32)
self.etype = etype
self.is_boss = is_boss
self.base_speed = 1.8 if is_boss else (2.0 if etype == "visual" else 2.4)
self.chase_speed = 4.5 if is_boss else (5.2 if etype == "visual" else 5.5)
self.state = "PATROL"
self.dir = (1, 0)
self.patrol_timer = 0
self.lose_timer = 0
self.eye_glow = 0
self.target_pos = None
# BOSS 巡逻点
self.patrol_points = []
self.current_patrol_idx = 0
# 感知范围
self.sight_range = 450 if etype == "visual" else 300
self.hear_range = 300 if etype == "audio" else 200
# 共享追踪
self.shared_target = None
self.shared_timer = 0
# BOSS 绕墙相关
self.wall_following = False
self.wall_dir = 0
self.wall_timer = 0
self.wall_stuck_count = 0
self.original_chase_angle = 0
class Item:
def __init__(self, pos, itype):
self.rect = pygame.Rect(pos[0]*TILE+10, pos[1]*TILE+10, 20, 20)
self.itype = itype
self.active = True
# ================= 6. 工具函数 =================
def move_with_collision(rect, dx, dy, walls, map_width=None, map_height=None):
if not walls: return
if not isinstance(rect, pygame.Rect): return
try:
original_x = rect.x
original_y = rect.y
if dx != 0:
rect.x += dx
collided_indices = rect.collidelistall(walls)
if collided_indices:
for idx in collided_indices:
w = walls[idx]
if dx > 0:
if rect.right > w.left and rect.right > w.right:
rect.left = w.right
else:
rect.right = w.left
elif dx < 0:
if rect.left < w.right and rect.left < w.left:
rect.right = w.left
else:
rect.left = w.right
collided_indices2 = rect.collidelistall(walls)
if collided_indices2:
rect.x = original_x
if dy != 0:
rect.y += dy
collided_indices = rect.collidelistall(walls)
if collided_indices:
for idx in collided_indices:
w = walls[idx]
if dy > 0:
if rect.bottom > w.top and rect.bottom > w.bottom:
rect.top = w.bottom
else:
rect.bottom = w.top
elif dy < 0:
if rect.top < w.bottom and rect.top < w.top:
rect.bottom = w.top
else:
rect.top = w.bottom
collided_indices2 = rect.collidelistall(walls)
if collided_indices2:
rect.y = original_y
if map_width is not None and map_height is not None:
if rect.left < 0: rect.left = 0
if rect.right > map_width: rect.right = map_width
if rect.top < 0: rect.top = 0
if rect.bottom > map_height: rect.bottom = map_height
except Exception as e:
print(f"碰撞检测异常: {e}")
def get_furthest_points(maze, count, exclude=None):
"""使用简化版最远点采样,确保物品分散"""
if exclude is None: exclude = set()
floors = [(c,r) for r in range(len(maze)) for c in range(len(maze[0]))
if maze[r][c]==0 and (c,r) not in exclude]
if not floors:
fallback = []
for r in range(1, len(maze)-1):
for c in range(1, len(maze[0])-1):
if maze[r][c] == 0 and len(fallback) < count:
fallback.append((c, r))
if not fallback and len(maze) > 2 and len(maze[0]) > 2:
fallback.append((1, 1))
return fallback[:count]
count = min(count, len(floors))
if count <= 0:
if len(maze) > 2 and len(maze[0]) > 2:
return [(1, 1)]
return []
points = [random.choice(floors)]
for _ in range(count - 1):
best_point = None
max_min_dist = -1
for p in floors:
if p in points: continue
min_dist = min([math.hypot(p[0]-ex[0], p[1]-ex[1]) for ex in points])
if min_dist > max_min_dist:
max_min_dist = min_dist
best_point = p
if best_point:
points.append(best_point)
exclude.add(best_point)
return points
# ================= 7. 射线投射 (保持原有高性能版本) =================
_fog_surf = None
_hole_surf = None
_glow_surfs = {}
_border_tint_surf = None
_minimap_cache = None
_minimap_cache_key = None
def init_render_surfaces():
global _fog_surf, _hole_surf, _border_tint_surf, _glow_surfs
_glow_surfs = {}
_fog_surf = pygame.Surface((SCREEN_W, SCREEN_H), pygame.SRCALPHA)
_hole_surf = pygame.Surface((SCREEN_W, SCREEN_H), pygame.SRCALPHA)
_border_tint_surf = pygame.Surface((SCREEN_W, SCREEN_H), pygame.SRCALPHA)
if hasattr(draw_crt_overlay, '_crt_surf'):
delattr(draw_crt_overlay, '_crt_surf')
def get_glow_surf(color, radius=12, size=30):
key = (color, radius, size)
if key not in _glow_surfs:
surf = pygame.Surface((size, size), pygame.SRCALPHA)
pygame.draw.circle(surf, (*color, 80), (size//2, size//2), radius)
_glow_surfs[key] = surf
return _glow_surfs[key]
def get_visible_polygon_optimized(px, py, max_dist, segments, vertices, spatial_grid, seg_spatial_grid=None):
angles = []
for a in range(0, 360, 12):
rad = a * math.pi / 180.0
angles.append(rad)
nearby_segs = []
for seg in segments:
x1, y1, x2, y2 = seg
cx, cy = (x1+x2)/2, (y1+y2)/2
if (cx-px)**2 + (cy-py)**2 < (max_dist + TILE)**2:
nearby_segs.append(seg)
points = []
for angle in angles:
dx = math.cos(angle)
dy = math.sin(angle)
closest_t = max_dist
closest_pt = (px + dx*max_dist, py + dy*max_dist)
for seg in nearby_segs:
x1, y1, x2, y2 = seg
sx, sy = x2 - x1, y2 - y1
D = -dx * sy + dy * sx
if abs(D) < 1e-6: continue
t = ((x1 - px) * (-sy) - (y1 - py) * (-sx)) / D
u = ((x1 - px) * (-dy) - (y1 - py) * (-dx)) / D
if 0 < t < closest_t and 0 <= u <= 1:
closest_t = t
closest_pt = (px + dx*t, py + dy*t)
points.append((closest_pt, angle))
points.sort(key=lambda p: p[1])
return [p[0] for p in points]
def render_vision(screen, player, enemies, cam_x, cam_y, segments, vertices, spatial_grid, seg_spatial_grid=None):
global _fog_surf, _hole_surf
try:
px_world = player.rect.centerx
py_world = player.rect.centery
if player.eagle_time > 0:
max_dist = 600
elif player.flashlight and player.power > 0:
max_dist = 220
else:
max_dist = 90
for e in enemies:
if (px_world - e.rect.centerx)**2 + (py_world - e.rect.centery)**2 < 40000:
max_dist = 50
break
poly_world = get_visible_polygon_optimized(px_world, py_world, max_dist, segments, vertices, spatial_grid, seg_spatial_grid)
poly_screen = []
for p in poly_world:
sx = p[0] - cam_x
sy = p[1] - cam_y
if -max_dist <= sx <= SCREEN_W + max_dist and -max_dist <= sy <= SCREEN_H + max_dist:
poly_screen.append((sx, sy))
_fog_surf.fill((0, 0, 0, 245))
if len(poly_screen) >= 3:
_hole_surf.fill((0, 0, 0, 0))
try:
pygame.draw.polygon(_hole_surf, (0, 0, 0, 255), poly_screen)
_fog_surf.blit(_hole_surf, (0, 0), special_flags=pygame.BLEND_RGBA_SUB)
except Exception:
_fog_surf.fill((0, 0, 0, 200))
except Exception as e:
print(f"视野渲染异常: {e}")
_fog_surf.fill((0, 0, 0, 200))
return _fog_surf
# ================= 8. UI 辅助函数 (复古风格) =================
def draw_retro_frame(screen, text, color, y_offset=0):
"""绘制复古风格的文本框"""
surf = FONT_LG.render(text, True, color)
rect = surf.get_rect(center=(SCREEN_W//2, SCREEN_H//2 + y_offset))
# 边框背景
border_rect = rect.inflate(40, 20)
pygame.draw.rect(screen, UI_BG, border_rect)
pygame.draw.rect(screen, UI_BORDER, border_rect, 2)
# 扫描线效果
for i in range(0, border_rect.height, 4):
pygame.draw.line(screen, (0,0,0,50), (border_rect.left, border_rect.top+i), (border_rect.right, border_rect.top+i))
screen.blit(surf, rect)
def draw_crt_overlay(screen):
"""绘制 CRT 显示器扫描线(预渲染)"""
if not hasattr(draw_crt_overlay, '_crt_surf'):
crt_surf = pygame.Surface((SCREEN_W, SCREEN_H), pygame.SRCALPHA)
for i in range(0, SCREEN_H, 6):
pygame.draw.line(crt_surf, (0, 0, 0, 20), (0, i), (SCREEN_W, i))
draw_crt_overlay._crt_surf = crt_surf
screen.blit(draw_crt_overlay._crt_surf, (0, 0))
def draw_story_text(screen, title, desc, color=WHITE):
"""绘制剧情文本界面"""
screen.fill(BLACK)
title_surf = FONT_LG.render(title, True, RED_TINT)
screen.blit(title_surf, title_surf.get_rect(center=(SCREEN_W//2, SCREEN_H//3)))
words = desc
lines = []
max_width = SCREEN_W - 200
current_line = ""
for char in words:
test_line = current_line + char
if FONT_MD.size(test_line)[0] > max_width and char in ",。!?,.!? ":
lines.append(current_line)
current_line = "" if char in ",。!?,.!?" else char
else:
current_line += char
if current_line:
lines.append(current_line)
y_offset = 0
for line in lines:
line_surf = FONT_MD.render(line, True, color)
screen.blit(line_surf, line_surf.get_rect(center=(SCREEN_W//2, SCREEN_H//2 + y_offset)))
y_offset += 40
if int(pygame.time.get_ticks() / 500) % 2 == 0:
hint = FONT_SM.render(t("press_enter_continue"), True, (150, 150, 150))
screen.blit(hint, hint.get_rect(center=(SCREEN_W//2, SCREEN_H - 80)))
draw_crt_overlay(screen)
pygame.display.flip()
def show_night_intro(screen, night_level):
"""显示夜晚开场叙事"""
lang = LANG["current"]
story = STORY_TEXTS[lang]
idx = min(night_level - 1, len(story["night_intro"]) - 1)
title = f"{t('night_x')} {night_level} {t('of')} 5 - {story['night_intro'][idx]}"
desc = story["night_desc"][idx]
waiting = True
while waiting:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key in (pygame.K_RETURN, pygame.K_SPACE):
waiting = False
if event.key == pygame.K_t:
LANG["current"] = "zh" if LANG["current"]=="en" else "en"
lang = LANG["current"]
story = STORY_TEXTS[lang]
idx = min(night_level - 1, len(story["night_intro"]) - 1)
title = f"{t('night_x')} {night_level} {t('of')} 5 - {story['night_intro'][idx]}"
desc = story["night_desc"][idx]
draw_story_text(screen, title, desc)
class ToastMessage:
def __init__(self):
self.message = ""
self.timer = 0
self.alpha = 0
self._surf_cache = None
self._bg_surf_cache = None
self._last_message = ""
def show(self, msg, duration=120):
self.message = msg
self.timer = duration
self.alpha = 255
if msg != self._last_message:
self._surf_cache = None
self._last_message = msg
def update(self):
if self.timer > 0:
self.timer -= 1
if self.timer < 60:
self.alpha = int(200 * (self.timer / 60))
else:
self.alpha = 200
else:
self.alpha = 0
def draw(self, screen):
if self.alpha > 0 and self.message:
if self._surf_cache is None:
self._surf_cache = FONT_SM.render(self.message, True, (200, 180, 160))
bg_w = self._surf_cache.get_width() + 20
bg_h = self._surf_cache.get_height() + 8
self._bg_surf_cache = pygame.Surface((bg_w, bg_h), pygame.SRCALPHA)
text_surf = self._surf_cache.copy()
text_surf.set_alpha(self.alpha)
bg_surf = self._bg_surf_cache.copy()
bg_surf.fill((0, 0, 0, int(60 * self.alpha / 200)))
margin = 15
screen.blit(bg_surf, (margin, SCREEN_H - margin - bg_surf.get_height()))
screen.blit(text_surf, (margin + 10, SCREEN_H - margin - bg_surf.get_height() + 4))
# ================= 9. 主游戏循环 =================
def main(night_level=1):
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H), pygame.DOUBLEBUF | pygame.HWSURFACE)
pygame.display.set_caption(f"Dark Corridor: Night {night_level}")
clock = pygame.time.Clock()
init_render_surfaces()
# --- 关卡配置 ---
map_size_multiplier = 1 + (night_level - 1) * 0.2
MAP_COLS = int(40 * map_size_multiplier)
MAP_ROWS = int(30 * map_size_multiplier)
num_enemies = 1 + (night_level // 2)
has_boss = night_level >= 3
# 生成地图
maze, WALLS, WALL_SEGMENTS, WALL_VERTICES, SPATIAL_GRID, SEG_SPATIAL_GRID = generate_connected_maze(MAP_COLS, MAP_ROWS, num_rooms=6+night_level)
start_pos = (1, 1)
exit_pos = (MAP_COLS-2, MAP_ROWS-2)
if maze[exit_pos[1]][exit_pos[0]] == 1:
for r in range(MAP_ROWS-2, 0, -1):
for c in range(MAP_COLS-2, 0, -1):
if maze[r][c] == 0:
exit_pos = (c, r)
break
else:
continue
break
used = {start_pos, exit_pos}
# 均匀分布水晶
shard_positions = get_furthest_points(maze, 5, used)
for p in shard_positions: used.add(p)
# 均匀分布道具
item_types = ["battery", "battery", "radar", "eagle"]
if night_level > 2: item_types.append("battery")
item_positions = get_furthest_points(maze, len(item_types), used)
items = []
for i, pos in enumerate(item_positions):
items.append(Item(pos, item_types[i]))
used.add(pos)
# 敌人生成
enemies = []
enemy_types = ["visual", "audio"]
for i in range(num_enemies):
etype = enemy_types[i % 2]
pts = get_furthest_points(maze, 1, used)
if not pts:
p = (1, 1)
else:
p = pts[0]
attempts = 0
while math.hypot(p[0]-start_pos[0], p[1]-start_pos[1]) < 15 and attempts < 50:
pts = get_furthest_points(maze, 1, used)
if pts:
p = pts[0]
attempts += 1
enemies.append(Enemy(p, etype)); used.add(p)
if has_boss:
pts = get_furthest_points(maze, 1, used)
if not pts:
p = (1, 1)
else:
p = pts[0]
boss = Enemy(p, "boss", is_boss=True)
# 为 BOSS 设置巡逻点 (地图的几个角落)
boss.patrol_points = [
(MAP_COLS//4 * TILE, MAP_ROWS//4 * TILE),
(3*MAP_COLS//4 * TILE, MAP_ROWS//4 * TILE),
(3*MAP_COLS//4 * TILE, 3*MAP_ROWS//4 * TILE),
(MAP_COLS//4 * TILE, 3*MAP_ROWS//4 * TILE)
]
enemies.append(boss)
player = Player(start_pos)
if player.rect.collidelist(WALLS) != -1:
for r in range(1, MAP_ROWS-1):
for c in range(1, MAP_COLS-1):
if maze[r][c] == 0:
test_rect = pygame.Rect(c*TILE+8, r*TILE+8, 24, 24)
if test_rect.collidelist(WALLS) == -1:
player.rect = test_rect
break
else:
continue
break
shards = [pygame.Rect(c*TILE+12, r*TILE+12, 16, 16) for c,r in shard_positions]
exit_rect = pygame.Rect(exit_pos[0]*TILE+5, exit_pos[1]*TILE+5, 30, 30)
exit_unlocked = False
map_surf = pygame.Surface((MAP_COLS*TILE, MAP_ROWS*TILE))
for r in range(MAP_ROWS):
for c in range(MAP_COLS):
color = WALL_COL if maze[r][c]==1 else FLOOR_COL
pygame.draw.rect(map_surf, color, (c*TILE, r*TILE, TILE, TILE))
toast = ToastMessage()
show_night_intro(screen, night_level)
game_state = "PLAYING"
jumpscare_timer = 0; elapsed_time = 0.0; last_tick = pygame.time.get_ticks()
show_minimap = False
fps_display = 0
frame_count = 0
running = True
error_count = 0
while running:
dt = clock.tick(FPS_TARGET)
fps_display = clock.get_fps()
now = pygame.time.get_ticks()
frame_dt = (now - last_tick) / 1000.0
last_tick = now
frame_count += 1
if game_state == "PLAYING": elapsed_time += frame_dt
# --- 事件处理 ---
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_f and game_state=="PLAYING":
player.flashlight = not player.flashlight
if event.key == pygame.K_h and game_state=="PLAYING":
if player.map_cooldown > 0:
toast.show(t("map_cooldown_hint"), 60)
elif player.map_power > 0:
show_minimap = not show_minimap
else:
toast.show(t("map_cooldown_hint"), 60)
if event.key == pygame.K_t: LANG["current"] = "zh" if LANG["current"]=="en" else "en"
if event.key == pygame.K_r and game_state in ("GAMEOVER", "WIN"): return night_level
if event.key == pygame.K_n and game_state == "WIN":
if night_level < 5: return night_level + 1
else: return 1 # 通关后重头开始
if event.key == pygame.K_ESCAPE: running = False
# --- PLAYING 逻辑 ---
if game_state == "PLAYING":
keys = pygame.key.get_pressed()
player.running = keys[pygame.K_LSHIFT] or keys[pygame.K_RSHIFT]
current_speed = player.run_speed if player.running else player.speed
player.noise_level = 0
if player.running: player.noise_level += 3
if player.flashlight: player.noise_level += 1
dx, dy = 0, 0
if keys[pygame.K_w] or keys[pygame.K_UP]: dy = -current_speed
if keys[pygame.K_s] or keys[pygame.K_DOWN]: dy = current_speed
if keys[pygame.K_a] or keys[pygame.K_LEFT]: dx = -current_speed
if keys[pygame.K_d] or keys[pygame.K_RIGHT]: dx = current_speed
if dx!=0 or dy!=0: player.facing = (dx, dy)
old_x, old_y = player.rect.x, player.rect.y
move_with_collision(player.rect, dx, dy, WALLS, MAP_COLS*TILE, MAP_ROWS*TILE)
if (player.rect.x==old_x and player.rect.y==old_y) and (dx or dy):
player.noise_level += 5
drain = 0.01
if player.flashlight: drain += 0.05
if player.running: drain += 0.02
if show_minimap: drain += 0.03
player.power = max(0, player.power - drain)
if player.power <= 0: player.flashlight = False
# 小地图逻辑
# 小地图电力系统
if show_minimap:
if player.map_power > 0:
player.map_power -= 1
else:
show_minimap = False
player.map_cooldown = player.MAP_COOLDOWN_MAX
toast.show(t("map_cooldown_hint"), 60)
if player.map_cooldown > 0:
player.map_cooldown -= 1
if player.map_cooldown == 0:
player.map_power = player.MAX_MAP_POWER
if player.eagle_time > 0: player.eagle_time -= 1
if player.radar_time > 0: player.radar_time -= 1
toast.update()
for s in shards[:]:
if player.rect.colliderect(s):
shards.remove(s)
player.shards += 1
player.noise_level += 5 # 拾取碎片发出声响,吸引红怪
story_hints = STORY_TEXTS[LANG["current"]]["shard_hints"]
if player.shards <= len(story_hints):
toast.show(story_hints[player.shards - 1], 240)
if player.shards >= player.max_shards: exit_unlocked = True
if exit_unlocked and player.rect.colliderect(exit_rect): game_state = "WIN"
for item in items[:]:
if item.active and player.rect.colliderect(item.rect):
item.active = False
player.noise_level += 3 # 拾取道具发出声响
if item.itype == "battery":
player.power = min(100, player.power + 40)
elif item.itype == "radar":
player.radar_time = 600
elif item.itype == "eagle":
player.eagle_time = 360
item_hints = STORY_TEXTS[LANG["current"]]["item_hints"]
if item.itype in item_hints:
toast.show(item_hints[item.itype], 180)
# ================= 敌人AI =================
# 收集所有处于CHASE状态的敌人的目标位置,用于信息共享
alert_positions = []
for e in enemies:
if e.state == "CHASE" and e.target_pos:
alert_positions.append(e.target_pos)
if frame_count % 2 == 0:
for enemy in enemies:
dist_to_player = math.hypot(player.rect.centerx-enemy.rect.centerx, player.rect.centery-enemy.rect.centery)
# 检查是否可以从其他敌人那里获得玩家位置信息
if enemy.state != "CHASE" and alert_positions:
for alert_pos in alert_positions:
dist_to_alert = math.hypot(enemy.rect.centerx - alert_pos[0], enemy.rect.centery - alert_pos[1])
if dist_to_alert < 250:
enemy.state = "CHASE"
enemy.lose_timer = 0
enemy.shared_target = alert_pos
enemy.shared_timer = 90
break
# 共享追踪倒计时
if enemy.shared_timer > 0:
enemy.shared_timer -= 1
if enemy.shared_timer == 0:
enemy.shared_target = None
if enemy.state == "CHASE":
enemy.state = "PATROL"
# BOSS 特殊逻辑:笨拙但执着,会绕墙
if enemy.is_boss:
heard_noise = player.noise_level > 1
can_see_light = player.flashlight and player.power > 0
boss_range = 500 if can_see_light else 350
if (can_see_light and dist_to_player < boss_range) or (heard_noise and dist_to_player < 300):
enemy.state = "CHASE"
enemy.lose_timer = 0
enemy.target_pos = (player.rect.centerx, player.rect.centery)
enemy.wall_following = False
enemy.wall_stuck_count = 0
elif enemy.state == "CHASE":
enemy.lose_timer += 1
if enemy.lose_timer > 180:
enemy.state = "PATROL"
enemy.wall_following = False
if enemy.state == "CHASE":
ex, ey = enemy.rect.centerx, enemy.rect.centery
tx, ty = player.rect.centerx, player.rect.centery
angle = math.atan2(ty - ey, tx - ex)
dx = math.cos(angle) * enemy.chase_speed
dy = math.sin(angle) * enemy.chase_speed
old_x, old_y = enemy.rect.x, enemy.rect.y
move_with_collision(enemy.rect, dx, dy, WALLS, MAP_COLS*TILE, MAP_ROWS*TILE)
if enemy.rect.x == old_x and enemy.rect.y == old_y:
if not enemy.wall_following:
enemy.wall_following = True
enemy.wall_dir = angle + math.pi / 2
enemy.wall_timer = 0
enemy.wall_stuck_count = 0
enemy.original_chase_angle = angle
enemy.wall_timer += 1
enemy.wall_stuck_count += 1
wdx = math.cos(enemy.wall_dir) * enemy.base_speed * 0.8
wdy = math.sin(enemy.wall_dir) * enemy.base_speed * 0.8
temp_rect = enemy.rect.copy()
temp_rect.x += wdx
temp_rect.y += wdy
if temp_rect.collidelist(WALLS) != -1:
enemy.wall_dir -= math.pi / 2
enemy.wall_timer = 0
wdx = math.cos(enemy.wall_dir) * enemy.base_speed * 0.8
wdy = math.sin(enemy.wall_dir) * enemy.base_speed * 0.8
move_with_collision(enemy.rect, wdx, wdy, WALLS, MAP_COLS*TILE, MAP_ROWS*TILE)
if enemy.rect.x == old_x and enemy.rect.y == old_y:
enemy.wall_dir -= math.pi / 2
enemy.wall_timer = 0
wdx = math.cos(enemy.wall_dir) * enemy.base_speed * 0.8
wdy = math.sin(enemy.wall_dir) * enemy.base_speed * 0.8
move_with_collision(enemy.rect, wdx, wdy, WALLS, MAP_COLS*TILE, MAP_ROWS*TILE)
new_dist = math.hypot(player.rect.centerx - enemy.rect.centerx, player.rect.centery - enemy.rect.centery)
if enemy.wall_stuck_count > 120:
enemy.wall_following = False
enemy.wall_stuck_count = 0
elif new_dist < dist_to_player * 0.95:
enemy.wall_following = False
enemy.wall_stuck_count = 0
elif enemy.wall_timer > 120:
angle_diff = abs(enemy.wall_dir - enemy.original_chase_angle)
while angle_diff > math.pi: angle_diff -= math.pi * 2
while angle_diff < -math.pi: angle_diff += math.pi * 2
if abs(angle_diff) < math.pi / 3:
enemy.wall_following = False
enemy.wall_stuck_count = 0
enemy.wall_timer = 0
else:
enemy.wall_following = False
enemy.wall_stuck_count = 0
enemy.eye_glow = 255
else:
if not enemy.patrol_points:
enemy.patrol_points = [(random.randint(1, MAP_COLS-2)*TILE, random.randint(1, MAP_ROWS-2)*TILE)]
target = enemy.patrol_points[enemy.current_patrol_idx]
dist_to_target = math.hypot(target[0] - enemy.rect.centerx, target[1] - enemy.rect.centery)
if dist_to_target < 20:
enemy.current_patrol_idx = (enemy.current_patrol_idx + 1) % len(enemy.patrol_points)
angle = math.atan2(target[1] - enemy.rect.centery, target[0] - enemy.rect.centerx)
old_x, old_y = enemy.rect.x, enemy.rect.y
move_with_collision(enemy.rect, math.cos(angle)*enemy.base_speed, math.sin(angle)*enemy.base_speed, WALLS, MAP_COLS*TILE, MAP_ROWS*TILE)
if enemy.rect.x == old_x and enemy.rect.y == old_y:
enemy.current_patrol_idx = (enemy.current_patrol_idx + 1) % len(enemy.patrol_points)
enemy.eye_glow = max(0, enemy.eye_glow-5)
# 普通敌人逻辑
elif enemy.etype == "visual": # 红怪:顺风耳
heard_noise = player.noise_level > 0
# 噪声越大,听力范围越远
hear_dist = enemy.hear_range * (1 + player.noise_level * 0.15) if heard_noise else 120
if heard_noise and dist_to_player < hear_dist:
enemy.target_pos = (player.rect.centerx, player.rect.centery)
enemy.state = "CHASE"; enemy.lose_timer = 0
elif enemy.state == "CHASE":
enemy.lose_timer += 1
if enemy.lose_timer > 120: enemy.state = "PATROL"; enemy.target_pos = None
if enemy.state == "CHASE" and enemy.target_pos:
tx, ty = enemy.target_pos
angle = math.atan2(ty - enemy.rect.centery, tx - enemy.rect.centerx)
move_with_collision(enemy.rect, math.cos(angle)*enemy.chase_speed, math.sin(angle)*enemy.chase_speed, WALLS, MAP_COLS*TILE, MAP_ROWS*TILE)
enemy.eye_glow = min(255, enemy.eye_glow+30)
if math.hypot(tx - enemy.rect.centerx, ty - enemy.rect.centery) < 10:
if not heard_noise: enemy.state = "PATROL"
else:
enemy.eye_glow = max(0, enemy.eye_glow-5)
enemy.patrol_timer += 1
if enemy.patrol_timer > 50 or enemy.rect.collidelist(WALLS)!=-1:
enemy.dir = random.choice([(1,0),(-1,0),(0,1),(0,-1)])
enemy.patrol_timer = 0
move_with_collision(enemy.rect, enemy.dir[0]*enemy.base_speed, enemy.dir[1]*enemy.base_speed, WALLS, MAP_COLS*TILE, MAP_ROWS*TILE)
elif enemy.etype == "audio": # 蓝怪:千里眼,透视追踪
# 始终能看到玩家,无视墙壁
enemy.state = "CHASE"
enemy.target_pos = (player.rect.centerx, player.rect.centery)
enemy.lose_timer = 0
tx, ty = enemy.target_pos
angle = math.atan2(ty - enemy.rect.centery, tx - enemy.rect.centerx)
# 速度降低为正常的70%
speed = enemy.base_speed * 0.7
move_with_collision(enemy.rect, math.cos(angle)*speed, math.sin(angle)*speed, WALLS, MAP_COLS*TILE, MAP_ROWS*TILE)
enemy.eye_glow = min(255, enemy.eye_glow+8)
if dist_to_player < 28:
game_state = "JUMPSCARE"; jumpscare_timer = 80
# 剧情触发:敌人靠近警告
if frame_count % 30 == 0 and game_state == "PLAYING":
min_enemy_dist = min([math.hypot(player.rect.centerx-e.rect.centerx, player.rect.centery-e.rect.centery) for e in enemies], default=9999)
boss_dist = min([math.hypot(player.rect.centerx-e.rect.centerx, player.rect.centery-e.rect.centery) for e in enemies if e.is_boss], default=9999)
if boss_dist < 200 and not getattr(player, '_boss_warned', False):
toast.show(t("boss_nearby"), 120)
player._boss_warned = True
elif boss_dist >= 300:
player._boss_warned = False
if min_enemy_dist < 150 and not getattr(player, '_enemy_warned', False):
toast.show(t("enemy_nearby"), 120)
player._enemy_warned = True
elif min_enemy_dist >= 250:
player._enemy_warned = False
if player.power < 20 and not getattr(player, '_power_warned', False):
toast.show(t("power_low"), 120)
player._power_warned = True
elif player.power > 30:
player._power_warned = False
# ================= 渲染 =================
cam_x = max(0, min(player.rect.centerx - SCREEN_W//2, MAP_COLS*TILE - SCREEN_W))
cam_y = max(0, min(player.rect.centery - SCREEN_H//2, MAP_ROWS*TILE - SCREEN_H))
screen.fill(BLACK)
screen.blit(map_surf, (-cam_x, -cam_y))
# 出口
ex, ey = exit_rect.x-cam_x, exit_rect.y-cam_y
e_col = EXIT_COL_OPEN if exit_unlocked else EXIT_COL_LOCKED
pygame.draw.rect(screen, e_col, (ex, ey, exit_rect.w, exit_rect.h), border_radius=4)
if exit_unlocked: pygame.draw.rect(screen, WHITE, (ex,ey,exit_rect.w,exit_rect.h), 2, border_radius=4)
# 碎片
for s in shards:
sx, sy = s.x-cam_x, s.y-cam_y
pts = [(sx+s.w//2,sy), (sx+s.w,sy+s.h//2), (sx+s.w//2,sy+s.h), (sx,sy+s.h//2)]
pygame.draw.polygon(screen, SHARD_COL, pts)
# 道具
for item in items:
if item.active:
ix, iy = item.rect.x-cam_x, item.rect.y-cam_y
col = ITEM_BATTERY if item.itype=="battery" else (ITEM_RADAR if item.itype=="radar" else ITEM_EAGLE)
screen.blit(get_glow_surf(col), (ix-5, iy-5))
pygame.draw.circle(screen, col, (int(ix+10), int(iy+10)), 7)
# 玩家
px, py = player.rect.x-cam_x, player.rect.y-cam_y
pygame.draw.rect(screen, PLAYER_COL, player.rect.move(-cam_x, -cam_y), border_radius=8)
fx, fy = player.facing
if fx!=0 or fy!=0:
tip_x = px+player.rect.w//2 + fx *16; tip_y = py+player.rect.h//2 + fy*16
pygame.draw.circle(screen, WHITE, (int(tip_x),int(tip_y)), 2)
# 敌人
for enemy in enemies:
ex, ey = enemy.rect.x-cam_x, enemy.rect.y-cam_y
if enemy.is_boss:
e_col = BOSS_COL
size_mod = 1.5 # BOSS 更大
else:
e_col = ENEMY_VISUAL if enemy.etype=="visual" else ENEMY_AUDIO
size_mod = 1.0
rect_size = int(32 * size_mod)
offset = int(4 * size_mod)
pygame.draw.rect(screen, e_col, pygame.Rect(ex-offset, ey-offset, rect_size, rect_size), border_radius=6)
glow = enemy.eye_glow
eye_col = (min(255,150+glow), min(255,150+glow), min(255,150+glow))
pupil_col = RED_TINT if glow >100 else (60,0,0)
eye_offset = int(10 * size_mod)
pupil_offset = int(2 * size_mod)
pygame.draw.circle(screen, eye_col, (ex+eye_offset,ey+eye_offset), int(5*size_mod))
pygame.draw.circle(screen, eye_col, (ex+rect_size-eye_offset,ey+eye_offset), int(5*size_mod))
pygame.draw.circle(screen, pupil_col, (ex+eye_offset,ey+eye_offset), pupil_offset)
pygame.draw.circle(screen, pupil_col, (ex+rect_size-eye_offset,ey+eye_offset), pupil_offset)
# ⭐ 应用射线投射视野遮挡
vision_fog = render_vision(screen, player, enemies, cam_x, cam_y, WALL_SEGMENTS, WALL_VERTICES, SPATIAL_GRID, SEG_SPATIAL_GRID)
screen.blit(vision_fog, (0,0))
# 危险泛红
if game_state=="PLAYING" and frame_count % 2 == 0:
min_dist_sq = 999999
px, py = player.rect.centerx, player.rect.centery
for e in enemies:
dx = px - e.rect.centerx
dy = py - e.rect.centery
dist_sq = dx * dx + dy * dy
if dist_sq < min_dist_sq:
min_dist_sq = dist_sq
if min_dist_sq < 40000:
break
if min_dist_sq < 40000:
min_dist = math.sqrt(min_dist_sq)
tint = int(max(0, (200-min_dist)*0.8))
_border_tint_surf.fill((0,0,0,0))
pygame.draw.rect(_border_tint_surf, (255,0,0,tint), (0,0,SCREEN_W,SCREEN_H), 30)
screen.blit(_border_tint_surf, (0,0))
# ================= UI =================
ui_y = 12
# 电量条
pygame.draw.rect(screen, (30,30,35), (12,ui_y,160,20), border_radius=4)
bar_col = (0,200,60) if player.power >30 else (220,50,0)
pygame.draw.rect(screen, bar_col, (14,ui_y+2, max(0,int(player.power*1.56)), 16), border_radius=3)
power_text = FONT_SM.render(f"{int(player.power)}%", True, WHITE)
screen.blit(power_text, (14, ui_y+1))
# 碎片计数
shard_text = FONT_SM.render(f"{player.shards}/{player.max_shards}", True, SHARD_COL)
screen.blit(shard_text, (185, ui_y+2))
# 状态指示
if player.eagle_time >0:
screen.blit(FONT_SM.render("NIGHT VISION", True, ITEM_EAGLE), (250, ui_y+2))
elif player.radar_time >0:
screen.blit(FONT_SM.render("RADAR", True, ITEM_RADAR), (250, ui_y+2))
elif player.running:
screen.blit(FONT_SM.render("RUNNING", True, (255,220,0)), (250, ui_y+2))
# 时间显示
time_text = FONT_SM.render(f"{t('time')}: {elapsed_time:.1f}s", True, (180,180,180))
screen.blit(time_text, (SCREEN_W - 130, ui_y+2))
# 底部提示
hint_text = t("hint")
hint_surf = FONT_SM.render(hint_text, True, (100,100,100))
screen.blit(hint_surf, (12, SCREEN_H-40))
if exit_unlocked:
exit_surf = FONT_MD.render(t("exit_open"), True, EXIT_COL_OPEN)
screen.blit(exit_surf, (SCREEN_W//2 - exit_surf.get_width()//2, SCREEN_H-55))
if game_state == "PLAYING":
toast.draw(screen)
# 小地图
if show_minimap and game_state=="PLAYING":
mm_w, mm_h = 200, 150
mm_x, mm_y = SCREEN_W - mm_w - 15, SCREEN_H - mm_h - 40
if not hasattr(player, '_minimap_bg'):
player._minimap_bg = pygame.Surface((mm_w, mm_h), pygame.SRCALPHA)
pygame.transform.smoothscale(map_surf, (mm_w, mm_h), player._minimap_bg)
pygame.draw.rect(player._minimap_bg, (60,60,60), (0,0,mm_w,mm_h), 2)
mm_bg = player._minimap_bg.copy()
scale_x = mm_w / (MAP_COLS*TILE)
scale_y = mm_h / (MAP_ROWS*TILE)
for s in shards: pygame.draw.circle(mm_bg, SHARD_COL, (int(s.x*scale_x), int(s.y*scale_y)), 2)
for item in items:
if item.active:
ic = ITEM_BATTERY if item.itype=="battery" else (ITEM_RADAR if item.itype=="radar" else ITEM_EAGLE)
pygame.draw.circle(mm_bg, ic, (int(item.rect.x*scale_x), int(item.rect.y*scale_y)), 2)
if player.radar_time > 0:
for enemy in enemies:
ec = ENEMY_VISUAL if enemy.etype=="visual" else ENEMY_AUDIO
pygame.draw.circle(mm_bg, ec, (int(enemy.rect.centerx*scale_x), int(enemy.rect.centery*scale_y)), 3)
exit_mx = exit_rect.x*scale_x + exit_rect.w*scale_x/2
exit_my = exit_rect.y*scale_y + exit_rect.h*scale_y/2
if exit_unlocked:
pulse_size = 6 + int(math.sin(pygame.time.get_ticks() / 300) * 2)
pygame.draw.circle(mm_bg, EXIT_COL_OPEN, (int(exit_mx), int(exit_my)), pulse_size)
pygame.draw.circle(mm_bg, WHITE, (int(exit_mx), int(exit_my)), 4)
pygame.draw.circle(mm_bg, EXIT_COL_OPEN, (int(exit_mx), int(exit_my)), 2)
else:
pygame.draw.rect(mm_bg, EXIT_COL_LOCKED,
(exit_rect.x*scale_x, exit_rect.y*scale_y, exit_rect.w*scale_x, exit_rect.h*scale_y))
px_mm = player.rect.centerx * scale_x
py_mm = player.rect.centery * scale_y
pygame.draw.circle(mm_bg, PLAYER_COL, (int(px_mm), int(py_mm)), 4)
pygame.draw.circle(mm_bg, WHITE, (int(px_mm), int(py_mm)), 2)
screen.blit(mm_bg, (mm_x, mm_y))
# 小地图状态提示
if player.map_cooldown > 0:
cd_sec = max(1, (player.map_cooldown + 59) // 60)
cd_text = FONT_SM.render(f"{t('map_cd')}: {cd_sec}s", True, RED_TINT)
screen.blit(cd_text, (mm_x, mm_y - 18))
else:
power_sec = max(0, player.map_power // 45)
ready_text = FONT_SM.render(f"[H] Ready {power_sec}s", True, WHITE)
screen.blit(ready_text, (mm_x, mm_y - 18))
# 小地图电力条
bar_w = mm_w
bar_h = 6
bar_x = mm_x
bar_y = mm_y + mm_h + 4
pygame.draw.rect(screen, (40, 40, 40), (bar_x, bar_y, bar_w, bar_h), border_radius=2)
power_ratio = player.map_power / player.MAX_MAP_POWER
p_col = (0, 200, 60) if power_ratio > 0.3 else (220, 50, 0)
pygame.draw.rect(screen, p_col, (bar_x, bar_y, int(bar_w * power_ratio), bar_h), border_radius=2)
# ======= 特殊状态 =================
if game_state == "JUMPSCARE":
jumpscare_timer -= 1
sx = random.randint(-15,15); sy = random.randint(-15,15)
screen.fill(RED_TINT)
cx, cy = SCREEN_W//2+sx, SCREEN_H//2+sy
pygame.draw.circle(screen, BLACK, (cx,cy), 180)
pygame.draw.circle(screen, WHITE, (cx-50,cy-40), 35)
pygame.draw.circle(screen, WHITE, (cx+50,cy-40), 35)
pygame.draw.circle(screen, RED_TINT, (cx-50,cy-40), 15)
pygame.draw.circle(screen, RED_TINT, (cx+50,cy-40), 15)
for i in range(-60, 60, 15):
pygame.draw.rect(screen, WHITE, (cx+i-5, cy+50, 10, 30))
if jumpscare_timer <= 0: game_state = "GAMEOVER"
elif game_state == "GAMEOVER":
screen.fill(BLACK)
draw_retro_frame(screen, t("caught"), RED_TINT, -80)
sub = FONT_MD.render(f"{t('time')}: {elapsed_time:.1f}s | {t('shards')}: {player.shards}", True, WHITE)
screen.blit(sub, sub.get_rect(center=(SCREEN_W//2, SCREEN_H//2+20)))
bad_ending = STORY_TEXTS[LANG["current"]]["endings"]["bad"]
ending_lines = []
max_width = SCREEN_W - 200
current_line = ""
for char in bad_ending:
test_line = current_line + char
if FONT_SM.size(test_line)[0] > max_width and char in ",。!?,.!? ":
ending_lines.append(current_line)
current_line = "" if char in ",。!?,.!?" else char
else:
current_line += char
if current_line:
ending_lines.append(current_line)
y_off = 60
for line in ending_lines:
line_surf = FONT_SM.render(line, True, (180, 180, 180))
screen.blit(line_surf, line_surf.get_rect(center=(SCREEN_W//2, SCREEN_H//2+y_off)))
y_off += 25
screen.blit(FONT_SM.render(t("play_again"), True, WHITE), (SCREEN_W//2-90, SCREEN_H//2+130))
draw_crt_overlay(screen)
elif game_state == "WIN":
screen.fill((10,22,12))
draw_retro_frame(screen, t("escaped"), (0,255,100), -100)
score = 1000 - int(elapsed_time*10) + player.shards*100 + int(player.power*5)
rank = "S" if score >1500 else "A" if score >1200 else "B" if score >900 else "C"
rc = (255,215,0) if rank=="S" else WHITE
info = FONT_MD.render(f"{t('time')}: {elapsed_time:.1f}s | Power: {int(player.power)}% | Rank: {rank}", True, rc)
screen.blit(info, info.get_rect(center=(SCREEN_W//2, SCREEN_H//2-10)))
story = STORY_TEXTS[LANG["current"]]
if night_level >= 5:
ending_text = story["endings"]["good"]
else:
idx = min(night_level - 1, len(story["night_desc"]) - 1)
ending_text = story["night_desc"][idx]
ending_lines = []
max_width = SCREEN_W - 200
current_line = ""
for char in ending_text:
test_line = current_line + char
if FONT_SM.size(test_line)[0] > max_width and char in ",。!?,.!? ":
ending_lines.append(current_line)
current_line = "" if char in ",。!?,.!?" else char
else:
current_line += char
if current_line:
ending_lines.append(current_line)
y_off = 40
for line in ending_lines:
line_surf = FONT_SM.render(line, True, (200, 200, 200))
screen.blit(line_surf, line_surf.get_rect(center=(SCREEN_W//2, SCREEN_H//2+y_off)))
y_off += 25
next_hint = FONT_SM.render(t("play_again"), True, WHITE)
screen.blit(next_hint, next_hint.get_rect(center=(SCREEN_W//2, SCREEN_H//2+y_off+20)))
draw_crt_overlay(screen)
pygame.display.flip()
pygame.quit()
sys.exit()
def title_screen():
"""复古风格标题界面"""
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H), pygame.DOUBLEBUF | pygame.HWSURFACE)
pygame.display.set_caption("Dark Corridor")
clock = pygame.time.Clock()
running = True
blink_timer = 0
while running:
dt = clock.tick(60)
blink_timer += dt
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN: return 1
if event.key == pygame.K_t: LANG["current"] = "zh" if LANG["current"]=="en" else "en"
if event.key == pygame.K_ESCAPE: running = False
screen.fill(BLACK)
# 标题
title_surf = FONT_XL.render(t("game_title"), True, RED_TINT)
screen.blit(title_surf, title_surf.get_rect(center=(SCREEN_W//2, SCREEN_H//3)))
# 闪烁的提示
if int(blink_timer / 500) % 2 == 0:
start_surf = FONT_MD.render(t("start_game"), True, WHITE)
screen.blit(start_surf, start_surf.get_rect(center=(SCREEN_W//2, SCREEN_H//2)))
# 底部版权/提示 - 添加深色背景条防止CRT扫描线吞噬文字
hint_text = "[T] Switch Language" if LANG["current"] == "en" else "[T] 切换语言"
hint_surf = FONT_SM.render(hint_text, True, (180,180,180))
hint_rect = hint_surf.get_rect(center=(SCREEN_W//2, SCREEN_H - 50))
bg_rect = hint_rect.inflate(20, 8)
bg_surf = pygame.Surface((bg_rect.width, bg_rect.height), pygame.SRCALPHA)
bg_surf.fill((0, 0, 0, 180))
pygame.draw.rect(bg_surf, (60, 60, 70, 180), bg_surf.get_rect(), 1, border_radius=3)
screen.blit(bg_surf, bg_rect)
screen.blit(hint_surf, hint_rect)
draw_crt_overlay(screen)
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
current_night = title_screen()
if current_night:
while True:
result = main(current_night)
if isinstance(result, int):
current_night = result
else:
break后记
这次也算是我无聊做的程序,也是无聊写的文章(用时<20min),如果看到就当看个乐,作者本蒟蒻没当真。 ---