-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkreatures.py
More file actions
317 lines (274 loc) · 12.3 KB
/
kreatures.py
File metadata and controls
317 lines (274 loc) · 12.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
# Copyright (c) 2022 Daniel McCoy Stephenson
# Apache License 2.0
import json
import os
import random
import time
from world.world import World
from entity.livingEntity import LivingEntity
from config.config import Config
# @author Daniel McCoy Stephenson
class Kreatures:
def __init__(self):
self.environment = World()
self.names = self._load_names()
print("What would you like to name your kreature?")
self.creatureName = input("> ")
self.playerCreature = LivingEntity(self.creatureName)
self.running = True
self.config = Config()
self.tick = 0
# Initialize player early-game protection
self.playerCreature.damageReduction = self.config.playerDamageReduction
self.playerCreature.log.append(
"%s has early-game protection!" % self.playerCreature.name
)
def _load_names(self):
"""Load names from configuration file"""
try:
# Get the directory of this file to build the path to names.json
current_dir = os.path.dirname(os.path.abspath(__file__))
names_file = os.path.join(current_dir, "config", "names.json")
with open(names_file, "r") as f:
config = json.load(f)
return config["names"]
except (FileNotFoundError, KeyError, json.JSONDecodeError) as e:
# Fallback to a minimal set of names if config file is missing/corrupted
print(f"Warning: Could not load names from config file: {e}")
print("Using fallback names list.")
return [
"Jesse",
"Juan",
"Jose",
"Ralph",
"Jeremy",
"Bobby",
"Johnny",
"Douglas",
"Peter",
"Scott",
"Kyle",
"Billy",
"Terry",
"Randy",
"Adam",
]
def initiateEntityActions(self):
entities_to_remove = [] # Track entities that die this turn
for entity in self.environment.getEntities():
target = self.environment.getRandomEntity()
if target == entity:
continue
decision = entity.getNextAction(target)
if decision == "nothing":
entity.log.append(
"%s had an argument with %s!" % (entity.name, target.name)
)
elif decision == "love":
parents = entity.reproduce(target)
entity.increaseChanceToBefriend()
entity.decreaseChanceToFight()
self.createChildEntity(parents[0], parents[1])
elif decision == "fight":
# Enhanced protection: during grace period, reduce attacks on player
if target == self.playerCreature:
if self.config.godMode:
continue
# During grace period, 85% chance to skip attacking the player
if (
self.tick < self.config.earlyGameGracePeriod
and random.randint(1, 100) <= 85
):
entity.log.append(
"%s decided not to attack %s." % (entity.name, target.name)
)
continue
entity.increaseChanceToFight()
entity.decreaseChanceToBefriend()
entity.fight(target)
# Check if either entity died from the fight to the death
if not target.isAlive() and target not in entities_to_remove:
entities_to_remove.append(target)
if not entity.isAlive() and entity not in entities_to_remove:
entities_to_remove.append(entity)
elif decision == "befriend":
entity.increaseChanceToBefriend()
entity.decreaseChanceToFight()
entity.befriend(target)
# Remove all entities that died this turn
for entity in entities_to_remove:
self.environment.removeEntity(entity)
def updatePlayerProtection(self):
"""Update player protection based on current tick"""
if self.tick >= self.config.earlyGameGracePeriod:
# Grace period has ended
if (
hasattr(self.playerCreature, "damageReduction")
and self.playerCreature.damageReduction > 0
):
self.playerCreature.damageReduction = 0
self.playerCreature.log.append(
"%s's protection has worn off!" % self.playerCreature.name
)
def regenerateAllEntities(self):
"""Regenerate health for all living entities
This method is called every game tick AFTER entities take their actions in
initiateEntityActions(). Health regeneration is a passive background process
that does not prevent entities from making decisions or taking actions.
Entities continue to fight, befriend, and reproduce regardless of their
health status or whether they are regenerating.
"""
for entity in self.environment.getEntities():
if entity.isAlive():
entity.regenerateHealth()
def createEntity(self):
newEntity = LivingEntity(self.names[random.randint(0, len(self.names) - 1)])
self.environment.addEntity(newEntity)
def createChildEntity(self, parent1, parent2):
"""Create a child entity with proper parent-child relationships"""
childName = self.names[random.randint(0, len(self.names) - 1)]
child = LivingEntity(childName)
# Set up parent-child relationships
child.addParent(parent1)
child.addParent(parent2)
parent1.addChild(child)
parent2.addChild(child)
# Child inherits some traits from parents (average)
child.chanceToFight = (parent1.chanceToFight + parent2.chanceToFight) // 2
child.chanceToBefriend = 100 - child.chanceToFight
# Child inherits health traits from parents (average with some variation)
parentHealthAvg = (parent1.maxHealth + parent2.maxHealth) // 2
child.health = parentHealthAvg + random.randint(-10, 10) # Add some variation
child.maxHealth = child.health
child.log.append(
"%s is the child of %s and %s." % (childName, parent1.name, parent2.name)
)
self.environment.addEntity(child)
return child
def getLivingChildren(self, entity):
"""Get all living children of an entity"""
living_children = []
for child in entity.children:
if child in self.environment.entities:
living_children.append(child)
return living_children
def continueAsChild(self):
"""Allow player to continue as one of their creature's children"""
living_children = self.getLivingChildren(self.playerCreature)
if not living_children:
return False
print(
f"\n{self.playerCreature.name} has died, but has {len(living_children)} living children!"
)
print("Would you like to continue as one of your children? (y/n)")
choice = input("> ").lower().strip()
if choice == "y" or choice == "yes":
if len(living_children) == 1:
# Only one child, automatically select it
new_player = living_children[0]
print(f"You are now playing as {new_player.name}!")
else:
# Multiple children, let player choose
print("\nWhich child would you like to continue as?")
for i, child in enumerate(living_children):
print(f"{i+1}. {child.name}")
while True:
try:
choice_idx = int(input("> ")) - 1
if 0 <= choice_idx < len(living_children):
new_player = living_children[choice_idx]
print(f"You are now playing as {new_player.name}!")
break
else:
print("Invalid choice. Please try again.")
except ValueError:
print("Please enter a number.")
# Update the player creature reference
self.playerCreature = new_player
# Make sure the new player creature is at position 0 in the entities list
if new_player in self.environment.entities:
self.environment.entities.remove(new_player)
self.environment.entities.insert(0, new_player)
self.running = True # Continue the game
return True
return False
def printSummary(self):
print("=== Summary ===")
if self.playerCreature.chanceToFight > self.playerCreature.chanceToBefriend:
print("%s was ferocious." % self.playerCreature.name)
elif self.playerCreature.chanceToBefriend > self.playerCreature.chanceToFight:
print("%s was very friendly." % self.playerCreature.name)
else:
print("%s was neutral." % self.playerCreature.name)
print(
"%s's chance to get into a fight was %d percent."
% (self.playerCreature.name, self.playerCreature.chanceToFight)
)
print(
"%s's chance to be nice was %d percent."
% (self.playerCreature.name, self.playerCreature.chanceToBefriend)
)
# Show protection status
if (
hasattr(self.playerCreature, "damageReduction")
and self.playerCreature.damageReduction > 0
):
protection_percent = int(self.playerCreature.damageReduction * 100)
print(
"%s still has %d%% damage reduction."
% (self.playerCreature.name, protection_percent)
)
if self.playerCreature.isAlive():
print(
"%s ended with %d health (out of %d max)."
% (
self.playerCreature.name,
self.playerCreature.health,
self.playerCreature.maxHealth,
)
)
else:
print("%s died during the simulation." % self.playerCreature.name)
print("Kreatures still alive: %d" % self.environment.getNumEntities())
print("Simulation ran for %d ticks." % self.tick)
def printStats(self):
print("=== Stats ===")
print("Friendships forged: %d" % self.playerCreature.stats.numFriendshipsForged)
print("Babies made: %d" % self.playerCreature.stats.numOffspring)
print("Creatures Eaten: %d" % self.playerCreature.stats.numCreaturesEaten)
def run(self):
self.environment.entities[0] = self.playerCreature
print("")
# code to run a day, then show any new additions to log
while self.running:
try:
print(self.playerCreature.log[0]) # tries to print log entry
if (
"eaten" in self.playerCreature.log[0]
): # if creature was eaten, check for children
if not self.continueAsChild():
self.running = False
break
del self.playerCreature.log[0] # tries to delete log entry
except: # if list is empty, just keep going
pass
# Game tick order is important:
# 1. Entities take actions (fight, befriend, reproduce) based on their decision-making
self.initiateEntityActions()
# 2. Update player protection status based on current tick
self.updatePlayerProtection()
# 3. Passive health regeneration happens AFTER actions, as a background process
# This ensures entities can take actions regardless of health/regeneration status
self.regenerateAllEntities()
time.sleep(self.config.tickLength)
self.tick += 1
if self.tick >= self.config.maxTicks:
print("Maximum iterations reached.")
self.running = False
break
input("[CONTINUE]")
self.printSummary()
self.printStats()
if __name__ == "__main__":
kreatures = Kreatures()
kreatures.run()