-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLevel.py
389 lines (325 loc) · 12 KB
/
Level.py
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
"""
Levels Module which holds 2 Classes
Level()
Levelinit()
"""
import json
import random
import os
from Utils import Pr, Logger
from config import entities_folder
class Level:
"""
Class which defines Levels
Contains Functions:
from_json : Creates Levels from JSON
"""
__slots__ = (
"name",
"descr",
"text",
"choices",
"inv",
"triggers",
"ltype",
"entitylist",
"entityspawn",
)
def __init__(
self,
text=None,
choices=None,
name="Levelnameplatzhalter",
inv=None,
ltype="Testtype",
descr="Standartdescription du Sohn einer Dirne",
entitylist=None,
entityspawn=None,
triggers=None,
):
if text is None:
text = []
if choices is None:
choices = []
if inv is None:
inv = []
if entitylist is None:
entitylist = []
if triggers is None:
triggers = []
if entityspawn is None:
entityspawn = []
self.name = name
self.descr = descr
# self.text = text
self.choices = self.zip_choices(text, choices)
self.inv = inv
self.triggers = triggers
self.ltype = ltype
self.entitylist = entitylist
self.entityspawn = entityspawn
self.onLevelCreate()
self.populate()
def __str__(self):
return f"{self.name}"
# Commented out for readability in Logfile - need to find a workaround
# def __repr__(self):
# return f"[{self.__class__.__module__}.{self.__class__.__name__}([{self.text}],[{self.choices}],'{self.name}',[{self.inv}],'{self.ltype}','{self.descr}',[{self.entitylist}],[{self.entityspawn}],[{self.triggers}]) at <{hex(id(self))}>]" # pylint:disable=C0301
@staticmethod
def from_json(json_dct, lname):
"""Creates a Level from JSON
Args:
json_dct (JSON): Json Data to be parsed
lname (String): Levelname
Returns:
Level: Level
"""
return Level(
json_dct["text"],
json_dct["choices"],
lname,
json_dct["inv"],
json_dct["ltype"],
json_dct["descr"],
json_dct["entitylist"],
json_dct["entityspawn"],
json_dct["triggers"],
)
def change_entity_list(self, ctype, entity):
"""
Changes the list of entities for specific level
:ctype: + for adding, - for subtracting entity from list
:entity: the entity obj
:dbg: debug, default = True
=return= returns True if seccessfull, else false
"""
match ctype:
case "+":
Logger.log(
f"Entitylist of Level {self}: {[str(x) for x in self.entitylist]}"
)
Logger.log(f"Trying to add {entity} to {self}")
try:
for e in self.entitylist:
if e.name == entity.name:
raise Exception(
f"{entity} \
is already in entitielist of Level \
{self} \
and thus cannot be added."
)
self.entitylist.append(entity)
self.onEntityJoin(entity)
Logger.log(f"{entity} got added to Level {self}")
Logger.log(
f"Entitylist of Level {self}: {[str(x) for x in self.entitylist]}"
)
Logger.log(
f"Changing Entity Location Var from Level for Entity: {entity}",
2,
)
entity.location = self
return True
except Exception as e:
Logger.log(e, 4)
return False
case "-":
Logger.log(
f"Entitylist of Level {self}: {[str(x) for x in self.entitylist]}"
)
Logger.log(f"Trying to remove {entity.name} from {self}")
try:
self.entitylist = list(
filter(lambda e: e.name != entity.name, self.entitylist)
)
self.onEntityLeave(entity)
Logger.log(f"{entity.name} got removed from Level {self}")
Logger.log(
f"Entitylist of Level {self}: {[str(x) for x in self.entitylist]}"
)
return True
except:
return False
case _:
return Logger.log("got no right ctype. choose between + and -", 1)
def printDesc(self):
"""Prints Level Description to User"""
for entry in self.descr:
if len(entry) > 1:
if isinstance(entry, str):
Pr.n(f"{str(entry)}")
continue
if entry[1] in self.triggers:
Pr.n(f"{str(entry[0])}")
continue
def getAvailableChoices(self):
"""Returns the Choices currently available to the User
Returns:
list: Choices
"""
achoices = []
for choice in self.choices:
# The following part adds choices without trigger
# to the availibleChoices.
# Choices with trigger get added if
# Level.triggers[n] == Choice.allow_trigger
if choice.allow_trigger is None:
achoices.append(choice)
elif isinstance(choice.allow_trigger, dict):
for set_trigger in self.triggers:
if set_trigger == choice.allow_trigger:
achoices.append(choice)
else:
Logger.log(
f"Unsupported allow_trigger in Choice! {choice.allow_trigger}"
)
return achoices
def printChoices(self):
"""Prints the Available Choices to the User
Returns:
Boolean: True
"""
i = 1
for llist in self.choices:
if len(llist) == 1 and llist[0] != "":
Pr.n(f"{i}. {llist[0]}")
i = i + 1
elif len(llist) > 1:
for ddict in self.triggers:
if llist[1] == ddict:
Pr.n(f"{i}. {llist[0]}")
i = i + 1
return True
def levelname(lobject):
"""Return the Name of an Levelobject
Args:
object (Level): Level from what you wan't the Objectname
Returns:
String: Levelname
"""
try:
return lobject.name
except Exception as e:
Logger.log(f"ERR: {e}", 2)
return None
def populate(self): # pylint: disable=R1710
"""Populates the Level with Entities from Spawnlist
Returns:
Array: List of Entities
"""
from Entities import EntityInit # pylint: disable=C0415
_entitiestospawn = self.entityspawn
if _entitiestospawn is None or len(_entitiestospawn) < 1:
Logger.log("No Entities to Spawn in this Level", 2)
return 1
_amount = random.randrange(1, len(_entitiestospawn))
Logger.log(f"Entities to spawn: {_entitiestospawn}, Amount: {_amount}")
_dict = list(_entitiestospawn.keys())
_weights = list(_entitiestospawn.values())
Logger.log(f"Trying to Spawn {_amount} Entities", 1)
_entity = random.choices(_dict, weights=_weights, k=_amount)
_entityreturn = []
for i in _entity:
Logger.log(f"Loading Entity {i} from Assets", 0)
_entityreturn.append(
EntityInit.load_entities_by_name_from_json(
f"{entities_folder}{os.sep}{i}.json", i
)
)
for e in _entityreturn:
Logger.log(f"Adding spawned Entity {e} to Level", 1)
self.change_entity_list("+", e)
return
def onLevelCreate(self):
"""This is called whenever an Level is created"""
Logger.log(f"Created Instance of Level: {self}", 0)
def onEntityJoin(self, entity):
"""This is called whenever an Entity joins a Level
Args:
entity (entity): Entity which is joining the Level
"""
Logger.log(f"Entity:{entity} joined Level: {self}", 0)
if entity.isPlayer:
if len(self.entitylist) > 1:
# TODO: Add Chance to put Player into Combat
# TODO: Change Chance based on Entity hostility
Logger.log(f"Entitylist of Level: {self.entitylist}", -1)
Pr.n(f"Du wirst von {self.entitylist[0]} angegriffen!")
entity.actionstack.insert( # pylint: disable=E1101
0, ["change_gamestate", ["combat"]]
)
def onEntityLeave(self, entity):
"""This is called whenever an Entity Leaves a Level
Args:
entity (entity): Entity which is leaving the Level
"""
Logger.log(f"Entity:{entity} left Level: {self}", 0)
def zip_choices(self, text, choices):
"""This is called whenever a level gets created and populates
its choices.
Args:
text (list[string, {action}]): Follow-up text and actions
choices (list): all hardcoded choices
"""
zipped_choices = []
for index, choice in enumerate(choices):
zipped_choices.append(
Choice(text[index], choice, choice[1] if len(choice) > 1 else None)
)
return zipped_choices
class LevelInit:
"""
Class which Initializes Levels
Contains Functions:
load_all_levels_from_json : Loads all available Levels from a Json File
load_level_by_name_from_json : Loads an Level by it's Name from a Json File
"""
def load_all_levels_from_json(json_file, _curLevels=None):
"""
Return alls Levels from Json file
:json_file (File): Json file to load Levels from
:_curLevels (List): Internally used for recursion
=return= List of all Levels loaded from Json
"""
if _curLevels is None:
_curLevels = []
curLevels = _curLevels
Logger.log(f"Loading Levels from: {json_file}")
if json_file:
if not isinstance(json_file, dict):
with open(json_file, encoding="UTF-8") as json_data:
data = json.load(json_data)
else:
data = json_file
for lname in data.keys():
if lname[0] != "$":
if data[lname].get("child_levels"):
childlevels = data[lname].get("child_levels")
LevelInit.load_all_levels_from_json(childlevels, curLevels)
curLevels.append(Level.from_json(data[lname], lname))
return curLevels
def load_level_by_name_from_json(json_file, name):
"""
Return a single Level Object from Json/File by given Name
:json_file (File): Json File to load Level from
=return= Level object
"""
if json_file:
if not isinstance(json_file, dict):
with open(json_file, encoding="UTF-8") as json_data:
data = json.load(json_data)
else:
data = json_file
for lname in data.keys():
if name == lname:
return Level.from_json(data[lname], lname)
Logger.log(f"Levelname: {name} not found!", 1)
return False
class Choice:
"""
Class witch defines Choices.
"""
def __init__(self, text, choice, allow_trigger=None):
self.choice = choice
self.text = text
self.allow_trigger = allow_trigger