结合上述提供完整代码import numpy as np
import pandas as pd
from tabulate import tabulate
import random
import math
from collections import deque, defaultdict
import heapq
import networkx as nx
from concurrent.futures import ThreadPoolExecutor, as_completed
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from tqdm import tqdm
import time
# 配置参数
max_weight = 1200 # kg
initial_money = 10000 # 元
# 资源参数
per_water_weight = 3 # kg/箱
water_price = 5 # 元/箱
water_sunny = 3 # 箱/天
water_hot = 9
water_sandstorm = 10
per_food_weight = 2 # kg/箱
food_price = 10 # 元/箱
food_sunny = 4
food_hot = 9
food_sandstorm = 10
# 天气类型和消耗量
WEATHER_TYPES = ['晴朗', '高温', '沙暴']
WEATHER_PROBS = [0.3, 0.5, 0.2]
WEATHER_CONSUMPTION = {
'晴朗': {'water': water_sunny, 'food': food_sunny},
'高温': {'water': water_hot, 'food': food_hot},
'沙暴': {'water': water_sandstorm, 'food': food_sandstorm}
}
# 地图参数
rows = 5 # 行数
cols = 5 # 列数
total_regions = rows * cols # 总区域数
# 创建邻接矩阵
adj_matrix = [[0 for _ in range(total_regions + 1)] for _ in range(total_regions + 1)]
# 创建连接关系
for region in range(1, total_regions + 1):
# 计算当前区域的行和列
row = (region - 1) // cols + 1
col = (region - 1) % cols + 1
# 检查上方邻居
if row > 1:
neighbor = region - cols
adj_matrix[region][neighbor] = 1
adj_matrix[neighbor][region] = 1
# 检查下方邻居
if row < rows:
neighbor = region + cols
adj_matrix[region][neighbor] = 1
adj_matrix[neighbor][region] = 1
# 检查左侧邻居
if col > 1:
neighbor = region - 1
adj_matrix[region][neighbor] = 1
adj_matrix[neighbor][region] = 1
# 检查右侧邻居
if col < cols:
neighbor = region + 1
adj_matrix[region][neighbor] = 1
adj_matrix[neighbor][region] = 1
# 节点类型定义
NODE_TYPES = {
'NORMAL': 0,
'START': 1, # 起点
'MINE': 2, # 矿山
'VILLAGE': 3, # 村庄
'END': 4 # 终点
}
# 节点类型初始化
node_types = [NODE_TYPES['NORMAL']] * (total_regions + 1)
# 设置特殊节点
node_types[1] = NODE_TYPES['START']
node_types[18] = NODE_TYPES['MINE']
node_types[14] = NODE_TYPES['VILLAGE']
node_types[25] = NODE_TYPES['END']
# 场景生成参数
SCENARIO_COUNT = 50 # 场景数量
MAX_DAYS = 30 # 最大天数
def get_node_type_name(node_type):
"""根据节点类型值获取名称"""
for name, value in NODE_TYPES.items():
if value == node_type:
return name
return "UNKNOWN"
# 创建NetworkX图
G = nx.Graph()
# 添加边
for u in range(1, total_regions + 1):
for v in range(u + 1, total_regions + 1):
if adj_matrix[u][v] == 1:
G.add_edge(u, v)
# 设置节点颜色
node_colors = []
node_sizes = []
for node in G.nodes():
node_type = node_types[node]
if node_type == NODE_TYPES['START']:
node_colors.append('limegreen')
node_sizes.append(800)
elif node_type == NODE_TYPES['MINE']:
node_colors.append('gold')
node_sizes.append(800)
elif node_type == NODE_TYPES['VILLAGE']:
node_colors.append('lightcoral')
node_sizes.append(700)
elif node_type == NODE_TYPES['END']:
node_colors.append('darkorange')
node_sizes.append(800)
else:
node_colors.append('skyblue')
node_sizes.append(500)
# 创建图例
legend_elements = [
Patch(facecolor='limegreen', edgecolor='black', label='起点'),
Patch(facecolor='gold', edgecolor='black', label='矿山'),
Patch(facecolor='lightcoral', edgecolor='black', label='村庄'),
Patch(facecolor='darkorange', edgecolor='black', label='终点'),
Patch(facecolor='skyblue', edgecolor='black', label='普通区域'),
plt.Line2D([0], [0], color='gray', lw=2, label='可通行路径')
]
def generate_weather_scenarios(days, count):
"""生成指定天数和数量的天气场景"""
scenarios = []
for _ in range(count):
scenario = random.choices(WEATHER_TYPES, weights=WEATHER_PROBS, k=days)
scenarios.append(scenario)
return scenarios
def heuristic(current, end, remaining_days, money, distance_cache=None):
"""启发函数,估计从当前状态到终点的潜在收益"""
if distance_cache is None:
distance_cache = {}
# 使用缓存计算最短路径
if (current, end) in distance_cache:
distance = distance_cache[(current, end)]
else:
try:
distance = nx.shortest_path_length(G, current, end)
distance_cache[(current, end)] = distance
except:
distance = float('inf')
# 如果无法到达终点,只考虑当前金钱
if distance == float('inf'):
return money
# 否则,考虑剩余天数和可能的采矿收益
potential_mines = max(0, remaining_days - distance) // 2
return money + potential_mines * 1000
def solve_deterministic_model(G, weather_sequence, start=1, end=25, best_money_cache=None):
"""使用A*算法求解确定性模型,返回最优路径和收益"""
# 如果有全局缓存,使用它
if best_money_cache is not None and (start, end) in best_money_cache:
best_result, best_money = best_money_cache[(start, end)]
if best_money > 0:
return best_result
# 使用优先队列实现A*算法
queue = []
visited = set()
# 初始购买策略(在起点购买资源)
max_water = min(max_weight // per_water_weight, initial_money // water_price)
max_food = min(max_weight // per_food_weight, initial_money // food_price)
# 尝试不同的初始购买组合(增大步长)
for water in range(0, max_water + 1, 20): # 步长从10增加到20
for food in range(0, max_food + 1, 20): # 步长从10增加到20
cost = water * water_price + food * food_price
if cost > initial_money:
continue
if water * per_water_weight + food * per_food_weight > max_weight:
continue
money = initial_money - cost
state_key = (start, 0, water, food, money)
if state_key in visited:
continue
visited.add(state_key)
# 计算启发值
h = heuristic(start, end, len(weather_sequence), money)
# 优先级是( - 总收益估计, 实际金钱, 当前天数)
heapq.heappush(queue, (-h, 0, start, [start], water, food, money, []))
best_result = None
best_money = 0
# 添加优先级剪枝
best_h = float('-inf')
while queue:
h, priority, current, path, water, food, money, mining_days = heapq.heappop(queue)
current_h = -h # 恢复实际估计值
# 如果当前估计值比已知最优解还差,直接剪枝
if best_money > 0 and current_h < best_money * 0.8:
continue
# 提前剪枝:如果当前金钱加上最大可能收益仍小于已知最优解
if best_money_cache is not None and (start, end) in best_money_cache:
if money + (len(weather_sequence) - priority) * 1000 < best_money_cache[(start, end)][1]:
continue
# 如果到达终点
if current == end:
# 终点退回剩余资源
refund = water * water_price / 2 + food * food_price / 2
money += refund
if money > best_money:
best_money = money
best_result = (path, mining_days, money)
continue
# 如果超过最大天数
if priority >= len(weather_sequence):
continue
# 获取当前天气
weather = weather_sequence[priority]
# 计算基础消耗
water_consumption = WEATHER_CONSUMPTION[weather]['water']
food_consumption = WEATHER_CONSUMPTION[weather]['food']
# 尝试所有可能的行动
# 1. 在当前区域停留(仅在村庄或矿山有意义)
if node_types[current] == NODE_TYPES['VILLAGE'] or node_types[current] == NODE_TYPES['MINE']:
if water >= water_consumption and food >= food_consumption:
new_water = water - water_consumption
new_food = food - food_consumption
# 在村庄停留时可以购买资源
if node_types[current] == NODE_TYPES['VILLAGE']:
# 计算最大可购买量
max_water_buy = min((max_weight - (new_food * per_food_weight)) // per_water_weight,
money // water_price)
max_food_buy = min((max_weight - (new_water * per_water_weight)) // per_food_weight,
money // food_price)
# 尝试购买资源(增大步长)
for buy_water in range(0, max_water_buy + 1, 40): # 步长从20增加到40
for buy_food in range(0, max_food_buy + 1, 40): # 步长从20增加到40
cost = buy_water * water_price + buy_food * food_price
if money < cost:
continue
new_water2 = new_water + buy_water
new_food2 = new_food + buy_food
new_money = money - cost
# 检查负重
weight = new_water2 * per_water_weight + new_food2 * per_food_weight
if weight > max_weight:
continue
# 创建新状态
state_key = (current, priority+1, new_water2, new_food2, new_money)
if state_key not in visited:
visited.add(state_key)
# 计算启发值
remaining_days = len(weather_sequence) - (priority+1)
h = heuristic(current, end, remaining_days, new_money)
# 优先级是( - 总收益估计, 实际金钱, 当前天数)
heapq.heappush(
queue,
(-h, priority+1, current, path.copy(), new_water2, new_food2, new_money, mining_days.copy())
)
else:
# 矿山停留但不采矿
state_key = (current, priority+1, new_water, new_food, money)
if state_key not in visited:
visited.add(state_key)
# 计算启发值
remaining_days = len(weather_sequence) - (priority+1)
h = heuristic(current, end, remaining_days, money)
# 优先级是( - 总收益估计, 实际金钱, 当前天数)
heapq.heappush(
queue,
(-h, priority+1, current, path.copy(), new_water, new_food, new_money, mining_days.copy())
)
# 2. 移动到相邻区域
for neighbor in G.neighbors(current):
# 检查资源是否足够一天消耗
if water >= water_consumption and food >= food_consumption:
new_water = water - water_consumption
new_food = food - food_consumption
new_money = money
# 在村庄购买资源(到达时立即购买)
if node_types[neighbor] == NODE_TYPES['VILLAGE']:
# 计算最大可购买量
max_water_buy = min((max_weight - (new_food * per_food_weight)) // per_water_weight,
new_money // water_price)
max_food_buy = min((max_weight - (new_water * per_water_weight)) // per_food_weight,
new_money // food_price)
# 尝试购买资源(增大步长)
for buy_water in range(0, max_water_buy + 1, 40): # 步长从20增加到40
for buy_food in range(0, max_food_buy + 1, 40): # 步长从20增加到40
cost = buy_water * water_price + buy_food * food_price
if new_money < cost:
continue
new_water2 = new_water + buy_water
new_food2 = new_food + buy_food
new_money2 = new_money - cost
# 检查负重
weight = new_water2 * per_water_weight + new_food2 * per_food_weight
if weight > max_weight:
continue
# 创建新状态
state_key = (neighbor, priority+1, new_water2, new_food2, new_money2)
if state_key not in visited:
visited.add(state_key)
# 计算启发值
remaining_days = len(weather_sequence) - (priority+1)
h = heuristic(neighbor, end, remaining_days, new_money2)
# 优先级是( - 总收益估计, 实际金钱, 当前天数)
heapq.heappush(
queue,
(-h, priority+1, neighbor, path + [neighbor], new_water2, new_food2, new_money2, mining_days.copy())
)
else:
# 非村庄节点
state_key = (neighbor, priority+1, new_water, new_food, new_money)
if state_key not in visited:
visited.add(state_key)
# 计算启发值
remaining_days = len(weather_sequence) - (priority+1)
h = heuristic(neighbor, end, remaining_days, new_money)
# 优先级是( - 总收益估计, 实际金钱, 当前天数)
heapq.heappush(
queue,
(-h, priority+1, neighbor, path + [neighbor], new_water, new_food, new_money, mining_days.copy())
)
# 3. 在矿山采矿(如果当前在矿山)
if node_types[current] == NODE_TYPES['MINE'] and priority < len(weather_sequence) - 1:
# 采矿需要两天时间,消耗两天的资源
total_water = water_consumption * 2
total_food = food_consumption * 2
if water >= total_water and food >= total_food:
new_water = water - total_water
new_food = food - total_food
new_money = money + 1000 # 采矿收益
# 标记采矿天数
new_mining_days = mining_days.copy()
new_mining_days.append(priority + 1) # 记录第二天采矿
# 创建新状态
state_key = (current, priority+2, new_water, new_food, new_money)
if state_key not in visited:
visited.add(state_key)
# 计算启发值
remaining_days = len(weather_sequence) - (priority+2)
h = heuristic(current, end, remaining_days, new_money)
# 优先级是( - 总收益估计, 实际金钱, 当前天数)
heapq.heappush(
queue,
(-h, priority+2, current, path.copy(), new_water, new_food, new_money, new_mining_days)
)
# 更新全局缓存
if best_money_cache is not None:
best_money_cache[(start, end)] = (best_result, best_money)
return best_result if best_result else (None, None, 0)
# 场景评估函数
def evaluate_scenarios(G, scenarios, start=1, end=25):
"""评估所有场景,返回每个场景的最优解"""
scenario_results = []
distance_cache = {} # 缓存最短路径计算
best_money_cache = {} # 缓存最佳金钱结果
# 添加进度条
for i, scenario in enumerate(tqdm(scenarios, desc="处理场景")):
# 求解该场景的最优策略
path, mining_days, final_money = solve_deterministic_model(G, scenario, start, end, best_money_cache)
# 计算总行程天数
days = len(scenario)
# 计算路径长度
path_length = len(path) - 1 if path else float('inf')
# 记录结果 - 完整输出天气序列和路径
scenario_results.append({
'scenario_id': i+1,
'weather_sequence': '→'.join(scenario), # 完整天气序列
'path': '→'.join(map(str, path)) if path else '无路径', # 完整路径
'path_length': path_length,
'mining_days': '→'.join(map(str, mining_days)) if mining_days else '无采矿',
'total_days': days,
'final_money': final_money
})
return scenario_results
# 并行评估所有场景
def evaluate_scenarios_parallel(G, scenarios, start=1, end=25):
"""并行评估所有场景"""
scenario_results = []
with ThreadPoolExecutor(max_workers=8) as executor: # 增加线程数到8
futures = []
for i, scenario in enumerate(scenarios):
future = executor.submit(solve_deterministic_model, G, scenario, start, end)
futures.append((i, future))
for i, future in enumerate(tqdm(as_completed(futures), total=len(futures), desc="处理场景")):
result = future.result()
path, mining_days, final_money = result
# 计算总行程天数
days = len(scenarios[i])
# 计算路径长度
path_length = len(path) - 1 if path else float('inf')
# 记录结果
scenario_results.append({
'scenario_id': i+1,
'weather_sequence': '→'.join(scenarios[i]), # 完整天气序列
'path': '→'.join(map(str, path)) if path else '无路径', # 完整路径
'path_length': path_length,
'mining_days': '→'.join(map(str, mining_days)) if mining_days else '无采矿',
'total_days': days,
'final_money': final_money
})
return scenario_results
# 策略聚合函数
def aggregate_strategies(results):
"""聚合场景结果,生成不同策略"""
# 转换为DataFrame
df = pd.DataFrame(results)
# 过滤无效结果
valid_df = df[df['final_money'] > 0]
if len(valid_df) == 0:
return None
# 1. 期望最优策略(平均资金最高)
expected_optimal = valid_df.loc[valid_df['final_money'].idxmax()]
# 2. 最坏情况最优(最差场景中表现最好)
worst_case_optimal = valid_df.sort_values('final_money').iloc[0]
# 3. 鲁棒策略(最差20%场景中表现最好的)
robust_df = valid_df.sort_values('final_money').iloc[:max(1, len(valid_df)//5)]
robust_strategy = robust_df.sort_values('final_money').iloc[-1]
return {
'expected_optimal': expected_optimal,
'worst_case_optimal': worst_case_optimal,
'robust_strategy': robust_strategy}
# 结果展示函数
def display_results(results, strategies):
"""显示结果表格"""
# 转换为DataFrame
df = pd.DataFrame(results)
# 打印统计信息
print("\n=== 场景统计信息 ===")
valid_count = len(df[df['final_money'] > 0])
print(f"有效场景数: {valid_count}/{len(df)}")
if valid_count > 0:
valid_df = df[df['final_money'] > 0]
print(f"平均剩余资金: {valid_df['final_money'].mean():.2f} 元")
print(f"最低剩余资金: {valid_df['final_money'].min()} 元")
print(f"最高剩余资金: {valid_df['final_money'].max()} 元")
print(f"平均路径长度: {valid_df['path_length'].mean():.2f} 步")
# 打印策略对比
if strategies:
print("\n=== 策略对比 ===")
strategy_table = []
for strategy_name, row in strategies.items():
strategy_table.append([
strategy_name,
row['final_money'],
row['path'],
row['mining_days'],
row['total_days']
])
print(tabulate(strategy_table, headers=[
'策略类型', '剩余资金(元)', '路径', '采矿天数', '总天数'
], tablefmt='grid'))
# 保存为Excel
output_file = "5x5地图结果.xlsx"
df.to_excel(output_file, index=False)
print(f"\n所有场景结果已保存至 '{output_file}'")
def draw_map(layout, title, filename):
"""绘制地图"""
plt.figure(figsize=(14, 12))
# 选择布局
if layout == 'circular':
pos = nx.circular_layout(G)
elif layout == 'spring':
pos = nx.spring_layout(G, seed=42, k=0.3)
elif layout == 'grid':
# 自定义网格布局
pos = {}
for region in range(1, total_regions + 1):
row = (region - 1) // cols
col = (region - 1) % cols
pos[region] = np.array([col, -row])
else:
pos = nx.spring_layout(G, seed=42)
# 绘制图形
nx.draw_networkx_nodes(G, pos, node_color=node_colors, node_size=node_sizes, alpha=0.9)
nx.draw_networkx_edges(G, pos, edge_color='gray', width=1.5, alpha=0.7)
nx.draw_networkx_labels(G, pos, font_size=10, font_weight='bold')
# 添加图例和标题
plt.legend(handles=legend_elements, loc='upper right', fontsize=10,
bbox_to_anchor=(1.15, 1), framealpha=1)
plt.title(f"沙漠寻宝地图 - {title}", fontsize=16, pad=20)
plt.text(0.5, -0.1, "注:连线表示区域间可直接移动",
ha='center', transform=plt.gca().transAxes, fontsize=10)
# 显示和保存
plt.grid(False)
plt.axis('off')
plt.tight_layout()
plt.savefig(filename, dpi=300, bbox_inches='tight')
plt.show()
def main():
print("=== 5x5地图建模开始 ===")
# 创建图
G = nx.Graph()
# 添加边
for u in range(1, total_regions + 1):
for v in range(u + 1, total_regions + 1):
if adj_matrix[u][v] == 1:
G.add_edge(u, v)
# 生成天气场景
print(f"生成 {SCENARIO_COUNT} 个天气场景...")
scenarios = generate_weather_scenarios(MAX_DAYS, SCENARIO_COUNT)
# 评估所有场景
print("评估所有场景...")
scenario_results = evaluate_scenarios_parallel(G, scenarios) # 改用并行处理
# 聚合策略
print("聚合策略...")
strategies = aggregate_strategies(scenario_results)
# 显示结果
display_results(scenario_results, strategies)
# 绘制地图
print("绘制地图...")
draw_map('circular', '环形布局', 'desert_game_map_circular.png')
draw_map('spring', '力导向布局', 'desert_game_map_spring.png')
draw_map('grid', '网格布局', 'desert_game_map_grid.png')
print("\n=== 建模完成 ===")
if __name__ == "__main__":
main()
最新发布