-
Notifications
You must be signed in to change notification settings - Fork 43
/
quest_engine.py
644 lines (506 loc) · 32.2 KB
/
quest_engine.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
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
import math
from functools import reduce
from flask import session
from game_settings import game_settings, lookup_item_by_code, lookup_state_machine, replenish_energy, lookup_yield, \
allies, get_sessions_friends, lookup_items_by_unit_class
from quest_settings import quest_settings, prequels
from save_engine import lookup_objects_by_item_name, create_backup, get_saves
def merge_quest_progress(qc, output_list, label):
if qc:
print("new q before merge " + repr(qc))
print(label + " list before merge " + repr (output_list))
output_list[:] = qc + [e for e in output_list if e['name'] not in [q['name'] for q in qc]]
print(label + " list after merge " + repr (output_list))
def lookup_quest(name):
quests = [r for r in quest_settings['quests']['quest'] if r['_name'] == name]
return quests[0] if len(quests) == 1 else None
def new_quest(quest):
# progress = [0 for e in quest['tasks']]
progress, completes = map(list, zip(*[prepopulate_task(e) for e in get_tasks(quest)]))
return {"name": quest['_name'], "complete": all(completes), "expired": False, "progress": progress, "completedTasks": reduce((lambda x, y: x << 1 | y), [False] + completes[::-1])}
def progress_quest_task(name, index):
return lambda task, progress, i, extra, quest_name, *args: \
quest_name == name and \
i == index and \
progress_total_amount(task["_total"], task["_total"], extra, progress)
def progress_quest(name):
return lambda task, progress, i, extra, quest_name, *args: \
quest_name == name and \
progress_total_amount(task["_total"], task["_total"], extra, progress)
def progress_feed(feed_name):
return lambda task, progress, i, extra, quest_name, *args: \
task["_action"] == "feedReceived" and \
task["_feed"] == feed_name and \
progress_total_amount(task["_total"], task["_total"], extra, progress)
def prepopulate_task(task):
if task["_action"] == 'countPlaced' and "_item" in task:
item = lookup_item_by_code(task["_item"])
if 'stateMachineValues' in item:
state_machine = lookup_state_machine(item['stateMachineValues']['-stateMachineName'],
item['stateMachineValues'].get('define', []))
else:
state_machine = None
objects = lookup_objects_by_item_name(item['-name'])
built_objects = [e for e in objects if
int(e.get('state', 0)) >= (int(state_machine['-builtState']) if state_machine else 0)]
number_built = len(built_objects)
return min(number_built, int(task["_total"])), number_built >= int(task["_total"])
elif task["_action"] == 'countPlaced' and "_unitClass" in task:
items = lookup_items_by_unit_class(task["_unitClass"])
number_placed = 0
for item in items:
objects = lookup_objects_by_item_name(item['-name'])
number_placed += len(objects)
return min(number_placed, int(task["_total"])), number_placed >= int(task["_total"])
elif task["_action"] == 'countPlacements':
item = lookup_item_by_code(task.get("_item", task.get('_code')))
objects = lookup_objects_by_item_name(item['-name'])
number_placed = len(objects)
return min(number_placed, int(task["_total"])), number_placed >= int(task["_total"])
elif task["_action"] == 'inventoryCount':
item_inventory = session['user_object']["userInfo"]["player"]["inventory"]["items"]
return min(item_inventory.get(task["_item"], 0), int(task["_total"])), item_inventory.get(task["_item"], 0) >= int(task["_total"])
elif task["_action"] == 'population':
return min(session['population'], int(task["_total"])), session['population'] >= int(task["_total"])
elif task["_action"] == 'neighborsAdded':
if task["_desc"] == "quest_1140_task_01":
return 0, False
else:
neighbor_count = len([ally for ally in allies.values() if ally.get("friend") and ally.get("neighbor")])
return min(neighbor_count, int(task["_total"])), neighbor_count >= int(task["_total"])
elif task["_action"] == 'countUpgrades':
research = session['user_object']["userInfo"]["world"]["research"]
total = 0
unit = task["unit"]
for k, v in research.items():
if "_item" in unit:
if k == unit["_item"]:
total += len(v)
elif "_unitClass" in unit:
item = lookup_item_by_code(k)
if item["-unitClass"] == unit["_unitClass"]:
total += len(v)
elif "_subtype" in unit:
item = lookup_item_by_code(k)
if item["-subtype"] == unit["_subtype"]:
total += len(v)
return min(total, int(task["_total"])), total >= int(task["_total"])
elif task["_action"] == 'autoComplete':
return 1, True
else:
return 0, False
# "autoComplete","battleDamage","battleKill","build","buyExpansion","challengeCreate","clear","countPlaced","expandIsland","fight","finishBuilding","fullscreen","genericString","harvest","inventoryAdded","islandWin","marketAdd","marketBuy","move","neighborsAdded","openDialog","ownObjects","ownResource","place","population","pillage","pvpCombat","resourceAdded","seenFlag","select","socialXPAdded","startImmunity","state","tending","tendingRewardDropped","unlockTutorial","useConsumable","visit","zoom"
def handle_world_state_change(meta, *state_args):
handle_quest_progress(meta, world_state_change(*state_args))
def world_state_change(*state_args):
return lambda *args: \
any([progress_finish_building_count_placed(*state_args)(*args),
progress_auto_complete()(*args),
progress_place(*state_args)(*args),
progress_place_unit(*state_args)(*args),
progress_build(*state_args)(*args),
progress_harvest(*state_args)(*args),
progress_state(*state_args)(*args),
progress_inventory_count()(*args),
progress_harvest_consumable(*state_args)(*args)
])
def progress_finish_building_count_placed(state, state_machine, game_item, step, previous_state, *state_args):
return lambda task, progress, i, *args: \
task["_action"] in ["finishBuilding", "countPlaced"] and progress_match_filters(game_item)(task, progress, i, *args) and \
progress < int(task["_total"]) and state['-stateName'] == state_machine['-builtState'] and \
int(previous_state['-stateName']) < int(state['-stateName'])
def progress_match_filters(game_item):
return all_lambda(
progress_parameter_implies("_item", game_item.get("-code", "")),
progress_parameter_implies("_type", game_item.get("-type", "")),
progress_parameter_implies("_subtype", game_item.get("-subtype", "")),
progress_parameter_implies("_unitClass", game_item.get("-unitClass", "")),
progress_parameter_implies("_warehouseType", game_item.get("-warehouseType", "")),
progress_parameter_implies("_superore", game_item.get("-superore", "")),
progress_parameter_implies("_resourceType", game_item.get("-resourceType", "")),
progress_parameter_implies("_villain", game_item.get("-villain", ""))
)
def progress_inventory_count():
return lambda task, progress, i, extra, *args: \
task["_action"] == "inventoryCount" and progress_inventory(task["_item"], task["_total"], extra, progress) \
and progress < int(task["_total"])
def progress_inventory(item, maximum_total, extra, progress):
item_inventory = session['user_object']["userInfo"]["player"]["inventory"]["items"]
total = min(item_inventory.get(item, 0), int(maximum_total))
extra["total"] = total
return total != progress
def progress_neighbor_count():
return lambda task, progress, i, extra, *args: \
task["_action"] == "neighborsAdded" and progress_neighbors(task["_total"], extra, progress) \
and progress < int(task["_total"])
def progress_neighbors(maximum_total, extra, progress):
neighbor_count = len([ally for ally in allies.values() if ally.get("friend") and ally.get("neighbor")] + get_sessions_friends(get_saves()))
total = min(neighbor_count, int(maximum_total))
extra["total"] = total
return total != progress
def progress_upgrades_count():
return lambda task, progress, i, extra, *args: \
task["_action"] == "countUpgrades" and progress_upgrades(task["unit"], task["_total"], extra, progress) \
and progress < int(task["_total"])
def progress_upgrades(unit, maximum_total, extra, progress):
research = session['user_object']["userInfo"]["world"]["research"]
total = 0
for k, v in research.items():
if "_item" in unit:
if k == unit["_item"]:
total += len(v)
elif "_unitClass" in unit:
item = lookup_item_by_code(k)
if item["-unitClass"] == unit["_unitClass"]:
total += len(v)
elif "_subtype" in unit:
item = lookup_item_by_code(k)
if item["-subtype"] == unit["_subtype"]:
total += len(v)
extra["total"] = min(total, int(maximum_total))
return total != progress
def progress_battle_damage_count(action, damage, ally_unit, baddy_unit):
return lambda task, progress, i, extra, *args: \
task["_action"] == action and \
all_lambda(
progress_parameter_implies("_subtype", ally_unit.get("-subtype", "")),
progress_parameter_implies("_unitClass", ally_unit.get("-unitClass", "")),
progress_parameter_implies("_item", ally_unit.get("-code", "")),
progress_nested_parameter_implies("targetInfo", "_unitClass", baddy_unit.get("-unitClass", "")),
progress_nested_parameter_implies_contains("targetInfo", "_unitType",
baddy_unit.get("unit", {}).get("-type", ""))
)(task, progress, i, extra, *args) \
and progress_battle_damage(damage, task["_total"], extra, progress) \
and progress < int(task["_total"])
def progress_battle_damage(damage, maximum_total, extra, progress):
extra["yield"] = min(damage, int(maximum_total))
return True
def progress_resource_added_count(rewards, prefix):
standard_resources = ["coins", "oil", "wood", "aluminum", "copper", "gold", "iron", "uranium"]
ores = ["aluminum", "copper", "gold", "iron", "uranium"]
rares = {"rare": 0, "nrare0": 0, "nrare1": 1, "nrare2": 2, "nrare3": 3, "nrare4": 4}
resource_type = session['user_object']["userInfo"]["player"]["playerResourceType"]
sorted_ores = ores[resource_type - 3:] + ores[:resource_type - 3]
# resources[standard_resources[int(market["item"])]]
return lambda task, progress, i, extra, *args: \
task["_action"] == "resourceAdded" and ((rewards.get(prefix + task["_type"]) \
and progress_yield_amount(str(rewards[prefix + task["_type"]]).split('|')[0], task["_total"], extra, progress)) \
or (task["_type"] in rares and rewards.get(prefix + sorted_ores[rares[task["_type"]]]) \
and progress_yield_amount(str(rewards[prefix + sorted_ores[rares[task["_type"]]]]).split('|')[0], task["_total"], extra, progress)))
def progress_market_added_count(amount):
return lambda task, progress, i, extra, *args: \
task["_action"] == "marketAdd" and \
progress_parameter_implies("_item", "rare") and \
progress_total_amount(amount,task["_total"], extra, progress)
def progress_total_amount(amount, maximum_total, extra, progress):
extra["total"] = min(int(amount), int(maximum_total))
return amount != progress
def progress_yield_amount(amount, maximum_total, extra, progress):
extra["yield"] = min(int(amount), int(maximum_total))
return amount != progress
#cancels?
def progress_build(state, state_machine, game_item, step, previous_state, reference_item, previous_reference_item, *state_args):
return lambda task, progress, i, *args: \
task["_action"] == "build" and reference_item is not None and (
reference_item.split(":")[0] in task.get("_item", "").split(',') or
progress_parameter_equals("_resourceType",
lookup_item_by_code(reference_item.split(":")[0]).get("-resourceType", ""))(task, progress, i, *args)
or all_lambda(progress_parameter_equals("_isUpgrade", "true"),
lambda *args: lookup_item_by_code(reference_item.split(":")[0]).get("-type","upgrade"),
progress_nested_parameter_implies("unit", "_subtype", lookup_item_by_code(
reference_item.split(":")[1]).get("-subtype", "") if len(
reference_item.split(":")) > 1 else "")
)(task, progress, i, *args)
) \
and previous_reference_item == None
def progress_harvest(state, state_machine, game_item, step, previous_state, reference_item, previous_reference_item, *state_args):
return lambda task, progress, i, *args: \
task["_action"] == "harvest" and previous_reference_item is not None and (
previous_reference_item.split(":")[0] in task.get("_item", "").split(',') or
progress_parameter_equals("_subtype", lookup_item_by_code(previous_reference_item.split(":")[0]).get("-subtype",""))(task, progress, i, *args)
or all_lambda(progress_parameter_equals("_isUpgrade", "true"),
lambda *args: lookup_item_by_code(previous_reference_item.split(":")[0]).get("-type","upgrade"),
progress_nested_parameter_implies("unit", "_subtype", lookup_item_by_code(previous_reference_item.split(":")[1]).get("-subtype","") if len(previous_reference_item.split(":")) > 1 else "")
)(task, progress, i, *args)
) \
and reference_item == None
def progress_auto_complete():
return lambda task, *args: task["_action"] in ["autoComplete", "population"]
def progress_place(state, state_machine, game_item, step, *state_args):
return lambda task, progress, i, *args: \
task["_action"] in ["place", "countPlacements"] and task.get("_item", task.get('_code')) == game_item['-code'] and progress < int(task["_total"]) and step == "place"
def progress_place_unit(state, state_machine, game_item, step, *state_args):
return lambda task, progress, i, *args: \
task["_action"] in ["countPlaced"] and task.get("_unitClass", "NONE") == game_item.get('-unitClass', "OTHER") and progress < int(task["_total"]) and step == "place"
def progress_state(state, state_machine, game_item, step, *state_args):
return lambda task, progress, i, *args: \
task["_action"] in ["state", "countState"] and '-stateName' in state and state['-stateName'] in task["_state"].split(',') and ("_item" not in task or task["_item"] == game_item['-code'])\
and ("_subtype" not in task or task["_subtype"] == game_item['-subtype']) and progress < int(task["_total"])
# def all_lambda(lambdas, *initializer):
# return lambda *args: all([l(*initializer)(*args) for l in lambdas])
def all_lambda(*lambdas):
return lambda *args: all([l(*args) for l in lambdas])
def progress_action(action):
return lambda task, *args: task["_action"] == action
def progress_parameter_equals(key, value):
return lambda task, *args: task.get(key, "_NO_MATCH_") == value
def progress_parameter_implies(key, value):
return lambda task, *args: task.get(key) == None or task.get(key, "_NO_MATCH_") == value
def progress_nested_parameter_implies(key, key2, value):
return lambda task, *args: task.get(key) == '' or task.get(key, {}).get(key2) == None or task.get(key, {}).get(key2, "_NO_MATCH_") == value
def progress_nested_parameter_implies_contains(key, key2, value):
return lambda task, *args: task.get(key) == '' or task.get(key, {}).get(key2) == None or any(i in task.get(key, {}).get(key2, "_NO_MATCH_").split(",") for i in value.split(","))
def progress_parameter_implies_contains(key, value):
return lambda task, *args: task.get(key) == None or any(
i in task.get(key, "_NO_MATCH_").split(",") for i in value.split(","))
# deprogress functions?
def handle_quest_progress(meta, progress_function):
replenish_energy()
incomplete_quests = [e for e in session['quests'] if e["complete"] == False]
for session_quest in incomplete_quests:
new_quests = []
report_quest = False
tasks = get_tasks(lookup_quest(session_quest['name']))
for task, progress, i in zip(tasks, session_quest['progress'], range(len(session_quest['progress']))):
extra = {"yield": 1}
if progress_function(task, progress, i, extra, session_quest['name']): #countPlaced tasks should be prepopulated with already placed items, however removed ones? precomplete autoComplete?
print("Task", repr(task), "progress", repr(progress), "i", i, "quest_name", session_quest['name'])
report_quest = True
if task['_action'] == 'population':
session_quest['progress'][i] = min(lookup_yield(), int(task["_total"])) # session['population']
else:
session_quest['progress'][i] = extra.get("total", session_quest['progress'][i] + extra["yield"])
print("Task progress", task["_action"])
if session_quest['progress'][i] >= int(task["_total"]):
session_quest["completedTasks"] = session_quest["completedTasks"] | 1 << i
print("Task complete", task["_action"])
if report_quest:
print("completedTasks", session_quest["completedTasks"], "len(tasks)", len(tasks), "calc", 2 ** len(tasks) - 1)
if session_quest["completedTasks"] >= 2 ** len(tasks) - 1:
session_quest["complete"] = True
print("Quest complete", session_quest['name'])
do_quest_rewards(lookup_quest(session_quest['name']), meta)
activate_sequels(session_quest, new_quests, meta)
if report_quest:
if "QuestComponent" not in meta:
meta['QuestComponent'] = []
merge_quest_progress([session_quest] + new_quests, meta['QuestComponent'], "output quest")
merge_quest_progress(new_quests, session['quests'], "session quest")
#meta['QuestComponent'].append(session_quest) ### merge if already in it?
# progress = [0 for e in quest['tasks']]
def get_tasks(quest):
raw_tasks = quest['tasks']['task']
tasks = raw_tasks if isinstance(raw_tasks, list) else [raw_tasks]
return tasks
def simple_list(raw_list):
return (raw_list if isinstance(raw_list, list) else [raw_list]) if raw_list != '' else []
def activate_sequels(session_quest, new_quests, meta):
raw_sequels = lookup_quest(session_quest['name'])['sequels']
sequels = (raw_sequels["sequel"] if isinstance(raw_sequels["sequel"], list) else [
raw_sequels["sequel"]]) if raw_sequels != "" and "sequel" in raw_sequels else []
for sequel in sequels:
new_quest_with_sequels(sequel["_name"], new_quests, meta)
def new_quest_with_sequels(name, new_quests, meta, force=False):
if name in [e['name'] for e in session['quests']]:
print("sequel", name, "already in session quests")
elif new_quests is not None and name in [e['name'] for e in new_quests]:
print("sequel", name, "already in new quests")
else:
q = lookup_quest(name)
if matches_requirement(q) or force:
print("Activating sequel", name)
new_sequel_quest = new_quest(q)
new_quests.append(new_sequel_quest)
if new_sequel_quest["complete"]:
print("Sequel quest precompleted", name)
do_quest_rewards(q, meta)
activate_sequels(new_sequel_quest, new_quests, meta)
activate_unlocked_quests(new_quests, meta)
else:
print("Deferring sequel", name, "due to requirements")
def activate_unlocked_quests(new_quests, meta):
open_quests = [e["name"] for e in session["quests"] if e["complete"] == False]
if len(open_quests) <= 20:
completed_quests = [e["name"] for e in session["quests"] if e["complete"] == True]
quests = [e["name"] for e in session["quests"]]
sc = 0
quest_selection = []
for s, p in prequels.items():
if s not in quests and (not p or any(v in completed_quests for v in p)):
quest = lookup_quest(s)
if matches_requirement(quest):
print(repr(quest))
quest_selection.append(quest)
quest_selection.sort(key=lambda q: (
int(q.get("_priority", "1000")), int(q.get("requiredDate", {}).get("_start", "0/0/0").split("/")[2]),
int(q.get("requiredDate", {}).get("_start", "0/0/0").split("/")[0]),
int(q.get("requiredDate", {}).get("_start", "0/0/0").split("/")[1])))
for quest in quest_selection:
if len(open_quests) + sc > 20: # todo make selection?
print("Skipping " + quest["_name"] + " too many open quests")
else:
new_quest_with_sequels(quest["_name"], new_quests, meta)
sc += 1
print('Unlocked new quests', sc)
else:
print("No unlock quests because there are too many open quests")
def matches_requirement(quest):
#return "requires" in quest and quest["requires"]['_type'] =='level'
return quest is not None and ("requires" not in quest or (quest["requires"]['_type'] =='level'
and int(quest["requires"]['_count']) <= session['user_object']["userInfo"]["player"]["level"])) and \
("_activateExperimentNeeded" not in quest or (quest["_activateExperimentNeeded"] in session['user_object']["experiments"] and
str(session['user_object']["experiments"][quest["_activateExperimentNeeded"]]) in quest["_activateExperimentVariants"].split(','))) and \
not quest["_name"].startswith("QFD") # no daily quests
#TODO or (quest['_questTree'] =='level' and quest['_questTree'] ???
# def autoclick_next_state(state_machine, next_click_state):
# while '-autoNext' in next_click_state and next_click_state['-stateName'] != next_click_state[
# '-autoNext']: # '-clientDuration': '2.0s', '-duration': '0' respect duration for harvest?
# next_state_id = next_click_state['-autoNext'] # not all states have this!! end states? autostate after time?
# next_click_state = lookup_state(state_machine, next_state_id)
# print("auto_next_state:", repr(next_click_state))
def do_quest_rewards(quest, meta):
# TODO: rewardModifier
raw_rewards = quest['reward']
do_rewards("Quest", raw_rewards, meta)
def do_rewards(label, raw_rewards, meta, inc_modifier=lambda a: a, item_modifier=lambda a: a):
rewards = simple_list(raw_rewards)
inc = {r.get("_type", r.get("-type")): inc_modifier(int(r.get('_count', r.get('-count', 1)))) for r in rewards if r.get("_type") != "item" and r.get("-type") != "item"}
items = {r.get("_item", r.get("-item")): item_modifier(int(r.get('_count', r.get('-count', 1)))) for r in rewards if r.get("_type") == "item" or r.get("-type") == "item"}
player = session['user_object']["userInfo"]["player"]
player['energy'] += int(inc.get('energy', 0))
player['xp'] += int(inc.get('xp', 0))
player['cash'] += int(inc.get('cash', 0))
player['socialXpGood'] += int(inc.get('socialXpGood', 0))
player['socialXpBad'] += int(inc.get('socialXpBad', 0))
world = session['user_object']["userInfo"]["world"]
resources = world['resources']
resources['coins'] += int(inc.get('coins', 0))
resources['energy'] += int(inc.get('energy', 0)) #which one? #repleenish!!
resources['oil'] += int(inc.get('oil', 0))
resources['wood'] += int(inc.get('wood', 0))
resource_order = world['resourceOrder']
resources[resource_order[0]] += int(inc.get('rare', 0))
resources[resource_order[0]] += int(inc.get('nrare0', 0))
resources[resource_order[1]] += int(inc.get('nrare1', 0))
resources[resource_order[2]] += int(inc.get('nrare2', 0))
resources[resource_order[3]] += int(inc.get('nrare3', 0))
resources[resource_order[4]] += int(inc.get('nrare4', 0))
level_cash = 0
levels_count = 0
levels = [level for level in game_settings['settings']['levels']['level'] if int(level["-num"]) > player['level'] and int(level["-requiredXP"]) <= player['xp'] ]
for level in levels:
[energy_cap] = [e['-cap'] for e in game_settings['settings']['energycaps']['energycap'] if e['-level'] == level["-num"]]
print("Level increased to", level["-num"], "New energy:", energy_cap)
player['level'] = int(level["-num"])
player['energy'] = int(energy_cap)
resources['energy'] = int(energy_cap)
player['energyMax'] = int(energy_cap)
levels_count += 1
if "reward" in level and level["reward"]["-type"] == "cash":
player['cash'] += int(level["reward"]["-count"])
level_cash += int(level["reward"]["-count"])
create_backup("Level " + level["-num"])
if inc:
print(label, "rewards:", ", ".join(
[label + " " + ("+" if int(increment) > 0 else "") + str(increment) + " (" + str(total) + ")" for
(label, increment, total)
in
[("xp:", inc.get('xp', 0), player['xp']),
("energy:", inc.get('energy', 0), player['energy']),
("coins:", inc.get('coins', 0), resources['coins']),
("oil:", inc.get('oil', 0), resources['oil']),
("wood:", inc.get('wood', 0), resources['wood']),
("cash:", inc.get('cash', 0), player['cash']),
("cash (level):", level_cash, player['cash']),
("levels:", levels_count, player['level']),
("socialXpGood:", inc.get('socialXpGood', 0), player['socialXpGood']),
("socialXpBad:", inc.get('socialXpBad', 0), player['socialXpBad']),
(resource_order[0] + ":", inc.get('rare', 0), resources[resource_order[0]]),
(resource_order[0] + ":", inc.get('nrare0', 0), resources[resource_order[0]]),
(resource_order[1] + ":", inc.get('nrare1', 0), resources[resource_order[1]]),
(resource_order[2] + ":", inc.get('nrare2', 0), resources[resource_order[2]]),
(resource_order[3] + ":", inc.get('nrare3', 0), resources[resource_order[3]]),
(resource_order[4] + ":", inc.get('nrare4', 0), resources[resource_order[4]])
] if int(increment) != 0]))
if items:
item_inventory = session['user_object']["userInfo"]["player"]["inventory"]["items"]
for k,v in items.items():
item_inventory[k] = item_inventory.get(k, 0) + v
print(label, "item rewards:", ", ".join([ k + ": " + str(v) for k,v in items.items()]))
handle_quest_progress(meta, progress_resource_added_count(inc, ""))
if levels:
new_quests = []
if "QuestComponent" not in meta:
meta['QuestComponent'] = []
activate_unlocked_quests(new_quests, meta)
merge_quest_progress(new_quests, meta['QuestComponent'], "output quest")
merge_quest_progress(new_quests, session['quests'], "session quest")
def roll_random():
world = session['user_object']["userInfo"]["world"]
prev_seed = str(world["randSeedW"]) + ', ' + str(world["randSeedZ"])
world["randSeedZ"] = 36969 * (world["randSeedZ"] & 65535) + (world["randSeedZ"] >> 16 & 65535) & 4294967295;
world["randSeedW"] = 18000 * (world["randSeedW"] & 65535) + (world["randSeedW"] >> 16 & 65535) & 4294967295;
print("Seed", prev_seed, "=>", str(world["randSeedW"]) + ', ' + str(world["randSeedZ"]))
return (world["randSeedZ"] << 16) + world["randSeedW"] & 4294967295
def roll_random_float():
number = roll_random() / (2 ** 32 - 1)
number_ = math.floor(number * 10 ** 3) / 10 ** 3
print("random float", number_)
return number_
def roll_random_between(a, b):
f = roll_random_float() * (b - a) + a
print("random between", a ,"and", b, "=", f)
return f
def get_seed_w():
return session['user_object']["userInfo"]["world"]["randSeedW"]
def get_seed_z():
return session['user_object']["userInfo"]["world"]["randSeedZ"]
def roll_reward_random():
world = session['user_object']["userInfo"]["world"]
world["rewardRandSeedZ"] = 36969 * (world["rewardRandSeedZ"] & 65535) + (world["rewardRandSeedZ"] >> 16 & 65535) & 4294967295;
world["rewardRandSeedW"] = 18000 * (world["rewardRandSeedW"] & 65535) + (world["rewardRandSeedW"] >> 16 & 65535) & 4294967295;
print( (world["rewardRandSeedZ"] << 16) + world["rewardRandSeedW"] & 4294967295)
return (world["rewardRandSeedZ"] << 16) + world["rewardRandSeedW"] & 4294967295
def roll_reward_random_float():
number = roll_reward_random() / (2 ** 32 - 1)
return math.floor(number * 10 ** 3) / 10 ** 3
def roll_reward_random_between(a, b):
return roll_reward_random_float() * (b - a) + a
def progress_harvest_consumable(state, state_machine, game_item, step, previous_state, reference_item, previous_reference_item, *state_args):
return lambda task, progress, i, *args: \
task["_action"] in "inventoryAdded" and state.get("-harvestingState") == "1" and reference_item is not None and (
progress_parameter_implies("_type", lookup_item_by_code(reference_item.split(":")[0]).get("-type",""))(task, progress, i, *args) and \
progress_parameter_implies("_subtype", lookup_item_by_code(reference_item.split(":")[0]).get("-subtype",""))(task, progress, i, *args) and \
progress_parameter_implies_contains("_item", reference_item.split(":")[0])(task, progress, i, *args)) \
def progress_buy_consumable(item):
return lambda task, progress, i, *args: \
task["_action"] == "inventoryAdded" and item is not None and \
progress_parameter_implies("_type", item.get("-type", ""))(task, progress, i, *args) and \
progress_parameter_implies("_subtype", item.get("-subtype", ""))(task, progress, i, *args) and \
progress_parameter_implies_contains("_item", item["-code"])(task, progress, i, *args)
def progress_gifted_parts(item, count):
return lambda task, progress, i, extra, *args: \
task["_action"] == "inventoryAdded" and item is not None and \
progress_parameter_implies("_type", item.get("-type", ""))(task, progress, i, *args) and \
progress_parameter_implies("_subtype", item.get("-subtype", ""))(task, progress, i, *args) and \
progress_parameter_implies_contains("_item", item["-code"])(task, progress, i, *args) and \
progress_yield_amount(count, task["_total"], extra, progress)
def progress_useAOA_consumable(item):
return lambda task, progress, i, *args: \
task["_action"] == "useConsumable" and task.get("_neighbor") == "true" and item is not None and \
progress_parameter_implies("_type", item.get("-type", ""))(task, progress, i, *args) and \
progress_parameter_implies("_subtype", item.get("-subtype", ""))(task, progress, i, *args) and \
progress_parameter_implies_contains("_item", item["-code"])(task, progress, i, *args)
def progress_useGeneral_consumable(item,enemy_turn): #DONT USE THIS FUNCTION FOR SOMETHING ELSE
if enemy_turn == False:
item_inventory = session['user_object']["userInfo"]["player"]["inventory"]["items"]
if item["-subtype"] == "secondary":
session['user_object']["userInfo"]["player"]["mana"]["value"]-=int(item["consumable"]["-mana"])
elif session['user_object']["userInfo"]["player"]["tutorialProgress"] != "tut_step_powerUpPowerUsed" and \
session['user_object']["userInfo"]["player"]["tutorialProgress"] != "tut_step_powerUpPowerSelected":
item_inventory[item["-code"]] -= 1
return lambda task, progress, i, *args: \
task["_action"] == "useConsumable" and item is not None and enemy_turn == False and \
progress_parameter_implies("_type", item.get("-type", ""))(task, progress, i, *args) and \
progress_parameter_implies("_subtype", item.get("-subtype", ""))(task, progress, i, *args) and \
progress_parameter_implies_contains("_item", item["-code"])(task, progress, i, *args)