技術準備
在開始編碼之前,我們需要準備開發環境和相關工具。以下是開發 StarForge Colony 所需的技術棧和資源。
1. 技術棧
- 編程語言:Python 3.x(推薦 3.8 或更高版本)。
- 核心庫:
random:生成隨機事件、資源分佈和環境挑戰。time:控制遊戲節奏和事件觸發。json:保存和加載殖民地狀態。pygame(可選):用於圖形界面和殖民地佈局可視化。
- 數據存儲:
- 使用字典存儲資源、建築和科技數據。
- 列表存儲任務、人口和事件狀態。
- 用户界面:基於命令行界面(CLI)顯示資源、建築和交互,圖形界面作為擴展。
- 依賴安裝:
random、time和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 random
class 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 = True
self.buildings["Habitat"].active = True
self.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 False
if building.active:
print(f"{building_name} 已建成!")
return False
if 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 -= c
self.labor -= 2
building.active = True
if building.function == "Population":
self.storage_capacity += building.capacity
elif building.function in ["Minerals", "Energy", "Water"]:
self.resources[building.function].production_rate += building.capacity
elif building.function == "Happiness":
self.happiness += building.capacity
print(f"成功建造 {building_name},消耗勞動力 2")
return True
print("資源或勞動力不足!")
return False
def 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 False
if 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 -= c
tech.researched = True
for building_name, effect in tech.unlocks.items():
building = self.buildings[building_name]
building.unlocked = True
for attr, value in effect.items():
if attr == "production_rate":
self.resources[building.function].production_rate += value
elif attr == "capacity":
building.capacity += value
if building.function == "Population" and building.active:
self.storage_capacity += value
elif building.function == "Happiness" and building.active:
self.happiness += value
print(f"成功研發 {tech_name},解鎖或升級 {list(tech.unlocks.keys())}")
return True
print("資源不足或需要研究實驗室!")
return False
def maintain(self):
"""維護建築並更新資源"""
for building in self.buildings.values():
if building.active:
for r, c in building.maintenance.items():
self.resources[r].amount -= c
if self.resources[r].amount < 0:
building.active = False
print(f"{building.name} 因 {r} 不足已停用!")
if building.function == "Population":
self.storage_capacity -= building.capacity
elif building.function in ["Minerals", "Energy", "Water"]:
self.resources[building.function].production_rate -= building.capacity
elif building.function == "Happiness":
self.happiness -= building.capacity
def produce(self):
"""生產資源並更新人口"""
for resource in self.resources.values():
resource.amount += resource.production_rate
if resource.amount > self.storage_capacity:
resource.amount = self.storage_capacity
print(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_capacity
print("人口超出住宅容量!")
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 json
class StarForgeGame:
def __init__(self):
"""初始化遊戲"""
self.colony = Colony()
self.turn = 0
self.max_turns = 50
self.game_over = False
def 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 = True
if self.check_lose():
print("遊戲結束。未能在 50 天內達成目標,或人口不足。")
self.game_over = True
time.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 -= 1
self.colony.resources[self.colony.buildings[building_name].function].production_rate += 2
print(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 -= damage
print(f"隕石雨,損失 {damage} 礦物!")
elif event == "Radiation Storm":
self.colony.happiness -= 10
print("輻射風暴,幸福度下降 10!")
elif event == "Equipment Failure":
for building in self.colony.buildings.values():
if building.active and random.random() < 0.3:
building.active = False
print(f"{building.name} 因設備故障停用!")
if building.function == "Population":
self.colony.storage_capacity -= building.capacity
elif building.function in ["Minerals", "Energy", "Water"]:
self.colony.resources[building.function].production_rate -= building.capacity
elif building.function == "Happiness":
self.colony.happiness -= building.capacity
def 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 += 1
self.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 StarForgeGame
if __name__ == "__main__":
game = StarForgeGame()
game.run()
運行遊戲
1. 啓動遊戲
在項目目錄下運行:
python main.py
2. 遊戲流程
- 初始化:
- 玩家從 10 人口、50 幸福度、100 單位資源(礦物、能源、水)開始,初始解鎖“Habitat”建築。
- 每回合行動:
- 顯示狀態:查看人口、幸福度、資源、建築和科技。
- 建造建築:消耗資源和勞動力建造建築。
- 研發科技:解鎖新建築或提升效率。
- 分配勞動力:增加資源生產效率。
- 保存/加載:保存進度或恢復遊戲。
- 結束天數:維護建築、生產資源、觸發隨機事件。
- 遊戲結束:
- 人口 ≥ 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 = id
self.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) + 1
target = 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 = turn
self.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!")
return
if task.target == "Population":
if self.population >= task.target_amount:
for r, amount in task.reward_resources.items():
self.resources[r].amount += amount
self.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 += amount
self.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 = True
if self.check_lose():
print("遊戲結束。未能在 50 天內達成目標,或人口不足。")
self.game_over = True
time.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("沒有可用任務!")
return
print("可用任務:")
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 pygame
class 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 = True
while running and not self.game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
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 == "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 = True
if self.check_lose():
print("遊戲結束。未能在 50 天內達成目標,或人口不足。")
self.game_over = True
time.sleep(1)
pygame.quit()
實現效果:
- 顯示殖民地建築狀態(綠色為啓用,紅色為停用,灰色為未解鎖)。
- CLI 交互保留,狀態在屏幕頂部顯示。
3. 教育模塊
- 行星科學:介紹行星環境(如大氣、輻射)。
- 生態管理:展示資源循環利用的重要性。
- 科技發展:講述殖民科技的現實背景。
示例代碼:行星科學
class Building:
def __init__(self, name, cost, maintenance, function, capacity=0, info=""):
self.name = name
self.cost = cost
self.maintenance = maintenance
self.function = function
self.capacity = capacity
self.unlocked = False
self.active = False
self.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 False
if building.active:
print(f"{building_name} 已建成!")
return False
if 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 -= c
self.labor -= 2
building.active = True
if building.function == "Population":
self.storage_capacity += building.capacity
elif building.function in ["Minerals", "Energy", "Water"]:
self.resources[building.function].production_rate += building.capacity
elif building.function == "Happiness":
self.happiness += building.capacity
print(f"成功建造 {building_name},消耗勞動力 2\n{building.info}")
return True
print("資源或勞動力不足!")
return False
實現效果:
- 建造建築時顯示科學背景,增強教育性。
遊戲策略與玩法分析
1. 玩家策略
- 資源分配:優先建造生產建築,保障資源供應。
- 科技研發:儘早解鎖 Research Lab,加速科技進展。
- 勞動力分配:平衡資源生產和建造需求。
- 幸福度管理:優先建設 Recreation Center,避免人口流失。
2. 平衡性
- 初始資源:100 單位資源,適合初期建設。
- 建築成本:高成本建築(如 Research Lab)需規劃資源。
- 隨機事件:隕石雨等事件增加挑戰。
- 回合限制:50 天需高效規劃。
3. 重玩價值
- 嘗試不同建築和科技解鎖順序。
- 應對隨機事件,優化資源管理。
- 學習行星科學知識。
附錄:完整代碼
以下是整合後的完整代碼,分為 game.py 和 main.py,可直接運行。
game.py
import random
import time
import json
class Resource:
def __init__(self, name, amount=0, production_rate=0):
self.name = name
self.amount = amount
self.production_rate = production_rate
class Building:
def __init__(self, name, cost, maintenance, function, capacity=0, info=""):
self.name = name
self.cost = cost
self.maintenance = maintenance
self.function = function
self.capacity = capacity
self.unlocked = False
self.active = False
self.info = info
class Technology:
def __init__(self, name, cost, unlocks):
self.name = name
self.cost = cost
self.unlocks = unlocks
self.researched = False
class 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 = True
self.buildings["Habitat"].active = True
self.technologies = self.create_technologies()
self.labor = 5
self.storage_capacity = 200
self.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 False
if building.active:
print(f"{building_name} 已建成!")
return False
if 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 -= c
self.labor -= 2
building.active = True
if building.function == "Population":
self.storage_capacity += building.capacity
elif building.function in ["Minerals", "Energy", "Water"]:
self.resources[building.function].production_rate += building.capacity
elif building.function == "Happiness":
self.happiness += building.capacity
print(f"成功建造 {building_name},消耗勞動力 2\n{building.info}")
return True
print("資源或勞動力不足!")
return False
def 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 False
if 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 -= c
tech.researched = True
for building_name, effect in tech.unlocks.items():
building = self.buildings[building_name]
building.unlocked = True
for attr, value in effect.items():
if attr == "production_rate":
self.resources[building.function].production_rate += value
elif attr == "capacity":
building.capacity += value
if building.function == "Population" and building.active:
self.storage_capacity += value
elif building.function == "Happiness" and building.active:
self.happiness += value
print(f"成功研發 {tech_name},解鎖或升級 {list(tech.unlocks.keys())}")
return True
print("資源不足或需要研究實驗室!")
return False
def maintain(self):
for building in self.buildings.values():
if building.active:
for r, c in building.maintenance.items():
self.resources[r].amount -= c
if self.resources[r].amount < 0:
building.active = False
print(f"{building.name} 因 {r} 不足已停用!")
if building.function == "Population":
self.storage_capacity -= building.capacity
elif building.function in ["Minerals", "Energy", "Water"]:
self.resources[building.function].production_rate -= building.capacity
elif building.function == "Happiness":
self.happiness -= building.capacity
def produce(self):
for resource in self.resources.values():
resource.amount += resource.production_rate
if resource.amount > self.storage_capacity:
resource.amount = self.storage_capacity
print(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_capacity
print("人口超出住宅容量!")
self.happiness = max(0, min(100, self.happiness + random.randint(-5, 5)))
self.labor = self.population // 2
def generate_task(self, turn):
if random.random() < 0.5:
task_id = len(self.tasks) + 1
target = 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 = turn
self.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!")
return
if task.target == "Population":
if self.population >= task.target_amount:
for r, amount in task.reward_resources.items():
self.resources[r].amount += amount
self.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 += amount
self.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 = id
self.target = target
self.target_amount = target_amount
self.reward_resources = reward_resources
self.created_turn = 0
class StarForgeGame:
def __init__(self):
self.colony = Colony()
self.turn = 0
self.max_turns = 50
self.game_over = False
def 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 = True
if self.check_lose():
print("遊戲結束。未能在 50 天內達成目標,或人口不足。")
self.game_over = True
time.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 -= 1
self.colony.resources[self.colony.buildings[building_name].function].production_rate += 2
print(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("沒有可用任務!")
return
print("可用任務:")
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 -= damage
print(f"隕石雨,損失 {damage} 礦物!")
elif event == "Radiation Storm":
self.colony.happiness -= 10
print("輻射風暴,幸福度下降 10!")
elif event == "Equipment Failure":
for building in self.colony.buildings.values():
if building.active and random.random() < 0.3:
building.active = False
print(f"{building.name} 因設備故障停用!")
if building.function == "Population":
self.colony.storage_capacity -= building.capacity
elif building.function in ["Minerals", "Energy", "Water"]:
self.colony.resources[building.function].production_rate -= building.capacity
elif building.function == "Happiness":
self.colony.happiness -= building.capacity
def 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 += 1
self.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 StarForgeGame
if __name__ == "__main__":
game = StarForgeGame()
game.run()