技术准备

在开始编码之前,我们需要准备开发环境和相关工具。以下是开发 StarForge Colony 所需的技术栈和资源。

1. 技术栈

  • 编程语言:Python 3.x(推荐 3.8 或更高版本)。
  • 核心库
  • random:生成随机事件、资源分布和环境挑战。
  • time:控制游戏节奏和事件触发。
  • json:保存和加载殖民地状态。
  • pygame(可选):用于图形界面和殖民地布局可视化。
  • 数据存储
  • 使用字典存储资源、建筑和科技数据。
  • 列表存储任务、人口和事件状态。
  • 用户界面:基于命令行界面(CLI)显示资源、建筑和交互,图形界面作为扩展。
  • 依赖安装
  • randomtime 和 json 是 Python 标准库,无需额外安装。
  • pygame(可选):pip install pygame

2. 开发环境

确保已安装 Python(可从 python.org 下载)。推荐使用 Visual Studio Code 或 PyCharm 作为开发工具,提供代码补全和调试支持。本游戏的核心版本基于 CLI,扩展部分引入图形界面。项目结构如下:

starforge_colony/
├── main.py           # 主程序入口
└── game.py           # 游戏逻辑模块

3. 游戏目标

玩家将扮演一名殖民地指挥官,目标是在 50 个回合(模拟 50 天)内达成以下目标:建立一个容纳 100 人口的繁荣殖民地,解锁所有科技,维持高幸福度(>80),并应对环境挑战。游戏采用回合制,每回合代表一天,玩家需要:

  • 采集资源:开采矿物、能源和水。
  • 建设建筑:建造功能性建筑,满足人口需求。
  • 研发科技:解锁高级建筑和资源效率。
  • 管理人口:分配劳动力,提升幸福度。
  • 应对事件:处理陨石雨、辐射风暴或设备故障。
  • 保存/加载:保存游戏进度以便继续。

游戏设计与核心功能

1. 游戏结构

我们将游戏分解为多个模块,使用类和函数封装功能,确保代码清晰且易于维护。以下是核心设计:

  • Resource 类:定义资源类型(矿物、能源、水)。
  • Building 类:表示建筑,包含资源需求、功能和维护成本。
  • Technology 类:定义科技树,解锁新建筑和效率提升。
  • Colony 类:管理殖民地状态,包括资源、人口和建筑。
  • StarForgeGame 类:管理游戏状态、任务和主循环。
  • 算法
  • 资源管理:检查资源是否足够建造或维护。
  • 人口增长:基于幸福度和住宅容量模拟人口变化。
  • 事件触发:随机生成环境挑战,影响资源或幸福度。
  • 数据结构
  • 资源:字典存储矿物、能源和水。
  • 建筑:字典存储名称、成本和功能。
  • 科技:列表存储科技名称和解锁条件。
  • 人口:跟踪数量、幸福度和劳动力。
  • 游戏状态:回合数、资源、建筑和科技。

2. 核心代码实现

以下是游戏的完整代码框架,我们将逐一讲解每个模块的实现细节。

2.1 资源类:Resource

Resource 类定义资源类型及其属性。

# game.py
class Resource:def __init__(self, name, amount=0, production_rate=0):"""初始化资源"""self.name = name  # 资源名称self.amount = amount  # 当前数量self.production_rate = production_rate  # 每回合生产速率

说明

  • __init__:初始化资源名称、数量和生产速率。

2.2 建筑类:Building

Building 类定义建筑的属性和功能。

# game.py (续)
class Building:def __init__(self, name, cost, maintenance, function, capacity=0):"""初始化建筑"""self.name = name  # 建筑名称self.cost = cost  # 建造成本 {资源: 数量}self.maintenance = maintenance  # 维护成本 {资源: 数量}self.function = function  # 功能(如增加资源生产或人口容量)self.capacity = capacity  # 容量(如人口或存储)self.unlocked = False  # 是否解锁self.active = False  # 是否启用

说明

  • __init__:初始化建筑名称、成本、维护费用、功能和容量。

2.3 科技类:Technology

Technology 类定义科技树。

# game.py (续)
class Technology:def __init__(self, name, cost, unlocks):"""初始化科技"""self.name = name  # 科技名称self.cost = cost  # 研发成本 {资源: 数量}self.unlocks = unlocks  # 解锁的建筑或效果self.researched = False  # 是否已研发

说明

  • __init__:初始化科技名称、研发成本和解锁内容。

2.4 殖民地类:Colony

Colony 类管理殖民地状态和操作。

# game.py (续)
import randomclass Colony:def __init__(self):"""初始化殖民地"""self.population = 10  # 初始人口self.happiness = 50  # 初始幸福度self.resources = {"Minerals": Resource("Minerals", 100, 5),"Energy": Resource("Energy", 100, 5),"Water": Resource("Water", 100, 5)}self.buildings = self.create_buildings()self.buildings["Habitat"].unlocked = Trueself.buildings["Habitat"].active = Trueself.technologies = self.create_technologies()self.labor = 5  # 初始劳动力self.storage_capacity = 200  # 初始存储容量def create_buildings(self):"""创建建筑"""return {"Habitat": Building("Habitat", {"Minerals": 50}, {"Energy": 2, "Water": 1}, "Population", 20),"Mine": Building("Mine", {"Minerals": 30, "Energy": 20}, {"Energy": 1}, "Minerals", 10),"Solar Plant": Building("Solar Plant", {"Minerals": 40}, {"Minerals": 1}, "Energy", 10),"Hydroponics": Building("Hydroponics", {"Minerals": 30, "Water": 20}, {"Energy": 1}, "Water", 10),"Research Lab": Building("Research Lab", {"Minerals": 50, "Energy": 30}, {"Energy": 2}, "Research", 0),"Recreation Center": Building("Recreation Center", {"Minerals": 40, "Water": 10}, {"Energy": 1}, "Happiness", 10)}def create_technologies(self):"""创建科技"""return [Technology("Advanced Mining", {"Minerals": 50, "Energy": 20}, {"Mine": {"production_rate": 5}}),Technology("Solar Efficiency", {"Minerals": 40, "Energy": 30}, {"Solar Plant": {"production_rate": 5}}),Technology("Hydroponics Optimization", {"Minerals": 30, "Water": 20}, {"Hydroponics": {"production_rate": 5}}),Technology("Advanced Habitats", {"Minerals": 60, "Energy": 40}, {"Habitat": {"capacity": 10}}),Technology("Recreation Systems", {"Minerals": 50, "Water": 30}, {"Recreation Center": {"capacity": 5}})]def build(self, building_name):"""建造建筑"""building = self.buildings.get(building_name)if not building or not building.unlocked:print(f"{building_name} 未解锁或无效!")return Falseif building.active:print(f"{building_name} 已建成!")return Falseif all(self.resources[r].amount >= c for r, c in building.cost.items()) and self.labor >= 2:for r, c in building.cost.items():self.resources[r].amount -= cself.labor -= 2building.active = Trueif building.function == "Population":self.storage_capacity += building.capacityelif building.function in ["Minerals", "Energy", "Water"]:self.resources[building.function].production_rate += building.capacityelif building.function == "Happiness":self.happiness += building.capacityprint(f"成功建造 {building_name},消耗劳动力 2")return Trueprint("资源或劳动力不足!")return Falsedef research(self, tech_name):"""研发科技"""tech = next((t for t in self.technologies if t.name == tech_name and not t.researched), None)if not tech:print("科技无效或已研发!")return Falseif all(self.resources[r].amount >= c for r, c in tech.cost.items()) and self.buildings["Research Lab"].active:for r, c in tech.cost.items():self.resources[r].amount -= ctech.researched = Truefor building_name, effect in tech.unlocks.items():building = self.buildings[building_name]building.unlocked = Truefor attr, value in effect.items():if attr == "production_rate":self.resources[building.function].production_rate += valueelif attr == "capacity":building.capacity += valueif building.function == "Population" and building.active:self.storage_capacity += valueelif building.function == "Happiness" and building.active:self.happiness += valueprint(f"成功研发 {tech_name},解锁或升级 {list(tech.unlocks.keys())}")return Trueprint("资源不足或需要研究实验室!")return Falsedef maintain(self):"""维护建筑并更新资源"""for building in self.buildings.values():if building.active:for r, c in building.maintenance.items():self.resources[r].amount -= cif self.resources[r].amount < 0:building.active = Falseprint(f"{building.name} 因 {r} 不足已停用!")if building.function == "Population":self.storage_capacity -= building.capacityelif building.function in ["Minerals", "Energy", "Water"]:self.resources[building.function].production_rate -= building.capacityelif building.function == "Happiness":self.happiness -= building.capacitydef produce(self):"""生产资源并更新人口"""for resource in self.resources.values():resource.amount += resource.production_rateif resource.amount > self.storage_capacity:resource.amount = self.storage_capacityprint(f"{resource.name} 超出存储容量,已限制为 {self.storage_capacity}")if self.storage_capacity > self.population and self.happiness > 50:self.population += random.randint(1, 3)elif self.happiness < 30:self.population -= random.randint(1, 2)if self.population > self.storage_capacity:self.population = self.storage_capacityprint("人口超出住宅容量!")self.happiness = max(0, min(100, self.happiness + random.randint(-5, 5)))self.labor = self.population // 2

说明

  • __init__:初始化人口、幸福度、资源、建筑和科技。
  • create_buildings:定义建筑及其属性。
  • create_technologies:定义科技树及其解锁效果。
  • build:消耗资源和劳动力建造建筑。
  • research:研发科技,解锁或升级建筑。
  • maintain:扣除建筑维护成本,停用资源不足的建筑。
  • produce:生产资源,更新人口和幸福度。

2.5 游戏类:StarForgeGame

StarForgeGame 类管理游戏状态和逻辑。

# game.py (续)
import time
import jsonclass StarForgeGame:def __init__(self):"""初始化游戏"""self.colony = Colony()self.turn = 0self.max_turns = 50self.game_over = Falsedef run(self):"""游戏主循环"""print("欢迎来到《StarForge Colony》!目标:在 50 天内建立繁荣殖民地(100 人口,幸福度 > 80,解锁所有科技)。")while not self.game_over:self.display_state()self.random_event()action = self.get_action()if action == "build":self.build()elif action == "research":self.research()elif action == "allocate_labor":self.allocate_labor()elif action == "save_game":self.save_game()elif action == "load_game":self.load_game()elif action == "end_turn":self.end_turn()if self.check_win():print("恭喜!你建立了繁荣的殖民地!")self.game_over = Trueif self.check_lose():print("游戏结束。未能在 50 天内达成目标,或人口不足。")self.game_over = Truetime.sleep(1)def display_state(self):"""显示游戏状态"""print(f"\n天数 {self.turn + 1}")print(f"人口: {self.colony.population} (容量 {self.colony.storage_capacity})")print(f"幸福度: {self.colony.happiness}")print(f"劳动力: {self.colony.labor}")print("资源:", {r: f"{v.amount} (生产 {v.production_rate}/回合)" for r, v in self.colony.resources.items()})print("建筑:", [f"{k} ({'启用' if v.active else '停用' if v.unlocked else '未解锁'})" for k, v in self.colony.buildings.items()])print("科技:", [f"{t.name} ({'已研发' if t.researched else '未研发'})" for t in self.colony.technologies])def get_action(self):"""获取玩家行动"""print("\n你想做什么?")print("1. 建造建筑")print("2. 研发科技")print("3. 分配劳动力")print("4. 保存游戏")print("5. 加载游戏")print("6. 结束天数")choice = input("输入选项 (1-6): ")actions = {"1": "build","2": "research","3": "allocate_labor","4": "save_game","5": "load_game","6": "end_turn"}return actions.get(choice, self.get_action())def build(self):"""建造建筑"""print("可建造建筑:")for name, building in self.colony.buildings.items():if building.unlocked and not building.active:print(f"{name}: 成本 {building.cost}, 维护 {building.maintenance}")building_name = input("输入建筑名称:")self.colony.build(building_name)def research(self):"""研发科技"""print("可研发科技:")for tech in self.colony.technologies:if not tech.researched:print(f"{tech.name}: 成本 {tech.cost}")tech_name = input("输入科技名称:")self.colony.research(tech_name)def allocate_labor(self):"""分配劳动力"""print(f"当前劳动力: {self.colony.labor}")print("可分配建筑:")for name, building in self.colony.buildings.items():if building.active and building.function in ["Minerals", "Energy", "Water"]:print(f"{name}: 当前生产 {self.colony.resources[building.function].production_rate}")building_name = input("输入建筑名称(或按 Enter 跳过):")if building_name and building_name in self.colony.buildings and self.colony.buildings[building_name].active:if self.colony.labor >= 1:self.colony.labor -= 1self.colony.resources[self.colony.buildings[building_name].function].production_rate += 2print(f"分配 1 劳动力到 {building_name},增加 2 {self.colony.buildings[building_name].function} 生产")else:print("劳动力不足!")else:print("无效建筑或已跳过!")def random_event(self):"""随机事件"""event = random.choice(["None", "Meteor Shower", "Radiation Storm", "Equipment Failure"])if event == "Meteor Shower":damage = random.randint(5, 15)self.colony.resources["Minerals"].amount -= damageprint(f"陨石雨,损失 {damage} 矿物!")elif event == "Radiation Storm":self.colony.happiness -= 10print("辐射风暴,幸福度下降 10!")elif event == "Equipment Failure":for building in self.colony.buildings.values():if building.active and random.random() < 0.3:building.active = Falseprint(f"{building.name} 因设备故障停用!")if building.function == "Population":self.colony.storage_capacity -= building.capacityelif building.function in ["Minerals", "Energy", "Water"]:self.colony.resources[building.function].production_rate -= building.capacityelif building.function == "Happiness":self.colony.happiness -= building.capacitydef save_game(self):"""保存游戏状态"""state = {"turn": self.turn,"colony": {"population": self.colony.population,"happiness": self.colony.happiness,"labor": self.colony.labor,"storage_capacity": self.colony.storage_capacity,"resources": {r: {"amount": v.amount, "production_rate": v.production_rate} for r, v in self.colony.resources.items()},"buildings": {k: {"unlocked": v.unlocked, "active": v.active} for k, v in self.colony.buildings.items()},"technologies": [{"name": t.name, "researched": t.researched} for t in self.colony.technologies]}}with open("savegame.json", "w") as f:json.dump(state, f)print("游戏已保存!")def load_game(self):"""加载游戏状态"""try:with open("savegame.json", "r") as f:state = json.load(f)self.turn = state["turn"]self.colony.population = state["colony"]["population"]self.colony.happiness = state["colony"]["happiness"]self.colony.labor = state["colony"]["labor"]self.colony.storage_capacity = state["colony"]["storage_capacity"]for r, data in state["colony"]["resources"].items():self.colony.resources[r].amount = data["amount"]self.colony.resources[r].production_rate = data["production_rate"]for name, data in state["colony"]["buildings"].items():self.colony.buildings[name].unlocked = data["unlocked"]self.colony.buildings[name].active = data["active"]for tech_data in state["colony"]["technologies"]:tech = next(t for t in self.colony.technologies if t.name == tech_data["name"])tech.researched = tech_data["researched"]print("游戏已加载!")except FileNotFoundError:print("没有找到存档文件!")def end_turn(self):"""结束当前天数"""self.turn += 1self.colony.maintain()self.colony.produce()def check_win(self):"""检查胜利条件"""return (self.colony.population >= 100 and self.colony.happiness > 80 and all(t.researched for t in self.colony.technologies))def check_lose(self):"""检查失败条件"""return self.turn > self.max_turns or self.colony.population <= 0

说明

  • __init__:初始化殖民地和回合数。
  • run:游戏主循环,显示状态、触发事件、处理行动。
  • display_state:显示人口、幸福度、资源、建筑和科技。
  • get_action:提供交互菜单,返回玩家选择。
  • build:选择并建造建筑。
  • research:研发科技,解锁或升级建筑。
  • allocate_labor:分配劳动力提升资源生产。
  • random_event:触发陨石雨、辐射风暴或设备故障。
  • save_game 和 load_game:保存和加载游戏状态。
  • end_turn:推进天数,维护建筑并生产资源。
  • check_win 和 check_lose:检查是否达成目标或失败。

2.6 主程序:main.py

启动游戏的入口文件。

# main.py
from game import StarForgeGameif __name__ == "__main__":game = StarForgeGame()game.run()

运行游戏

1. 启动游戏

在项目目录下运行:

python main.py

2. 游戏流程

  1. 初始化
  • 玩家从 10 人口、50 幸福度、100 单位资源(矿物、能源、水)开始,初始解锁“Habitat”建筑。
  1. 每回合行动
  • 显示状态:查看人口、幸福度、资源、建筑和科技。
  • 建造建筑:消耗资源和劳动力建造建筑。
  • 研发科技:解锁新建筑或提升效率。
  • 分配劳动力:增加资源生产效率。
  • 保存/加载:保存进度或恢复游戏。
  • 结束天数:维护建筑、生产资源、触发随机事件。
  1. 游戏结束
  • 人口 ≥ 100、幸福度 > 80、解锁所有科技胜利,超过 50 天或人口为 0 失败。

3. 示例运行

欢迎来到《StarForge Colony》!目标:在 50 天内建立繁荣殖民地(100 人口,幸福度 > 80,解锁所有科技)。天数 1
人口: 10 (容量 20)
幸福度: 50
劳动力: 5
资源: {'Minerals': '100 (生产 5/回合)', 'Energy': '100 (生产 5/回合)', 'Water': '100 (生产 5/回合)'}
建筑: ['Habitat (启用)', 'Mine (未解锁)', 'Solar Plant (未解锁)', 'Hydroponics (未解锁)', 'Research Lab (未解锁)', 'Recreation Center (未解锁)']
科技: ['Advanced Mining (未研发)', 'Solar Efficiency (未研发)', 'Hydroponics Optimization (未研发)', 'Advanced Habitats (未研发)', 'Recreation Systems (未研发)']你想做什么?
1. 建造建筑
2. 研发科技
3. 分配劳动力
4. 保存游戏
5. 加载游戏
6. 结束天数
输入选项 (1-6): 1可建造建筑:
输入建筑名称:Mine
Mine 未解锁或无效!天数 1
人口: 10 (容量 20)
幸福度: 50
劳动力: 5
资源: {'Minerals': '100 (生产 5/回合)', 'Energy': '100 (生产 5/回合)', 'Water': '100 (生产 5/回合)'}
建筑: ['Habitat (启用)', 'Mine (未解锁)', 'Solar Plant (未解锁)', 'Hydroponics (未解锁)', 'Research Lab (未解锁)', 'Recreation Center (未解锁)']
科技: ['Advanced Mining (未研发)', 'Solar Efficiency (未研发)', 'Hydroponics Optimization (未研发)', 'Advanced Habitats (未研发)', 'Recreation Systems (未研发)']你想做什么?
1. 建造建筑
2. 研发科技
3. 分配劳动力
4. 保存游戏
5. 加载游戏
6. 结束天数
输入选项 (1-6): 2可研发科技:
Advanced Mining: 成本 {'Minerals': 50, 'Energy': 20}
Solar Efficiency: 成本 {'Minerals': 40, 'Energy': 30}
Hydroponics Optimization: 成本 {'Minerals': 30, 'Water': 20}
Advanced Habitats: 成本 {'Minerals': 60, 'Energy': 40}
Recreation Systems: 成本 {'Minerals': 50, 'Water': 30}
输入科技名称:Advanced Mining
资源不足或需要研究实验室!天数 1
人口: 10haviors: ['Advanced Mining (未研发)', 'Solar Efficiency (未研发)', 'Hydroponics Optimization (未研发)', 'Advanced Habitats (未研发)', 'Recreation Systems (未研发)']你想做什么?
1. 建造建筑
2. 研发科技
3. 分配劳动力
4. 保存游戏
5. 加载游戏
6. 结束天数
输入选项 (1-6): 1可建造建筑:
输入建筑名称:Research Lab
Research Lab 未解锁或无效!天数 1
人口: 10 (容量 20)
幸福度: 50
劳动力: 5
资源: {'Minerals': '100 (生产 5/回合)', 'Energy': '100 (生产 5/回合)', 'Water': '100 (生产 5/回合)'}
建筑: ['Habitat (启用)', 'Mine (未解锁)', 'Solar Plant (未解锁)', 'Hydroponics (未解锁)', 'Research Lab (未解锁)', 'Recreation Center (未解锁)']
科技: ['Advanced Mining (未研发)', 'Solar Efficiency (未研发)', 'Hydroponics Optimization (未研发)', 'Advanced Habitats (未研发)', 'Recreation Systems (未研发)']你想做什么?
1. 建造建筑
2. 研发科技
3. 分配劳动力
4. 保存游戏
5. 加载游戏
6. 结束天数
输入选项 (1-6): 6天数 2
人口: 12 (容量 20)
幸福度: 53
劳动力: 6
资源: {'Minerals': '103 (生产 5/回合)', 'Energy': '103 (生产 5/回合)', 'Water': '104 (生产 5/回合)'}
建筑: ['Habitat (启用)', 'Mine (未解锁)', 'Solar Plant (未解锁)', 'Hydroponics (未解锁)', 'Research Lab (未解锁)', 'Recreation Center (未解锁)']
科技: ['Advanced Mining (未研发)', 'Solar Efficiency (未研发)', 'Hydroponics Optimization (未研发)', 'Advanced Habitats (未研发)', 'Recreation Systems (未研发)']
陨石雨,损失 10 矿物!你想做什么?
1. 建造建筑
2. 研发科技
3. 分配劳动力
4. 保存游戏
5. 加载游戏
6. 结束天数
输入选项 (1-6): 2可研发科技:
Advanced Mining: 成本 {'Minerals': 50, 'Energy': 20}
Solar Efficiency: 成本 {'Minerals': 40, 'Energy': 30}
Hydroponics Optimization: 成本 {'Minerals': 30, 'Water': 20}
Advanced Habitats: 成本 {'Minerals': 60, 'Energy': 40}
Recreation Systems: 成本 {'Minerals': 50, 'Water': 30}
输入科技名称:Advanced Mining
资源不足或需要研究实验室!天数 2
人口: 12 (容量 20)
幸福度: 53
劳动力: 6
资源: {'Minerals': '93 (生产 5/回合)', 'Energy': '103 (生产 5/回合)', 'Water': '104 (生产 5/回合)'}
建筑: ['Habitat (启用)', 'Mine (未解锁)', 'Solar Plant (未解锁)', 'Hydroponics (未解锁)', 'Research Lab (未解锁)', 'Recreation Center (未解锁)']
科技: ['Advanced Mining (未研发)', 'Solar Efficiency (未研发)', 'Hydroponics Optimization (未研发)', 'Advanced Habitats (未研发)', 'Recreation Systems (未研发)']你想做什么?
1. 建造建筑
2. 研发科技
3. 分配劳动力
4. 保存游戏
5. 加载游戏
6. 结束天数
输入选项 (1-6): 1可建造建筑:
输入建筑名称:Habitat
成功建造 Habitat,消耗劳动力 2

分析

  • 第一天尝试建造和研发,但因建筑或科技未解锁失败。
  • 第二天人口增长,触发陨石雨事件,损失矿物。
  • 成功建造第二个 Habitat,增加人口容量。

游戏机制详解

1. 资源管理

  • 资源类型
  • 矿物:用于建造和科技研发。
  • 能源:用于建筑维护和科技研发。
  • 水:用于人口生存和农业。
  • 生产:每回合生产资源,基于建筑和劳动力分配。
  • 存储:受容量限制,初始 200 单位。

2. 建筑功能

  • Habitat:增加人口容量。
  • Mine:增加矿物生产。
  • Solar Plant:增加能源生产。
  • Hydroponics:增加水生产。
  • Research Lab:允许科技研发。
  • Recreation Center:提升幸福度。

3. 科技研发

  • 科技树
  • Advanced Mining:解锁 Mine 并提升生产。
  • Solar Efficiency:解锁 Solar Plant 并提升生产。
  • Hydroponics Optimization:解锁 Hydroponics 并提升生产。
  • Advanced Habitats:提升 Habitat 容量。
  • Recreation Systems:解锁 Recreation Center 并提升幸福度。
  • 研发条件:需要资源和 Research Lab。

4. 人口与幸福度

  • 人口增长:幸福度 > 50 且有住宅容量时增加。
  • 人口减少:幸福度 < 30 时减少。
  • 幸福度:受建筑和事件影响,范围 0-100。
  • 劳动力:人口 / 2,可分配到生产建筑。

5. 随机事件

  • 陨石雨:损失 5-15 矿物。
  • 辐射风暴:幸福度 -10。
  • 设备故障:30% 几率停用建筑。

6. 胜利与失败

  • 胜利:人口 ≥ 100,幸福度 > 80,解锁所有科技。
  • 失败:超过 50 天或人口为 0。

游戏扩展与优化

当前版本是一个功能完整的行星殖民地建设游戏原型,我们可以通过以下方式增强游戏性、技术实现和教育价值。

1. 游戏性增强

  • 新建筑:添加防御塔、贸易站等。
  • 任务系统:完成特定目标(如生产 200 矿物)获得奖励。
  • 外星生物:引入友好或敌对生物,影响资源或安全。
  • 动态环境:模拟昼夜循环或季节变化。

示例代码:任务系统

class Task:def __init__(self, id, target, target_amount, reward_resources):"""初始化任务"""self.id = idself.target = target  # 目标(资源或人口)self.target_amount = target_amount  # 目标数量self.reward_resources = reward_resources  # 奖励资源class Colony:def __init__(self):# ... 其他初始化代码 ...self.tasks = []def generate_task(self, turn):"""生成任务"""if random.random() < 0.5:task_id = len(self.tasks) + 1target = random.choice(["Minerals", "Energy", "Water", "Population"])target_amount = random.randint(50, 100) if target != "Population" else random.randint(20, 50)reward_resources = {r: 20 for r in self.resources}task = Task(task_id, target, target_amount, reward_resources)task.created_turn = turnself.tasks.append(task)print(f"任务 ID {task_id}: 收集 {target_amount} {target},奖励 {reward_resources}")def complete_task(self, task_id):"""完成任务"""task = next((t for t in self.tasks if t.id == task_id), None)if not task:print("无效任务 ID!")returnif task.target == "Population":if self.population >= task.target_amount:for r, amount in task.reward_resources.items():self.resources[r].amount += amountself.tasks.remove(task)print(f"任务 ID {task_id} 完成!获得 {task.reward_resources}")else:print(f"人口不足({self.population}/{task.target_amount})")else:if self.resources[task.target].amount >= task.target_amount:for r, amount in task.reward_resources.items():self.resources[r].amount += amountself.tasks.remove(task)print(f"任务 ID {task_id} 完成!获得 {task.reward_resources}")else:print(f"{task.target} 不足({self.resources[task.target].amount}/{task.target_amount})")class StarForgeGame:def run(self):print("欢迎来到《StarForge Colony》!")while not self.game_over:self.display_state()self.colony.generate_task(self.turn)self.random_event()action = self.get_action()if action == "build":self.build()elif action == "research":self.research()elif action == "allocate_labor":self.allocate_labor()elif action == "complete_task":self.complete_task()elif action == "save_game":self.save_game()elif action == "load_game":self.load_game()elif action == "end_turn":self.end_turn()if self.check_win():print("恭喜!你建立了繁荣的殖民地!")self.game_over = Trueif self.check_lose():print("游戏结束。未能在 50 天内达成目标,或人口不足。")self.game_over = Truetime.sleep(1)def get_action(self):print("\n你想做什么?")print("1. 建造建筑")print("2. 研发科技")print("3. 分配劳动力")print("4. 完成任务")print("5. 保存游戏")print("6. 加载游戏")print("7. 结束天数")choice = input("输入选项 (1-7): ")actions = {"1": "build","2": "research","3": "allocate_labor","4": "complete_task","5": "save_game","6": "load_game","7": "end察觉return actions.get(choice, self.get_action())def complete_task(self):if not self.colony.tasks:print("没有可用任务!")returnprint("可用任务:")for task in self.colony.tasks:print(f"ID {task.id}: 收集 {task.target_amount} {task.target}")try:task_id = int(input("输入任务 ID: "))self.colony.complete_task(task_id)except ValueError:print("输入错误,请重试。")

实现效果

  • 随机任务要求收集资源或达到人口目标。
  • 完成任务获得资源奖励,增加策略性。

2. 技术优化

  • Pygame 界面:可视化殖民地布局和资源状态。
  • 存档加密:防止修改存档文件。
  • 动态数据:从外部文件加载行星数据。

示例代码:Pygame 界面

import pygameclass StarForgeGameWithGUI(StarForgeGame):def __init__(self):super().__init__()pygame.init()self.screen = pygame.display.set_mode((800, 600))pygame.display.set_caption("StarForge Colony")self.font = pygame.font.Font(None, 36)self.building_positions = {"Habitat": (100, 300),"Mine": (200, 300),"Solar Plant": (300, 300),"Hydroponics": (400, 300),"Research Lab": (500, 300),"Recreation Center": (600, 300)}def display_state(self):"""使用 Pygame 显示状态"""self.screen.fill((255, 255, 255))# 绘制建筑for name, building in self.colony.buildings.items():pos = self.building_positions[name]color = (0, 255, 0) if building.active else (255, 0, 0) if building.unlocked else (100, 100, 100)pygame.draw.circle(self.screen, color, pos, 20)text = self.font.render(name, True, (0, 0, 0))self.screen.blit(text, (pos[0] - 30, pos[1] + 30))# 显示状态texts = [f"Day: {self.turn + 1}",f"Population: {self.colony.population}/{self.colony.storage_capacity}",f"Happiness: {self.colony.happiness}",f"Labor: {self.colony.labor}",f"Minerals: {self.colony.resources['Minerals'].amount}",f"Energy: {self.colony.resources['Energy'].amount}",f"Water: {self.colony.resources['Water'].amount}"]for i, text in enumerate(texts):rendered = self.font.render(text, True, (0, 0, 0))self.screen.blit(rendered, (10, 10 + i * 30))pygame.display.flip()super().display_state()def run(self):print("欢迎来到《StarForge Colony》!")running = Truewhile running and not self.game_over:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseself.display_state()self.random_event()action = self.get_action()if action == "build":self.build()elif action == "research":self.research()elif action == "allocate_labor":self.allocate_labor()elif action == "complete_task":self.complete_task()elif action == "save_game":self.save_game()elif action == "load_game":self.load_game()elif action == "end_turn":self.end_turn()if self.check_win():print("恭喜!你建立了繁荣的殖民地!")self.game_over = Trueif self.check_lose():print("游戏结束。未能在 50 天内达成目标,或人口不足。")self.game_over = Truetime.sleep(1)pygame.quit()

实现效果

  • 显示殖民地建筑状态(绿色为启用,红色为停用,灰色为未解锁)。
  • CLI 交互保留,状态在屏幕顶部显示。

3. 教育模块

  • 行星科学:介绍行星环境(如大气、辐射)。
  • 生态管理:展示资源循环利用的重要性。
  • 科技发展:讲述殖民科技的现实背景。

示例代码:行星科学

class Building:def __init__(self, name, cost, maintenance, function, capacity=0, info=""):self.name = nameself.cost = costself.maintenance = maintenanceself.function = functionself.capacity = capacityself.unlocked = Falseself.active = Falseself.info = info  # 科学背景class Colony:def create_buildings(self):return {"Habitat": Building("Habitat", {"Minerals": 50}, {"Energy": 2, "Water": 1}, "Population", 20, "提供密封居住空间,抵御行星恶劣环境。"),"Mine": Building("Mine", {"Minerals": 30, "Energy": 20}, {"Energy": 1}, "Minerals", 10,"开采行星地壳中的金属和矿物资源。"),"Solar Plant": Building("Solar Plant", {"Minerals": 40}, {"Minerals": 1}, "Energy", 10,"利用行星表面太阳能发电,效率因距离恒星而异。"),"Hydroponics": Building("Hydroponics", {"Minerals": 30, "Water": 20}, {"Energy": 1}, "Water", 10,"水培农业技术,适应低重力环境生产水和食物。"),"Research Lab": Building("Research Lab", {"Minerals": 50, "Energy": 30}, {"Energy": 2}, "Research", 0,"研究外星环境和先进技术,推动殖民地发展。"),"Recreation Center": Building("Recreation Center", {"Minerals": 40, "Water": 10}, {"Energy": 1}, "Happiness", 10,"提供娱乐设施,缓解殖民者的心理压力。")}def build(self, building_name):building = self.buildings.get(building_name)if not building or not building.unlocked:print(f"{building_name} 未解锁或无效!")return Falseif building.active:print(f"{building_name} 已建成!")return Falseif all(self.resources[r].amount >= c for r, c in building.cost.items()) and self.labor >= 2:for r, c in building.cost.items():self.resources[r].amount -= cself.labor -= 2building.active = Trueif building.function == "Population":self.storage_capacity += building.capacityelif building.function in ["Minerals", "Energy", "Water"]:self.resources[building.function].production_rate += building.capacityelif building.function == "Happiness":self.happiness += building.capacityprint(f"成功建造 {building_name},消耗劳动力 2\n{building.info}")return Trueprint("资源或劳动力不足!")return False

实现效果

  • 建造建筑时显示科学背景,增强教育性。

游戏策略与玩法分析

1. 玩家策略

  • 资源分配:优先建造生产建筑,保障资源供应。
  • 科技研发:尽早解锁 Research Lab,加速科技进展。
  • 劳动力分配:平衡资源生产和建造需求。
  • 幸福度管理:优先建设 Recreation Center,避免人口流失。

2. 平衡性

  • 初始资源:100 单位资源,适合初期建设。
  • 建筑成本:高成本建筑(如 Research Lab)需规划资源。
  • 随机事件:陨石雨等事件增加挑战。
  • 回合限制:50 天需高效规划。

3. 重玩价值

  • 尝试不同建筑和科技解锁顺序。
  • 应对随机事件,优化资源管理。
  • 学习行星科学知识。

附录:完整代码

以下是整合后的完整代码,分为 game.pymain.py,可直接运行。

game.py

import random
import time
import jsonclass Resource:def __init__(self, name, amount=0, production_rate=0):self.name = nameself.amount = amountself.production_rate = production_rateclass Building:def __init__(self, name, cost, maintenance, function, capacity=0, info=""):self.name = nameself.cost = costself.maintenance = maintenanceself.function = functionself.capacity = capacityself.unlocked = Falseself.active = Falseself.info = infoclass Technology:def __init__(self, name, cost, unlocks):self.name = nameself.cost = costself.unlocks = unlocksself.researched = Falseclass Colony:def __init__(self):self.population = 10self.happiness = 50self.resources = {"Minerals": Resource("Minerals", 100, 5),"Energy": Resource("Energy", 100, 5),"Water": Resource("Water", 100, 5)}self.buildings = self.create_buildings()self.buildings["Habitat"].unlocked = Trueself.buildings["Habitat"].active = Trueself.technologies = self.create_technologies()self.labor = 5self.storage_capacity = 200self.tasks = []def create_buildings(self):return {"Habitat": Building("Habitat", {"Minerals": 50}, {"Energy": 2, "Water": 1}, "Population", 20,"提供密封居住空间,抵御行星恶劣环境。"),"Mine": Building("Mine", {"Minerals": 30, "Energy": 20}, {"Energy": 1}, "Minerals", 10,"开采行星地壳中的金属和矿物资源。"),"Solar Plant": Building("Solar Plant", {"Minerals": 40}, {"Minerals": 1}, "Energy", 10,"利用行星表面太阳能发电,效率因距离恒星而异。"),"Hydroponics": Building("Hydroponics", {"Minerals": 30, "Water": 20}, {"Energy": 1}, "Water", 10,"水培农业技术,适应低重力环境生产水和食物。"),"Research Lab": Building("Research Lab", {"Minerals": 50, "Energy": 30}, {"Energy": 2}, "Research", 0,"研究外星环境和先进技术,推动殖民地发展。"),"Recreation Center": Building("Recreation Center", {"Minerals": 40, "Water": 10}, {"Energy": 1}, "Happiness", 10,"提供娱乐设施,缓解殖民者的心理压力。")}def create_technologies(self):return [Technology("Advanced Mining", {"Minerals": 50, "Energy": 20}, {"Mine": {"production_rate": 5}}),Technology("Solar Efficiency", {"Minerals": 40, "Energy": 30}, {"Solar Plant": {"production_rate": 5}}),Technology("Hydroponics Optimization", {"Minerals": 30, "Water": 20}, {"Hydroponics": {"production_rate": 5}}),Technology("Advanced Habitats", {"Minerals": 60, "Energy": 40}, {"Habitat": {"capacity": 10}}),Technology("Recreation Systems", {"Minerals": 50, "Water": 30}, {"Recreation Center": {"capacity": 5}})]def build(self, building_name):building = self.buildings.get(building_name)if not building or not building.unlocked:print(f"{building_name} 未解锁或无效!")return Falseif building.active:print(f"{building_name} 已建成!")return Falseif all(self.resources[r].amount >= c for r, c in building.cost.items()) and self.labor >= 2:for r, c in building.cost.items():self.resources[r].amount -= cself.labor -= 2building.active = Trueif building.function == "Population":self.storage_capacity += building.capacityelif building.function in ["Minerals", "Energy", "Water"]:self.resources[building.function].production_rate += building.capacityelif building.function == "Happiness":self.happiness += building.capacityprint(f"成功建造 {building_name},消耗劳动力 2\n{building.info}")return Trueprint("资源或劳动力不足!")return Falsedef research(self, tech_name):tech = next((t for t in self.technologies if t.name == tech_name and not t.researched), None)if not tech:print("科技无效或已研发!")return Falseif all(self.resources[r].amount >= c for r, c in tech.cost.items()) and self.buildings["Research Lab"].active:for r, c in tech.cost.items():self.resources[r].amount -= ctech.researched = Truefor building_name, effect in tech.unlocks.items():building = self.buildings[building_name]building.unlocked = Truefor attr, value in effect.items():if attr == "production_rate":self.resources[building.function].production_rate += valueelif attr == "capacity":building.capacity += valueif building.function == "Population" and building.active:self.storage_capacity += valueelif building.function == "Happiness" and building.active:self.happiness += valueprint(f"成功研发 {tech_name},解锁或升级 {list(tech.unlocks.keys())}")return Trueprint("资源不足或需要研究实验室!")return Falsedef maintain(self):for building in self.buildings.values():if building.active:for r, c in building.maintenance.items():self.resources[r].amount -= cif self.resources[r].amount < 0:building.active = Falseprint(f"{building.name} 因 {r} 不足已停用!")if building.function == "Population":self.storage_capacity -= building.capacityelif building.function in ["Minerals", "Energy", "Water"]:self.resources[building.function].production_rate -= building.capacityelif building.function == "Happiness":self.happiness -= building.capacitydef produce(self):for resource in self.resources.values():resource.amount += resource.production_rateif resource.amount > self.storage_capacity:resource.amount = self.storage_capacityprint(f"{resource.name} 超出存储容量,已限制为 {self.storage_capacity}")if self.storage_capacity > self.population and self.happiness > 50:self.population += random.randint(1, 3)elif self.happiness < 30:self.population -= random.randint(1, 2)if self.population > self.storage_capacity:self.population = self.storage_capacityprint("人口超出住宅容量!")self.happiness = max(0, min(100, self.happiness + random.randint(-5, 5)))self.labor = self.population // 2def generate_task(self, turn):if random.random() < 0.5:task_id = len(self.tasks) + 1target = random.choice(["Minerals", "Energy", "Water", "Population"])target_amount = random.randint(50, 100) if target != "Population" else random.randint(20, 50)reward_resources = {r: 20 for r in self.resources}task = Task(task_id, target, target_amount, reward_resources)task.created_turn = turnself.tasks.append(task)print(f"任务 ID {task_id}: 收集 {target_amount} {target},奖励 {reward_resources}")def complete_task(self, task_id):task = next((t for t in self.tasks if t.id == task_id), None)if not task:print("无效任务 ID!")returnif task.target == "Population":if self.population >= task.target_amount:for r, amount in task.reward_resources.items():self.resources[r].amount += amountself.tasks.remove(task)print(f"任务 ID {task_id} 完成!获得 {task.reward_resources}")else:print(f"人口不足({self.population}/{task.target_amount})")else:if self.resources[task.target].amount >= task.target_amount:for r, amount in task.reward_resources.items():self.resources[r].amount += amountself.tasks.remove(task)print(f"任务 ID {task_id} 完成!获得 {task.reward_resources}")else:print(f"{task.target} 不足({self.resources[task.target].amount}/{task.target_amount})")class Task:def __init__(self, id, target, target_amount, reward_resources):self.id = idself.target = targetself.target_amount = target_amountself.reward_resources = reward_resourcesself.created_turn = 0class StarForgeGame:def __init__(self):self.colony = Colony()self.turn = 0self.max_turns = 50self.game_over = Falsedef run(self):print("欢迎来到《StarForge Colony》!目标:在 50 天内建立繁荣殖民地(100 人口,幸福度 > 80,解锁所有科技)。")while not self.game_over:self.display_state()self.colony.generate_task(self.turn)self.random_event()action = self.get_action()if action == "build":self.build()elif action == "research":self.research()elif action == "allocate_labor":self.allocate_labor()elif action == "complete_task":self.complete_task()elif action == "save_game":self.save_game()elif action == "load_game":self.load_game()elif action == "end_turn":self.end_turn()if self.check_win():print("恭喜!你建立了繁荣的殖民地!")self.game_over = Trueif self.check_lose():print("游戏结束。未能在 50 天内达成目标,或人口不足。")self.game_over = Truetime.sleep(1)def display_state(self):print(f"\n天数 {self.turn + 1}")print(f"人口: {self.colony.population} (容量 {self.colony.storage_capacity})")print(f"幸福度: {self.colony.happiness}")print(f"劳动力: {self.colony.labor}")print("资源:", {r: f"{v.amount} (生产 {v.production_rate}/回合)" for r, v in self.colony.resources.items()})print("建筑:", [f"{k} ({'启用' if v.active else '停用' if v.unlocked else '未解锁'})" for k, v in self.colony.buildings.items()])print("科技:", [f"{t.name} ({'已研发' if t.researched else '未研发'})" for t in self.colony.technologies])if self.colony.tasks:print("任务:", [f"ID {t.id}: 收集 {t.target_amount} {t.target}" for t in self.colony.tasks])def get_action(self):print("\n你想做什么?")print("1. 建造建筑")print("2. 研发科技")print("3. 分配劳动力")print("4. 完成任务")print("5. 保存游戏")print("6. 加载游戏")print("7. 结束天数")choice = input("输入选项 (1-7): ")actions = {"1": "build","2": "research","3": "allocate_labor","4": "complete_task","5": "save_game","6": "load_game","7": "end_turn"}return actions.get(choice, self.get_action())def build(self):print("可建造建筑:")for name, building in self.colony.buildings.items():if building.unlocked and not building.active:print(f"{name}: 成本 {building.cost}, 维护 {building.maintenance}")building_name = input("输入建筑名称:")self.colony.build(building_name)def research(self):print("可研发科技:")for tech in self.colony.technologies:if not tech.researched:print(f"{tech.name}: 成本 {tech.cost}")tech_name = input("输入科技名称:")self.colony.research(tech_name)def allocate_labor(self):print(f"当前劳动力: {self.colony.labor}")print("可分配建筑:")for name, building in self.colony.buildings.items():if building.active and building.function in ["Minerals", "Energy", "Water"]:print(f"{name}: 当前生产 {self.colony.resources[building.function].production_rate}")building_name = input("输入建筑名称(或按 Enter 跳过):")if building_name and building_name in self.colony.buildings and self.colony.buildings[building_name].active:if self.colony.labor >= 1:self.colony.labor -= 1self.colony.resources[self.colony.buildings[building_name].function].production_rate += 2print(f"分配 1 劳动力到 {building_name},增加 2 {self.colony.buildings[building_name].function} 生产")else:print("劳动力不足!")else:print("无效建筑或已跳过!")def complete_task(self):if not self.colony.tasks:print("没有可用任务!")returnprint("可用任务:")for task in self.colony.tasks:print(f"ID {task.id}: 收集 {task.target_amount} {task.target}")try:task_id = int(input("输入任务 ID: "))self.colony.complete_task(task_id)except ValueError:print("输入错误,请重试。")def random_event(self):event = random.choice(["None", "Meteor Shower", "Radiation Storm", "Equipment Failure"])if event == "Meteor Shower":damage = random.randint(5, 15)self.colony.resources["Minerals"].amount -= damageprint(f"陨石雨,损失 {damage} 矿物!")elif event == "Radiation Storm":self.colony.happiness -= 10print("辐射风暴,幸福度下降 10!")elif event == "Equipment Failure":for building in self.colony.buildings.values():if building.active and random.random() < 0.3:building.active = Falseprint(f"{building.name} 因设备故障停用!")if building.function == "Population":self.colony.storage_capacity -= building.capacityelif building.function in ["Minerals", "Energy", "Water"]:self.colony.resources[building.function].production_rate -= building.capacityelif building.function == "Happiness":self.colony.happiness -= building.capacitydef save_game(self):state = {"turn": self.turn,"colony": {"population": self.colony.population,"happiness": self.colony.happiness,"labor": self.colony.labor,"storage_capacity": self.colony.storage_capacity,"resources": {r: {"amount": v.amount, "production_rate": v.production_rate} for r, v in self.colony.resources.items()},"buildings": {k: {"unlocked": v.unlocked, "active": v.active} for k, v in self.colony.buildings.items()},"technologies": [{"name": t.name, "researched": t.researched} for t in self.colony.technologies],"tasks": [{"id": t.id, "target": t.target, "target_amount": t.target_amount, "reward_resources": t.reward_resources, "created_turn": t.created_turn} for t in self.colony.tasks]}with open("savegame.json", "w") as f:json.dump(state, f)print("游戏已保存!")def load_game(self):try:with open("savegame.json", "r") as f:state = json.load(f)self.turn = state["turn"]self.colony.population = state["colony"]["population"]self.colony.happiness = state["colony"]["happiness"]self.colony.labor = state["colony"]["labor"]self.colony.storage_capacity = state["colony"]["storage_capacity"]for r, data in state["colony"]["resources"].items():self.colony.resources[r].amount = data["amount"]self.colony.resources[r].production_rate = data["production_rate"]for name, data in state["colony"]["buildings"].items():self.colony.buildings[name].unlocked = data["unlocked"]self.colony.buildings[name].active = data["active"]for tech_data in state["colony"]["technologies"]:tech = next(t for t in self.colony.technologies if t.name == tech_data["name"])tech.researched = tech_data["researched"]self.colony.tasks = [Task(t["id"], t["target"], t["target_amount"], t["reward_resources"]) for t in state["colony"]["tasks"]]for t in self.colony.tasks:t.created_turn = state["colony"]["tasks"][self.colony.tasks.index(t)]["created_turn"]print("游戏已加载!")except FileNotFoundError:print("没有找到存档文件!")def end_turn(self):self.turn += 1self.colony.maintain()self.colony.produce()for task in self.colony.tasks[:]:if self.turn - task.created_turn >= 5:print(f"任务 ID {task.id} 过期!")self.colony.tasks.remove(task)def check_win(self):return (self.colony.population >= 100 and self.colony.happiness > 80 and all(t.researched for t in self.colony.technologies))def check_lose(self):return self.turn > self.max_turns or self.colony.population <= 0

main.py

from game import StarForgeGameif __name__ == "__main__":game = StarForgeGame()game.run()