-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinitializer.py
More file actions
508 lines (428 loc) · 17.3 KB
/
initializer.py
File metadata and controls
508 lines (428 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
# ============================================
# 生物进化模拟器 - 世界初始化
# ============================================
import random
import math
from typing import List, Tuple, Set
from species import Species, SpeciesType, Lifestyle
from ecology import EcologyCalculator
from species_templates import SpeciesFitter, fit_plant, fit_herbivore, fit_carnivore, fit_omnivore
import config as cfg
class WorldInitializer:
"""世界初始化器"""
def __init__(self, seed: int = None):
if seed is not None:
random.seed(seed)
self.next_species_id = 0
self.used_names: Set[str] = set()
self.fitter = SpeciesFitter()
def _get_fitted_name(self, species_attrs: dict, category: str, is_social: bool) -> Tuple[str, str]:
"""
使用拟合算法生成物种名称
返回: (生成的名称, 原型名称)
"""
result = self.fitter.fit_species(species_attrs, category, is_social, use_flavor=True)
generated_name = result['generated_name']
# 确保名称唯一
base_name = generated_name
counter = 2
while generated_name in self.used_names:
generated_name = f"{base_name}·{counter}"
counter += 1
self.used_names.add(generated_name)
return generated_name, result['template_name']
def _generate_id(self) -> int:
"""生成唯一ID"""
id = self.next_species_id
self.next_species_id += 1
return id
def _randint(self, low: int, high: int) -> int:
"""整数均匀分布随机数"""
return random.randint(low, high)
def _calc_initial_Q(self, V: float, K: float, rho: float) -> float:
"""
计算初始Q
Q = floor(K / V^ρ * U(0.85, 1.15))
"""
noise = random.uniform(0.85, 1.15)
Q = math.floor(K / (V ** rho) * noise)
return max(1, Q)
def _check_extinction_buffer(self, Q: float, V: float, B: float) -> bool:
"""
检查灭绝缓冲约束
Q >= 1.5 * 100V/B
"""
threshold = cfg.EXTINCTION_BUFFER * 100 * V / B
return Q >= threshold
def _check_predation_viability(self, predator: Species, prey: Species) -> bool:
"""
检查捕食可行性约束
(A_i/D_k) * (S_i/S_k) * (V_i/V_k) >= 0.6
"""
if prey.D <= 0 or prey.S <= 0 or prey.V <= 0:
return True # 植物猎物不需要检查
ratio = (predator.A / prey.D) * (predator.S / prey.S) * (predator.V / prey.V)
return ratio >= cfg.PREDATION_VIABILITY_THRESHOLD
def _create_plant(self) -> Species:
"""创建植物物种"""
conf = cfg.INIT_CONFIG['plant']
# 生成整数属性
V = self._randint(*conf['V'])
B = self._randint(*conf['B'])
F = self._randint(*conf['F'])
# 计算初始Q
Q = self._calc_initial_Q(V, conf['K'], conf['rho'])
# 检查灭绝缓冲(植物用更低的系数50而非100)
min_Q = cfg.EXTINCTION_BUFFER * 50 * V / B
Q = max(Q, min_Q)
# 使用拟合算法生成名称
name, template_name = self._get_fitted_name(
{'V': V, 'B': B, 'F': F},
'plant',
is_social=True
)
return Species(
id=self._generate_id(),
name=name,
species_type=SpeciesType.PLANT,
Q=Q,
V=V,
B=B,
F=F,
lifestyle=Lifestyle.SOCIAL, # 植物固定群居
)
def _create_herbivore(self, plants: List[Species]) -> Species:
"""创建植食动物"""
conf = cfg.INIT_CONFIG['herbivore']
# 生成整数属性
V = self._randint(*conf['V'])
S = self._randint(*conf['S'])
D = self._randint(*conf['D'])
A = self._randint(*conf['A'])
B = self._randint(*conf['B'])
F = self._randint(*conf['F'])
# 生活方式
lifestyle = Lifestyle.SOCIAL if random.random() < conf['lifestyle_prob']['social'] else Lifestyle.SOLITARY
# 食谱:选择2种不同植物
diet_count = conf['diet_count']
if len(plants) < diet_count:
diet_count = len(plants)
diet = set(random.sample([p.id for p in plants], diet_count))
# 计算初始Q
Q = self._calc_initial_Q(V, conf['K'], conf['rho'])
# 检查灭绝缓冲
min_Q = cfg.EXTINCTION_BUFFER * 100 * V / B
Q = max(Q, min_Q)
# 使用拟合算法生成名称
is_social = lifestyle == Lifestyle.SOCIAL
name, template_name = self._get_fitted_name(
{'V': V, 'S': S, 'D': D, 'A': A, 'B': B, 'F': F},
'herbivore',
is_social
)
return Species(
id=self._generate_id(),
name=name,
species_type=SpeciesType.HERBIVORE,
Q=Q,
V=V,
S=S,
D=D,
A=A,
B=B,
F=F,
lifestyle=lifestyle,
diet=diet,
plant_diet_efficiency=0.8, # 草食动物擅长消化植物
animal_diet_efficiency=0.3, # 草食动物不擅长消化动物
)
def _create_carnivore(self, herbivores: List[Species], existing_carnivores: List[Species]) -> Species:
"""创建肉食动物"""
conf = cfg.INIT_CONFIG['carnivore']
max_attempts = 20
for attempt in range(max_attempts):
# 生成整数属性
V = self._randint(*conf['V'])
S = self._randint(*conf['S'])
D = self._randint(*conf['D'])
A = self._randint(*conf['A'])
B = self._randint(*conf['B'])
F = self._randint(*conf['F'])
# 生活方式
lifestyle = Lifestyle.SOCIAL if random.random() < conf['lifestyle_prob']['social'] else Lifestyle.SOLITARY
# 食谱:选择1-2种植食动物(禁止初始互相捕食)
diet_count = random.randint(*conf['diet_count'])
if len(herbivores) < diet_count:
diet_count = len(herbivores)
# 选择猎物
potential_prey = herbivores.copy()
diet = set()
# 创建临时物种用于检查
temp_species = Species(
id=-1, name="temp",
species_type=SpeciesType.CARNIVORE,
V=V, S=S, D=D, A=A, B=B, F=F,
)
# 选择满足捕食可行性的猎物
random.shuffle(potential_prey)
for prey in potential_prey:
if self._check_predation_viability(temp_species, prey):
diet.add(prey.id)
prey.been_hunted = True # 标记被捕食
if len(diet) >= diet_count:
break
# 如果没有找到足够的猎物,调整属性后重试
if len(diet) < 1:
continue
# 计算初始Q
Q = self._calc_initial_Q(V, conf['K'], conf['rho'])
# 检查灭绝缓冲
min_Q = cfg.EXTINCTION_BUFFER * 100 * V / B
Q = max(Q, min_Q)
# 使用拟合算法生成名称
is_social = lifestyle == Lifestyle.SOCIAL
name, template_name = self._get_fitted_name(
{'V': V, 'S': S, 'D': D, 'A': A, 'B': B, 'F': F},
'carnivore',
is_social
)
return Species(
id=self._generate_id(),
name=name,
species_type=SpeciesType.CARNIVORE,
Q=Q,
V=V,
S=S,
D=D,
A=A,
B=B,
F=F,
lifestyle=lifestyle,
diet=diet,
plant_diet_efficiency=0.3, # 肉食动物不擅长消化植物
animal_diet_efficiency=0.8, # 肉食动物擅长消化动物
)
# 如果多次尝试失败,强制创建一个(放宽属性范围)
V = 6.0
S = 6.0
A = 7.0
D = 4.0
B = 3.0
F = 3.0
lifestyle = Lifestyle.SOLITARY
diet = {herbivores[0].id} if herbivores else set()
Q = self._calc_initial_Q(V, conf['K'], conf['rho'])
return Species(
id=self._generate_id(),
name=self._get_unique_name(cfg.CARNIVORE_NAMES),
species_type=SpeciesType.CARNIVORE,
Q=Q,
V=V,
S=S,
D=D,
A=A,
B=B,
F=F,
lifestyle=lifestyle,
diet=diet,
plant_diet_efficiency=0.3, # 肉食动物不擅长消化植物
animal_diet_efficiency=0.8, # 肉食动物擅长消化动物
)
def _create_omnivore(self, plants: List[Species], herbivores: List[Species]) -> Species:
"""创建杂食动物"""
conf = cfg.INIT_CONFIG['omnivore']
max_attempts = 20
for attempt in range(max_attempts):
# 生成整数属性
V = self._randint(*conf['V'])
S = self._randint(*conf['S'])
D = self._randint(*conf['D'])
A = self._randint(*conf['A'])
B = self._randint(*conf['B'])
F = self._randint(*conf['F'])
# 生活方式
lifestyle = Lifestyle.SOCIAL if random.random() < conf['lifestyle_prob']['social'] else Lifestyle.SOLITARY
# 食谱:植物 + 动物(杂食特性)
plant_diet_count = conf.get('plant_diet_count', 1)
animal_diet_count = conf.get('animal_diet_count', 1)
diet = set()
# 添加植物食谱
if len(plants) >= plant_diet_count:
plant_diet = random.sample([p.id for p in plants], plant_diet_count)
diet.update(plant_diet)
elif plants:
diet.update([p.id for p in plants])
# 创建临时物种用于检查捕食可行性
temp_species = Species(
id=-1, name="temp",
species_type=SpeciesType.OMNIVORE,
V=V, S=S, D=D, A=A, B=B, F=F,
)
# 添加动物食谱(优先选择能捕食的)
potential_prey = herbivores.copy()
random.shuffle(potential_prey)
animal_diet = []
for prey in potential_prey:
if self._check_predation_viability(temp_species, prey):
animal_diet.append(prey.id)
prey.been_hunted = True
if len(animal_diet) >= animal_diet_count:
break
# 如果没找到可捕食的动物,降低要求选择体型最小的
if not animal_diet and herbivores:
smallest = min(herbivores, key=lambda x: x.V)
animal_diet.append(smallest.id)
smallest.been_hunted = True
diet.update(animal_diet)
# 如果没有任何食物来源,重试
if not diet:
continue
# 计算初始Q
Q = self._calc_initial_Q(V, conf['K'], conf['rho'])
# 检查灭绝缓冲
min_Q = cfg.EXTINCTION_BUFFER * 100 * V / B
Q = max(Q, min_Q)
# 使用拟合算法生成名称
is_social = lifestyle == Lifestyle.SOCIAL
name, template_name = self._get_fitted_name(
{'V': V, 'S': S, 'D': D, 'A': A, 'B': B, 'F': F},
'omnivore',
is_social
)
return Species(
id=self._generate_id(),
name=name,
species_type=SpeciesType.OMNIVORE,
Q=Q,
V=V,
S=S,
D=D,
A=A,
B=B,
F=F,
lifestyle=lifestyle,
diet=diet,
plant_diet_efficiency=0.6, # 杂食动物平衡消化植物
animal_diet_efficiency=0.6, # 杂食动物平衡消化动物
)
# 如果多次尝试失败,强制创建一个
V = 5.0
S = 5.0
A = 5.0
D = 5.0
B = 5.0
F = 6.0 # 杂食动物适应性较高
lifestyle = Lifestyle.SOCIAL
diet = set()
if plants:
diet.add(plants[0].id)
if herbivores:
diet.add(herbivores[0].id)
Q = self._calc_initial_Q(V, conf['K'], conf['rho'])
is_social = lifestyle == Lifestyle.SOCIAL
name, template_name = self._get_fitted_name(
{'V': V, 'S': S, 'D': D, 'A': A, 'B': B, 'F': F},
'omnivore',
is_social
)
return Species(
id=self._generate_id(),
name=name,
species_type=SpeciesType.OMNIVORE,
Q=Q,
V=V,
S=S,
D=D,
A=A,
B=B,
F=F,
lifestyle=lifestyle,
diet=diet,
plant_diet_efficiency=0.6,
animal_diet_efficiency=0.6,
)
def _check_niche_overlap_constraint(self, species_list: List[Species]) -> bool:
"""
检查初始竞争上限约束
Σ NicheOverlap(i,j) <= 2.5 对所有物种
"""
if len(species_list) < 2:
return True
calc = EcologyCalculator(species_list)
for s in species_list:
total_overlap = calc.get_total_niche_overlap(s)
if total_overlap > cfg.MAX_NICHE_OVERLAP_SUM:
return False
return True
def initialize_world(self) -> List[Species]:
"""
初始化世界,生成10个物种
顺序:植物 → 植食动物 → 杂食动物 → 肉食动物
"""
species_list: List[Species] = []
# Step 1: 创建植物(4种)
plants = []
for _ in range(cfg.INIT_CONFIG['plant']['count']):
plant = self._create_plant()
plants.append(plant)
species_list.append(plant)
# Step 2: 创建植食动物(2种)
herbivores = []
for _ in range(cfg.INIT_CONFIG['herbivore']['count']):
herbivore = self._create_herbivore(plants)
herbivores.append(herbivore)
species_list.append(herbivore)
# Step 3: 创建杂食动物(2种)
omnivores = []
for _ in range(cfg.INIT_CONFIG['omnivore']['count']):
omnivore = self._create_omnivore(plants, herbivores)
omnivores.append(omnivore)
species_list.append(omnivore)
# Step 4: 创建肉食动物(2种)
# 肉食动物可以捕食植食动物和杂食动物
all_prey = herbivores + omnivores
carnivores = []
for _ in range(cfg.INIT_CONFIG['carnivore']['count']):
carnivore = self._create_carnivore(all_prey, carnivores)
carnivores.append(carnivore)
species_list.append(carnivore)
# 验证约束(如果不满足,记录警告但不重新生成)
if not self._check_niche_overlap_constraint(species_list):
print("[警告] 初始生态位重叠超过约束,但继续运行")
return species_list
def select_player_species(self, species_list: List[Species]) -> Species:
"""
让玩家选择操控的物种(必须是动物)
返回被选中的物种
"""
animals = [s for s in species_list if s.is_animal]
print("\n" + "="*50)
print("请选择你要操控的物种(只能选择动物):")
print("="*50)
for i, s in enumerate(animals):
print(f"\n[{i+1}] {s}")
# 显示食谱
diet_names = []
for prey_id in s.diet:
prey = next((x for x in species_list if x.id == prey_id), None)
if prey:
diet_names.append(prey.name)
print(f" 食谱: {', '.join(diet_names) if diet_names else '无'}")
while True:
try:
choice = int(input("\n请输入编号 (1-6): "))
if 1 <= choice <= len(animals):
selected = animals[choice - 1]
selected.is_player_controlled = True
print(f"\n你选择了: {selected.name}")
return selected
else:
print("无效的编号,请重新输入")
except ValueError:
print("请输入数字")
def auto_select_player_species(self, species_list: List[Species]) -> Species:
"""自动选择玩家物种(随机选一个动物)"""
animals = [s for s in species_list if s.is_animal]
selected = random.choice(animals)
selected.is_player_controlled = True
return selected