src / game.py
# -*- coding: utf-8 -*-
"""Game - 主类 + 主循环 + 命令解析 + 前6天剧情流程
整合系统:
- 随机数加权探索系统(每个地点有物资池,按权重随机获得)
- 前6天剧情(第1天核爆→山洞→第2-6天探索→第7天出发)
- 关系系统(信任度变化:不给枪→给枪)
- 生存系统(体温/饥饿/精神tick)
- 天气系统(世界状态+天气影响)
- 物资管理(库存系统)
"""
import random
import sys
from .vehicle import Vehicle
from .player import Player
from .lingmuxue import Lingmuxue
from .world import World
from .radio import Radio
from .inventory import Inventory
from .dialogue import DialogueBridge
class WeightedExplorationSystem:
"""随机数加权探索系统(基础层)。
每个探索点有物资池,每次搜索根据权重随机决定获得什么。
返回的物资映射到 inventory 系统的 item_id。
"""
# 简单名称 → inventory item_id 映射
ITEM_MAP = {
'食物': ['canned_meat', 'compressed_biscuit', 'flour_bag'],
'水': ['water_clean_1L'],
'柴油': ['diesel_20L'],
'零件': ['oil_filter', 'belt', 'piston_pin', 'wrench'],
'弹药': None, # 特殊处理:记录为 ammo_count
'医疗': ['bandage', 'iodine', 'painkiller'],
'书籍': ['barefoot_doctor_manual', 'minbing_manual', 'car_manual'],
'保暖': ['blanket', 'cotton_coat_pla'],
}
def __init__(self, location_name: str, distance: float, danger_level: int):
self.name = location_name
self.distance = distance # 距离基地km
self.danger_level = danger_level # 0-5
self.item_pool = {
'食物': {'weight': 30, 'amount_range': (1, 3)},
'水': {'weight': 20, 'amount_range': (1, 2)},
'柴油': {'weight': 15, 'amount_range': (1, 2)},
'零件': {'weight': 10, 'amount_range': (1, 2)},
'弹药': {'weight': 10, 'amount_range': (5, 20)},
'医疗': {'weight': 8, 'amount_range': (1, 2)},
'书籍': {'weight': 5, 'amount_range': (1, 1)},
'保暖': {'weight': 2, 'amount_range': (1, 1)},
}
def search(self):
"""搜索一次,返回获得的物品列表 [(item_id_or_special, amount), ...]"""
results = []
items = list(self.item_pool.keys())
weights = [self.item_pool[item]['weight'] for item in items]
# 随机选择3-5种
num_items = random.randint(3, 5)
selected = random.choices(items, weights=weights, k=num_items)
for item_name in selected:
pool_info = self.item_pool[item_name]
amount_range = pool_info['amount_range']
amount = random.randint(*amount_range)
if item_name == '弹药':
# 特殊:弹药单独追踪
results.append(('ammo_7.62x39', amount))
else:
# 从映射中随机选一个具体物品
candidates = self.ITEM_MAP.get(item_name, [])
if candidates:
chosen_id = random.choice(candidates)
results.append((chosen_id, amount))
return results
# ============================================================================
# 改进探索系统:多步骤 + 区域选择 + LLM关键词驱动
# ============================================================================
# 探索区域定义:每个地点有3-5个可搜索的子区域
EXPLORE_AREAS = {
'瓦房店工厂': [
{'name': '主车间', 'danger': 2, 'items_weight': {'食物': 10, '零件': 40, '柴油': 15}},
{'name': '仓库', 'danger': 1, 'items_weight': {'食物': 30, '水': 20, '保暖': 10}},
{'name': '办公室', 'danger': 1, 'items_weight': {'书籍': 30, '医疗': 10}},
{'name': '地下管道', 'danger': 3, 'items_weight': {'零件': 30, '弹药': 20}},
{'name': '围墙外', 'danger': 2, 'items_weight': {'食物': 20, '柴油': 10}},
],
'庄河加油站': [
{'name': '加油区', 'danger': 1, 'items_weight': {'柴油': 50, '零件': 10}},
{'name': '便利店', 'danger': 1, 'items_weight': {'食物': 30, '水': 20}},
{'name': '车库', 'danger': 2, 'items_weight': {'零件': 40, '工具': 20}},
{'name': '后院', 'danger': 1, 'items_weight': {'食物': 10, '保暖': 10}},
],
'东港港口': [
{'name': '码头', 'danger': 3, 'items_weight': {'柴油': 30, '零件': 20}},
{'name': '仓库', 'danger': 3, 'items_weight': {'食物': 20, '柴油': 20, '零件': 20}},
{'name': '船舱', 'danger': 4, 'items_weight': {'柴油': 30, '弹药': 20, '零件': 20}},
{'name': '办公楼', 'danger': 2, 'items_weight': {'书籍': 20, '医疗': 10}},
],
'金州居民区': [
{'name': '筒子楼', 'danger': 2, 'items_weight': {'食物': 20, '水': 20, '保暖': 20}},
{'name': '平房', 'danger': 1, 'items_weight': {'食物': 30, '水': 20}},
{'name': '商店', 'danger': 2, 'items_weight': {'食物': 30, '水': 20, '医疗': 10}},
{'name': '学校', 'danger': 1, 'items_weight': {'书籍': 40, '医疗': 10}},
],
'大连理工大学': [
{'name': '教学楼', 'danger': 2, 'items_weight': {'书籍': 40, '医疗': 10}},
{'name': '图书馆', 'danger': 2, 'items_weight': {'书籍': 50}},
{'name': '实验室', 'danger': 3, 'items_weight': {'医疗': 30, '零件': 20}},
{'name': '宿舍', 'danger': 1, 'items_weight': {'食物': 20, '保暖': 30}},
],
'大连市区': [
{'name': '商业街', 'danger': 4, 'items_weight': {'食物': 20, '医疗': 20, '保暖': 20}},
{'name': '政府区', 'danger': 5, 'items_weight': {'书籍': 20, '弹药': 20}},
{'name': '工厂区', 'danger': 4, 'items_weight': {'零件': 40, '柴油': 30}},
{'name': '港口', 'danger': 4, 'items_weight': {'柴油': 40, '零件': 20}},
],
}
# 凌暮雪情绪状态(自然后果)
LINGMUXUE_MOODS = {
'secure': '安心',
'aware': '察觉',
'unsettled': '不安',
'withdrawn': '疏远',
'hurt': '受伤',
'distant': '心冷',
'leaving': '离开',
}
# 凌暮雪的台词反映情绪
LINGMUXUE_MOOD_DIALOGUES = {
'secure': ['……你今天累不累?靠过来。', '……我想跟你说说话。'],
'aware': ['……你跟她聊了很久。', '……嗯。'],
'unsettled': ['……没什么。', '……你别管我。'],
'withdrawn': ['……哦。', '……随便。'],
'hurt': ['……你是不是,觉得她比我好?', '……我哪里不好?'],
'distant': ['……随便你。', '……我不想说话。'],
'leaving': ['……曾经坐在我身旁。', '……我走了你就不用愁了。'],
}
class ImprovedExploration:
"""改进探索系统:多步骤 + 区域选择 + LLM关键词驱动。
架构:数值硬编码 + 事件LLM关键词驱动
- 数值(物资数量、关系度变化、风险值)由代码硬编码计算
- LLM通过dialogue bridge生成场景描述、叙事、评论等文本
"""
def __init__(self, game):
self.game = game
self.dialogue = game.bridge # DialogueBridge桥接
def explore_location(self, location_name: str) -> dict:
"""执行完整的探索流程(多步骤)。
流程:出发 → 路上事件 → 到达地点 → 选择探索区域 → 深入探索 → 遭遇事件 → 搜刮 → 返回 → 路上事件
Returns:
探索结果字典,包含获得的物品、事件、叙事等。
"""
result = {
'success': False,
'location': location_name,
'area_chosen': None,
'items_found': [],
'trust_change': 0.0,
'radiation': 0.0,
'fuel_cost': 0.0,
'duration_hours': 0,
'encounter': None,
'narrative': '',
'ling_comment': '',
}
# 1. 硬编码:获取地点的探索区域
areas = EXPLORE_AREAS.get(location_name, [])
if not areas:
# 降级:使用旧系统
old_system = self.game.exploration_systems.get(location_name)
if old_system:
return self._fallback_explore(location_name, old_system)
result['narrative'] = f'{location_name}没有可探索的区域。'
return result
# 2. 硬编码:选择探索区域(简化:随机选一个)
chosen_area = random.choice(areas)
result['area_chosen'] = chosen_area['name']
# 3. 硬编码:计算物资(加权随机)
items = self._weighted_search(chosen_area)
result['items_found'] = items
# 4. 硬编码:计算数值
duration = 2 # 探索消耗2时间格
trust_change = self._calculate_trust(items, duration, chosen_area['danger'])
radiation = self._calculate_radiation(duration, chosen_area['danger'])
fuel_cost = self.game.exploration_systems[location_name].distance * 0.5 * 2 # 往返
result['trust_change'] = trust_change
result['radiation'] = radiation
result['fuel_cost'] = fuel_cost
result['duration_hours'] = duration
# 5. LLM:生成场景描述
weather = getattr(self.game.world, 'weather', '未知')
time_phase = getattr(self.game.world, 'time_phase', '白天')
trust = self.game.ling.trust
scene = self._generate_scene(location_name, weather, time_phase, trust)
# 6. LLM:生成探索叙事
narrative = self._generate_exploration_narrative(items, duration, trust)
result['narrative'] = f"{scene}\n{narrative}"
# 7. LLM:凌暮雪评论(概率触发)
comment_prob = self._lingmuxue_comment_probability(trust)
if random.random() < comment_prob:
comment = self._generate_lingmuxue_comment(items, trust, location_name)
result['ling_comment'] = comment
# 8. 硬编码:触发遭遇事件
encounter = None
if random.random() < self._encounter_probability(location_name, chosen_area['danger']):
encounter_type = self._select_encounter(location_name)
encounter_desc = self._generate_encounter(encounter_type, trust)
encounter = {'type': encounter_type, 'description': encounter_desc}
result['encounter'] = encounter
# 9. 硬编码:应用数值
for item_id, amount in items:
if item_id.startswith('ammo_'):
self.game.ammo_count += amount
else:
self.game.inventory.add(item_id, amount)
self.game.ling.trust += trust_change
self.game.player.radiation += radiation
result['success'] = True
return result
def _fallback_explore(self, location_name: str, old_system) -> dict:
"""降级处理:当新系统不可用时,使用旧系统。"""
results = old_system.search()
items = [(item_id, amount) for item_id, amount in results]
# 硬编码数值
trust_change = 0
radiation = old_system.danger_level * 2
fuel_cost = old_system.distance * 0.5 * 2
narrative = f"你在{location_name}搜索了一番。"
return {
'success': True,
'location': location_name,
'area_chosen': '整个区域',
'items_found': items,
'trust_change': trust_change,
'radiation': radiation,
'fuel_cost': fuel_cost,
'duration_hours': 2,
'encounter': None,
'narrative': narrative,
'ling_comment': '',
}
def _weighted_search(self, area: dict) -> list:
"""根据区域权重进行加权随机搜索(硬编码数值)。"""
items_weight = area.get('items_weight', {})
if not items_weight:
return []
# 构建物品池
item_candidates = []
for category, weight in items_weight.items():
candidates = WeightedExplorationSystem.ITEM_MAP.get(category, [])
if candidates:
for candidate in candidates:
item_candidates.append((candidate, weight))
if not item_candidates:
return []
# 随机选择2-4种物品
num_items = random.randint(2, 4)
selected_weights = [w for _, w in item_candidates]
selected = random.choices(
[item for item, _ in item_candidates],
weights=selected_weights,
k=min(num_items, len(item_candidates))
)
# 去重并确定数量
results = []
seen = set()
for item_id in selected:
if item_id not in seen:
seen.add(item_id)
amount = random.randint(1, 2)
results.append((item_id, amount))
return results
def _calculate_trust(self, items: list, duration: int, danger: int) -> float:
"""计算信任度变化(硬编码公式)。"""
# 基础:找到好物资增加信任
trust_change = 0.0
for item_id, _ in items:
if item_id in ('food', 'water', 'medical'):
trust_change += 1.0
elif item_id in ('ammo', 'weapon'):
trust_change += 0.5
# 危险度高会略微降低信任(担心安全)
trust_change -= danger * 0.2
return max(-2.0, min(5.0, trust_change))
def _calculate_radiation(self, duration: int, danger: int) -> float:
"""计算辐射值(硬编码公式)。"""
return duration * danger * 1.5
def _generate_scene(self, location: str, weather: str, time_phase: str, trust: float) -> str:
"""LLM生成场景描述(带降级)。"""
try:
context = {
'day': self.game.day,
'trust': trust,
'location': location,
'weather': weather,
'time_phase': time_phase,
}
prompt = f"[{location}] [{weather}] [{time_phase}] 我们到了这里,周围是什么样?"
reply = self.dialogue.talk(prompt, context=context)
return reply
except Exception:
return self._fallback_scene(location, weather, time_phase)
def _fallback_scene(self, location: str, weather: str, time_phase: str) -> str:
"""降级场景描述。"""
scenes = {
'瓦房店工厂': '废弃的工厂矗立在寒风中,烟囱已经倒塌。',
'庄河加油站': '加油站的棚顶塌了一半,油泵锈迹斑斑。',
'东港港口': '港口的起重机歪斜着,海风带着咸腥味。',
'金州居民区': '居民区的窗户大多破碎,街道上空无一人。',
'大连理工大学': '校园里的树木覆盖着白雪,教学楼静悄悄的。',
'大连市区': '市区的街道一片狼藉,商店的橱窗被砸碎。',
}
base = scenes.get(location, f'{location}的废墟出现在眼前。')
return f"{base} 天气:{weather},时间:{time_phase}。"
def _generate_exploration_narrative(self, items: list, duration: int, trust: float) -> str:
"""LLM生成探索叙事(带降级)。"""
try:
context = {
'day': self.game.day,
'trust': trust,
'recent_event': '探索',
}
item_names = []
for item_id, amount in items:
from .inventory import ITEM_CATALOG
item_def = ITEM_CATALOG.get(item_id)
name = item_def.name if item_def else item_id
item_names.append(f"{name}x{amount}")
prompt = f"我们找到了这些东西:{', '.join(item_names)}。描述一下探索过程。"
reply = self.dialogue.talk(prompt, context=context)
return reply
except Exception:
return self._fallback_narrative(items)
def _fallback_narrative(self, items: list) -> str:
"""降级探索叙事。"""
parts = []
for item_id, amount in items:
from .inventory import ITEM_CATALOG
item_def = ITEM_CATALOG.get(item_id)
name = item_def.name if item_def else item_id
parts.append(f"{name}x{amount}")
if parts:
return f"你仔细搜索,找到了:{', '.join(parts)}。"
return "你翻找了很久,但收获不大。"
def _lingmuxue_comment_probability(self, trust: float) -> float:
"""计算凌暮雪评论的概率(信任越高越爱说话)。"""
if trust < 30:
return 0.1
elif trust < 50:
return 0.3
elif trust < 70:
return 0.5
else:
return 0.7
def _generate_lingmuxue_comment(self, items: list, trust: float, location: str) -> str:
"""LLM生成凌暮雪评论(带降级)。"""
try:
context = {
'day': self.game.day,
'trust': trust,
'location': location,
}
item_summary = f"{len(items)}样东西"
prompt = f"我们找到了{item_summary}。凌暮雪会说些什么?"
reply = self.dialogue.talk(prompt, context=context)
return reply
except Exception:
return self._fallback_ling_comment(items, trust)
def _fallback_ling_comment(self, items: list, trust: float) -> str:
"""降级凌暮雪评论。"""
if trust < 30:
return "……嗯。"
elif trust < 50:
return "……小心点。"
elif trust < 70:
return "……这些应该够我们用一阵子了。"
else:
return "……你总是能找到办法。真好。"
def _encounter_probability(self, location: str, danger: int) -> float:
"""计算遭遇事件的概率。"""
base_prob = 0.1 + danger * 0.1
return min(0.5, base_prob)
def _select_encounter(self, location: str) -> str:
"""选择遭遇事件类型(硬编码)。"""
encounters = ['流民', '土匪', '解放军检查站', '苏军巡逻队', '商人', '陷阱']
return random.choice(encounters)
def _generate_encounter(self, encounter_type: str, trust: float) -> str:
"""LLM生成遭遇事件描述(带降级)。"""
try:
context = {
'day': self.game.day,
'trust': trust,
'recent_event': f'遭遇{encounter_type}',
}
prompt = f"我们遇到了{encounter_type}。描述一下情况。"
reply = self.dialogue.talk(prompt, context=context)
return reply
except Exception:
return self._fallback_encounter(encounter_type)
def _fallback_encounter(self, encounter_type: str) -> str:
"""降级遭遇事件描述。"""
descriptions = {
'流民': '几个衣衫褴褛的流民出现在远处,看起来没有恶意。',
'土匪': '一群持枪的土匪从废墟后冲了出来!',
'解放军检查站': '前方出现了中国人民解放军的检查站。',
'苏军巡逻队': '一辆苏军装甲车在街道上巡逻。',
'商人': '一个背着大包小包的商人向你走来。',
'陷阱': '你差点踩中一个隐蔽的陷阱。',
}
return descriptions.get(encounter_type, f'你遇到了{encounter_type}。')
class Game:
"""1979 主游戏类。"""
# 每次前进的公里数
ADVANCE_KM = 35.0
# 探索消耗的时间格(1 格 = 1/5 天)
EXPLORE_TIME_STEPS = 2
# 前进消耗的时间格
ADVANCE_TIME_STEPS = 1
VALID_COMMANDS = ("前进", "探索", "状态", "对话", "无线电", "帮助", "退出")
def __init__(self) -> None:
self.player = Player()
self.ling = Lingmuxue()
self.vehicle = Vehicle()
self.world = World()
self.radio = Radio()
self.inventory = Inventory()
self.turn = 0
self._intro_done = False
# character_chat 对话桥接层(懒加载,首次 talk 时初始化)
self.bridge = DialogueBridge()
# 前6天剧情相关
self.day = 1
self.phase = 'day1' # day1, exploration, day6_give_gun, day7_depart
self.ammo_count = 0 # 简化弹药计数
self.player_has_gun = False # 玩家是否有枪(第6天前没有)
# 探索系统配置(6个地点)
self.exploration_systems = {
'瓦房店工厂': WeightedExplorationSystem('瓦房店工厂', 10, 1),
'庄河加油站': WeightedExplorationSystem('庄河加油站', 8, 1),
'东港港口': WeightedExplorationSystem('东港港口', 15, 3),
'金州居民区': WeightedExplorationSystem('金州居民区', 12, 2),
'大连理工大学': WeightedExplorationSystem('大连理工大学', 20, 3),
'大连市区': WeightedExplorationSystem('大连市区', 25, 5),
}
self.explored_locations = set() # 已探索的地点
# ---------- 启动 ----------
def run(self) -> None:
self.show_intro()
self.ask_name()
# 第1天:核爆→山洞
self.run_day1()
# 第2-6天:探索期
for day_num in range(2, 7):
self.day = day_num
self.run_exploration_day()
# 关键剧情点
if day_num == 3:
self.blizzard_event()
if day_num == 5:
self.father_story_event()
if day_num == 6:
self.give_gun_event()
# 第7天:出发
self.day = 7
self.depart_event()
# 之后进入正式游戏主循环
print("\n" + "=" * 56)
print("第7天,你们出发了。正式游戏开始……")
print("=" * 56)
self.main_loop()
def show_intro(self) -> None:
if self._intro_done:
return
self._intro_done = True
print("=" * 56)
print(" 1 9 7 9")
print("=" * 56)
print()
print("1979年12月。苏军入侵阿富汗。")
print("中苏边境紧张骤升,苏方先发制人,对东北军政目标战术核打击。")
print("中国反击。全面核交换。")
print()
print("你是沈阳军区通讯团学员兵,党员。")
print("核爆时你正在前线实习,部队被打散。")
print("你带着一杆56半、一辆解放牌卡车,和一个人——")
print()
print("凌暮雪。哈尔滨机械中专下乡知青。反动学术权威的后代。")
print("在1979年,你和她站在一起本身就是政治禁忌。")
print("但末日,把这层禁忌撕开了一道口子。")
print()
print("你们要从大连往北,开到哈尔滨。")
print("1000公里。严冬。零下30度。多方势力围追堵截。")
print()
print("=" * 56)
print()
def ask_name(self) -> None:
while True:
name = input("请输入你的姓名:").strip()
if name:
self.player.name = name
print(f"\n欢迎,{name}。沈阳军区通讯团学员兵,党员。")
print("核战失散。不是逃兵。")
print()
break
print("姓名不能为空。")
# ---------- 第1天:核爆日 ----------
def run_day1(self):
"""第1天:核爆→山洞"""
print("\n" + "=" * 56)
print("第1天 · 核爆日")
print("=" * 56)
print("\n刺耳的警报声。窗外,远处城市方向升起一朵巨大的蘑菇云。")
print("凌暮雪冲进宿舍:'快跑!去山洞!我爸说过的那个山洞!'")
print("\n你们逃往大连郊区的山洞……")
input("\n按回车继续...")
print("\n山洞里,有一辆解放牌卡车和一杆56半步枪。")
print("凌暮雪打开箱子,犹豫了一下,抱枪在怀里。")
# 初始化物资(合理数量,避免超重/超体积)
# diesel_20L: 10kg, 12L per item -> 5 items = 50kg, 60L
self.inventory.add('diesel_20L', 5) # 100L柴油
self.inventory.add('canned_meat', 6)
self.inventory.add('flour_bag', 3) # 约75kg面粉
self.inventory.add('blanket', 2)
self.inventory.add('barefoot_doctor_manual', 1)
self.ammo_count = 30 # 30发子弹
print("\n你:给我吧。我学过。")
print("凌暮雪:(沉默)……先放我这。")
print("(系统提示:凌暮雪信任度-2。她没说实话。)")
self.ling.trust -= 2
# 记录这次关键剧情到记忆库
self.bridge.store_memory("第1天:核爆后逃到山洞,凌暮雪把枪抱在怀里没给我", importance="high")
print("\n【初始物资】")
print(self.inventory.status_line())
print(f"弹药:{self.ammo_count}发")
print("\n第1晚:你们在山洞躲避辐射尘暴。")
print("生存系统启动:体温/饥饿/精神开始下降。")
# 夜晚tick
self._night_tick()
input("\n按回车进入第2天...")
# ---------- 第2-6天:探索期 ----------
def run_exploration_day(self):
"""探索日(第2-6天)"""
print(f"\n{'=' * 56}")
print(f"第{self.day}天 · 探索日")
print(f"{'=' * 56}")
print(f"\n当前状态:")
print(self.world.status_line())
print(f"凌暮雪:信任度{self.ling.trust:.0f}")
print(f"你有枪:{'是' if self.player_has_gun else '否'}")
print("\n可探索地点:")
for idx, (name, system) in enumerate(self.exploration_systems.items(), 1):
explored_mark = "✓" if name in self.explored_locations else " "
print(f" [{idx}] {explored_mark} {name} (距离{system.distance}km, 危险{system.danger_level})")
choice = input("\n选择探索地点(输入编号或名称): ").strip()
# 尝试匹配地点
location_name = None
if choice.isdigit():
idx = int(choice) - 1
keys = list(self.exploration_systems.keys())
if 0 <= idx < len(keys):
location_name = keys[idx]
else:
# 直接输入名称
for name in self.exploration_systems:
if choice in name:
location_name = name
break
if location_name and location_name in self.exploration_systems:
system = self.exploration_systems[location_name]
print(f"\n前往{location_name}...")
# 消耗柴油(往返)
fuel_cost = system.distance * 0.5 * 2 # 往返
if self.vehicle.fuel >= fuel_cost:
self.vehicle.fuel -= fuel_cost
print(f"消耗柴油{fuel_cost:.1f}L")
else:
print("柴油不足!无法前往。")
return
print("\n搜索中...")
results = system.search()
print("\n获得物资:")
for item_id, amount in results:
if item_id.startswith('ammo_'):
caliber = item_id.split('_', 1)[1]
self.ammo_count += amount
print(f" 弹药({caliber}) x{amount}")
else:
success = self.inventory.add(item_id, amount)
if success:
from .inventory import ITEM_CATALOG
item_def = ITEM_CATALOG.get(item_id)
item_name = item_def.name if item_def else item_id
print(f" {item_name} x{amount}")
else:
print(f" {item_id} x{amount} (超重,丢弃)")
self.explored_locations.add(location_name)
print(f"\n返回基地...")
print(f"消耗柴油{fuel_cost:.1f}L")
input("\n按回车进入夜晚...")
# 夜晚事件
self.night_event()
else:
print("无效地点,今天浪费。")
def night_event(self):
"""夜晚事件"""
print("\n夜晚,你们在山洞扎营。")
# 生存系统tick
player_events = self.player.tick_effects()
ling_events = self.ling.tick_effects()
if player_events:
print("\n你的状态变化:")
for ev in player_events:
print(f" - {ev}")
if ling_events:
print("\n凌暮雪的状态变化:")
for ev in ling_events:
print(f" - {ev}")
print(f"\n你:HP{self.player.hp:.0f}, 体温{self.player.temperature:.1f}°C")
print(f"凌暮雪:HP{self.ling.hp:.0f}, 精神{self.ling.morale:.0f}")
input("\n按回车睡觉...")
def _night_tick(self):
"""简化的夜晚tick(不显示详细事件)"""
self.player.tick_effects()
self.ling.tick_effects()
# ---------- 关键剧情事件 ----------
def blizzard_event(self):
"""暴风雪事件(第3天)"""
print("\n" + "=" * 56)
print("暴风雪!")
print("=" * 56)
print("\n夜晚,暴风雪袭来。气温骤降到-35°C。")
print("凌暮雪主动靠过来取暖……")
print("\n(系统提示:凌暮雪信任度+5。她在极端天气下稍微放下防备。)")
self.ling.trust += 5
def father_story_event(self):
"""父亲故事事件(第5天)"""
print("\n" + "=" * 56)
print("深夜·父亲的故事")
print("=" * 56)
print("\n凌暮雪第一次主动讲述家庭背景:")
print("'我爸……他是大连理工机械系教授,1950年代留苏的。'")
print("'后来被打倒,下放到北大荒……我还不知道他死没死。'")
print("\n(系统提示:凌暮雪信任度+8。她开始信任你。)")
self.ling.trust += 8
def give_gun_event(self):
"""给枪事件(第6天)"""
print("\n" + "=" * 56)
print("遭遇土匪!")
print("=" * 56)
print("\n前方公路有人设卡。是土匪。")
print("凌暮雪犹豫很久,把56半和子弹递给你。")
print("\n凌暮雪:'……枪,你拿着。'")
print("凌暮雪:'……别对着我。'")
print("\n(系统提示:凌暮雪信任度+5。她把命交给你了。)")
print("(系统提示:你获得56半步枪!)")
self.ling.trust += 5
self.player_has_gun = True
def depart_event(self):
"""出发事件(第7天)"""
print("\n" + "=" * 56)
print("第7天 · 出发")
print("=" * 56)
print("\n辐射平息。")
print("凌暮雪:'……我们走吧。'")
print("\n你们开车离开山洞,开始正式逃亡。")
print("\n(系统提示:前6天教程完成!正式游戏开始。)")
# ---------- 主循环 ----------
def main_loop(self) -> None:
while True:
self.turn += 1
self.show_hud()
cmd = input("\n> ").strip()
if not cmd:
continue
# 别名
cmd_lower = cmd.lower()
if cmd_lower in ("q", "quit", "exit"):
cmd = "退出"
elif cmd_lower in ("h", "?", "help"):
cmd = "帮助"
elif cmd in ("走", "开", "前进", "f", "forward"):
cmd = "前进"
elif cmd in ("探", "探索", "e", "explore"):
cmd = "探索"
elif cmd in ("s", "status", "状态", "查"):
cmd = "状态"
elif cmd in ("对话", "说话", "聊", "talk", "t"):
cmd = "对话"
elif cmd in ("无线电", "电台", "听", "radio", "r"):
cmd = "无线电"
if cmd == "前进":
self.cmd_advance()
elif cmd == "探索":
self.cmd_explore()
elif cmd == "状态":
self.cmd_status()
elif cmd == "对话":
self.cmd_talk()
elif cmd == "无线电":
self.cmd_radio()
elif cmd == "帮助":
self.cmd_help()
elif cmd == "退出":
if self.confirm_exit():
print("\n……卡车的引擎熄了。1979年的风声又响了起来。")
print("(未保存进度已丢失)")
break
else:
print(f"未知命令:{cmd}。输入「帮助」查看可用命令。")
# 每轮结束做状态检查
self.end_of_turn_check()
# ---------- HUD ----------
def show_hud(self) -> None:
print("\n" + "-" * 56)
print(self.world.status_line())
print(self.vehicle.status_line())
print(self.player.status_line())
print(self.ling.status_line())
print("-" * 56)
# ---------- 命令 ----------
def cmd_advance(self) -> None:
if not self.vehicle.alive:
print("车已报废。必须先找到新车才能继续前进。")
return
result = self.vehicle.advance(self.ADVANCE_KM)
self.world.advance_km(self.ADVANCE_KM)
self.world.advance_time(self.ADVANCE_TIME_STEPS)
self.world.fuel_on_route += result["fuel_used"]
print(f"\n你挂上挡,卡车轰鸣着碾过冻土。前进 {self.ADVANCE_KM:.0f} 公里。")
print(f" 油耗 {-result['fuel_used']:.1f}L 车损 {-result['hull_lost']*100:.2f}%")
for ev in result["events"]:
print(f" ⚠ {ev}")
# 前进可能触发凌暮雪搭话(公路段 ii)
if self.ling.alive and random.random() < 0.45:
print()
print(self.ling.road_chatter(self.world, self.vehicle, self.player, bridge=self.bridge))
if self.world.arrived:
print("\n" + "=" * 56)
print("前方地平线上,出现了哈尔滨的轮廓。")
print("(序章抵达——分支点暂未实现)")
print("=" * 56)
def cmd_explore(self) -> None:
"""探索命令:使用改进的探索系统(多步骤+区域选择)。"""
print("\n你停下车,在周边探索。距离不缩短,但时间在流逝。")
self.world.advance_time(self.EXPLORE_TIME_STEPS)
veh_ev = self.vehicle.explore_tick()
for ev in veh_ev["events"]:
print(f" ⚠ {ev}")
# 尝试使用改进探索系统
improved = ImprovedExploration(self)
# 根据当前位置选择探索地点
location_name = self._get_current_location_name()
if location_name and location_name in self.exploration_systems:
result = improved.explore_location(location_name)
if result['success']:
# 显示叙事
print(f"\n{result['narrative']}")
# 显示获得的物品
if result['items_found']:
print("\n获得物资:")
for item_id, amount in result['items_found']:
if item_id.startswith('ammo_'):
caliber = item_id.split('_', 1)[1]
print(f" 弹药({caliber}) x{amount}")
else:
from .inventory import ITEM_CATALOG
item_def = ITEM_CATALOG.get(item_id)
item_name = item_def.name if item_def else item_id
print(f" {item_name} x{amount}")
# 显示凌暮雪评论
if result['ling_comment']:
print(f"\n凌暮雪:'{result['ling_comment']}'")
# 显示遭遇事件
if result['encounter']:
print(f"\n⚠ {result['encounter']['description']}")
# 数值变化
if result['radiation'] > 0:
print(f"\n辐射增加:{result['radiation']:.1f} mSv")
if result['trust_change'] != 0:
sign = '+' if result['trust_change'] > 0 else ''
print(f"信任度变化:{sign}{result['trust_change']:.1f}")
else:
# 降级到旧逻辑
self._fallback_explore_logic()
else:
# 没有匹配地点,使用旧逻辑
self._fallback_explore_logic()
def _get_current_location_name(self) -> str:
"""根据当前游戏状态获取当前位置名称。"""
# 简化:返回随机一个未探索或已探索的地点
available = list(self.exploration_systems.keys())
if available:
return random.choice(available)
return '未知地点'
def _fallback_explore_logic(self):
"""旧探索逻辑(保持兼容)。"""
# 占位:探索有小概率捡到物资
r = random.random()
if r < 0.15:
added = self.inventory.add('diesel_20L', 1)
if added:
print(" 你在一个废弃的苏军吉普里翻到了半桶柴油。+20L")
else:
print(" 你在一个废弃的苏军吉普里翻到了柴油,但装不下了。")
elif r < 0.25:
self.player.heal(5.0)
self.ling.heal(5.0)
print(" 你找到一个医药包。两人各回 5 HP。")
elif r < 0.35:
self.player.hunger = max(0, self.player.hunger - 10)
print(" 你翻到半袋面粉。不那么饿了。")
else:
print(" ……什么都没找到。风声很大。")
# 夜晚探索的危险
if self.world.time_phase in ("夜", "深夜"):
if random.random() < 0.2:
dmg = random.uniform(3, 8)
self.player.take_damage(dmg, "冻伤")
self.ling.take_damage(dmg * 0.8)
print(f" ⚠ 严寒里探索太久,两人都冻伤了。各 -{dmg:.1f} HP")
def cmd_status(self) -> None:
print("\n【详细状态】")
print(self.world.status_line())
print()
print(self.vehicle.status_line())
print()
print(self.player.status_line())
print()
print(self.ling.status_line())
print()
print(self.radio.status_line())
print()
print(self.inventory.status_line())
print(f"弹药:{self.ammo_count}发")
print(f"有枪:{'是' if self.player_has_gun else '否'}")
def cmd_talk(self) -> None:
if self.ling.left_silently:
print("\n你对着空荡荡的副驾驶,想说什么,又咽了回去。")
print("她的半瓶水还在你这边。")
return
print() # 空行
text = input("你说:").strip()
context = self._build_dialogue_context()
reply = self.ling.talk(text, bridge=self.bridge, context=context)
print()
print(f"凌暮雪:{reply}")
def _build_dialogue_context(self) -> dict:
"""构建对话上下文,让凌暮雪的回应符合当前游戏状态。"""
return {
'day': self.day,
'trust': self.ling.trust,
'location': '山洞' if self.day < 7 else '公路',
'weather': getattr(self.world, 'weather', '未知'),
'recent_event': self._recent_event_name(),
'player_has_gun': self.player_has_gun,
'phase': self.phase,
}
def _recent_event_name(self) -> str:
"""根据当前天数返回最近发生的剧情事件名。"""
if self.day <= 1:
return '核爆'
if self.day == 3:
return '暴风雪'
if self.day == 5:
return '父亲故事'
if self.day == 6:
return '给枪'
if self.day == 7:
return '出发'
return '探索'
def cmd_radio(self) -> None:
print()
print(self.radio.scan(self.world))
def cmd_help(self) -> None:
print("\n【可用命令】")
print(" 前进 - 沿公路前进 35km(耗燃料、车损、推进距离)")
print(" 探索 - 停车探索周边(不减距离、耗时间、可能捡物资)")
print(" 状态 - 查看详细状态")
print(" 对话 - 跟凌暮雪说话")
print(" 无线电 - 扫描短波信号")
print(" 帮助 - 显示本帮助")
print(" 退出 - 退出游戏")
def confirm_exit(self) -> bool:
return input("\n确定退出?(未保存进度将丢失)[y/N] ").strip().lower() in ("y", "yes")
# ---------- 回合结束检查 ----------
def end_of_turn_check(self) -> None:
# 玩家死亡
if not self.player.alive:
print("\n" + "=" * 56)
print("你的 HP 归零。眼前一黑。")
print("(Game Over - 读档重来)")
print("=" * 56)
sys.exit(0)
# 凌暮雪死亡(非无声离开)
if not self.ling.alive and not self.ling.left_silently:
print("\n" + "=" * 56)
print("凌暮雪的 HP 归零。她靠在你肩上,没了呼吸。")
print("(Game Over - 她死在了你怀里)")
print("=" * 56)
sys.exit(0)
# 车报废
if not self.vehicle.alive:
print("\n⚠ 车已报废。必须通过「探索」找到新车,否则无法前进。")