-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentro.py
1943 lines (1648 loc) · 96.4 KB
/
entro.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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pygame
import sys
sys.path.append('tools')
from zx_gfx import (font_sprite_names, font_sprite_data, sprite_names, sprite_data, get_font_sprite_data,
SPRITE_WIDTH, SPRITE_HEIGHT, draw_sprite, draw_font_sprite, sprite_at,
sprint, border, BLACK, BLUE, RED, MAGENTA, GREEN, CYAN, YELLOW, WHITE,
BRIGHT_BLUE, BRIGHT_RED, BRIGHT_MAGENTA, BRIGHT_GREEN, BRIGHT_CYAN, BRIGHT_YELLOW,
BRIGHT_WHITE, PALETTE, CURSOR_FRAME, CURSOR_FLY, CURSOR_CORNER, CURSOR_S, cursor_list)
from gamedata import (wizards, creature_list, creations, spell_list, animation_list, starting_position_data,
F_MOUNT, F_MOUNT_ANY, F_FLYING, F_UNDEAD, F_TREE, F_EXPIRES, F_EXPIRES_SPELL, F_NOCORPSE,
F_INVULN, F_STRUCT, F_ETH, F_ENGULFS, F_SPREADS, FLAGS, corpses, victims,
MIN_WIZARDS, MAX_WIZARDS, MAX_SPELLS)
from enum import Enum
import random, math
pygame.init()
pygame.mixer.init()
# TEST_SPELL = 36
# TODO: Friendly magic trees are causing engagement
# TODO: Investigate flight bug; (mountable?) flyers sometimes get stuck
# TODO: 'Bonus' engagement attack if ending movement engaged
# TODO: Allow ranged attackers to attack after successfully attacking and/or being mounted
# TODO: finish sound
# TODO: Primitive AI: much like the original, lots of random
# TODO: AI: Describe game state through OpenAI API calls to fetch spell selections, spell casting and movement decisions from GPT-4
# TODO: Fix creations dictlist to be more consistent with wizards dictlist
# TODO: Constants and file structure review
# TODO: Non-magic and non-undead ranged attacks should not kill undead
# TODO: Runtime window rescaling: UP/DOWN keys to change RESCALE_FACTOR and re-init window accordingly
# Constants for tile, arena and screen dimensions
CAPTION = 'Entro.py: Battle of Elderly Wizards'
TILE_SIZE = 16
ARENA_COLUMNS, ARENA_ROWS = 15, 10
ARENA_WIDTH, ARENA_HEIGHT = ARENA_COLUMNS * TILE_SIZE, ARENA_ROWS * TILE_SIZE
BORDER_WIDTH = TILE_SIZE
STATUS_LINE_HEIGHT = TILE_SIZE * 1.5
SCREEN_WIDTH = ARENA_WIDTH + 2 * BORDER_WIDTH
SCREEN_HEIGHT = ARENA_HEIGHT + BORDER_WIDTH + STATUS_LINE_HEIGHT
# The original resolution arena is rescaled
RESCALE_FACTOR = 6
RENDER_WIDTH,RENDER_HEIGHT = SCREEN_WIDTH * RESCALE_FACTOR, SCREEN_HEIGHT * RESCALE_FACTOR
X_SCALE, Y_SCALE = RENDER_WIDTH / SCREEN_WIDTH, RENDER_HEIGHT / SCREEN_HEIGHT
# Initialize the screen and game variables
GS_INTRO, GS_SETUP, GS_NAME, GS_MENU, GS_SELECT, GS_CAST, GS_ARENA, GS_INSPECT, GS_INFO, GS_INFO_ARENA, GS_GAME_OVER = range(11) # Game states
main_screen = pygame.display.set_mode((RENDER_WIDTH, RENDER_HEIGHT))
pygame.display.set_caption(CAPTION)
screen = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT)) # This is where we'll render everything initially
clock = pygame.time.Clock()
start_time = pygame.time.get_ticks()
cursor_pos = [0, 0] # Using a mutable list to manage cursor tile position changes on the arena
cursor_type = CURSOR_S
selection = None # Current wizard's arena selection
illusion_checking = False # We're asking whether wizard wants this next creation to be an illusion
dismount_checking = False # We're asking a mounted wizard whether they want to attempt to dismount
rangedCombatTime = False # A ranged combat equipped object just completed its move and should select a target for ranged attack
animations = []
moves_remaining = 0
num_wizards = 2
messageText = ""
current_screen = GS_INTRO
current_wizard = 0 # Used to progress through setup and turns
worldAlignment = 0
newCreations = []
showBases = True
highlightWizard = 0
turn = 1
SOUND_SET = [pygame.mixer.Sound('sound/S60-key_bloop.mp3'), pygame.mixer.Sound('sound/S10-tick.mp3'),
pygame.mixer.Sound('sound/spell_success.mp3'), pygame.mixer.Sound('sound/engaged.mp3'),
pygame.mixer.Sound('sound/sound_effect_22-undead.mp3'), pygame.mixer.Sound('sound/sound_effect_11-walk.mp3'),
pygame.mixer.Sound('sound/sound_effect_21-selected.mp3'), pygame.mixer.Sound('sound/sound_effect_16-explosion.mp3')]
SND_KEY, SND_TICK, SND_SUCCESS, SND_ENGAGED, SND_UNDEAD, SND_WALK, SND_SELECTED, SND_EXPLOSION = SOUND_SET[:8]
sound_channels = {}
sounds = []
def play_sound():
global sounds, sound_channels
if sounds and len(animations) % 2 == 0: sound = sounds.pop() # The animations check ensures that sounds don't get too out of sync with animations
else: return
# Check if the sound is already playing
if sound in sound_channels and sound_channels[sound].get_busy():
while sound_channels[sound].get_busy():
pygame.time.wait(50) # Wait for 50 milliseconds before checking again
sound_channels[sound].play(sound)
else:
# Find an available channel and play the sound
channel = pygame.mixer.find_channel(True)
if channel:
channel.play(sound)
sound_channels[sound] = channel
else:
print("No available channel to play sound.")
def check_engagement(activeObject):
global wizards, creations, messageText, sounds
alreadyEngaged = activeObject['engaged']
neighbours = get_all_neighbours(wizards + creations, activeObject['x'], activeObject['y'])
manoeuvre_rating = activeObject['manvr'] if is_wizard(activeObject) else activeObject['data']['mnv']
# print(f"AP: {activeObject}")
for neighbour in neighbours:
if activeObject['owner'] == neighbour['owner']:
# print(f"Friendlies don't cause engagements ({neighbour['name']})")
continue
if string_in_object(neighbour, F_STRUCT) or string_in_object(neighbour, F_SPREADS) or string_in_object(neighbour, F_EXPIRES_SPELL):
# print("Structures and spreaders don't cause engagements")
continue
roll = random.randint(0,9)
print(f"{activeObject['name']} ({activeObject['owner']}) with MR: {manoeuvre_rating} rolled {roll} trigger: {neighbour['name']} ({neighbour['owner']}) at {neighbour['x']},{neighbour['y']}")
if roll < manoeuvre_rating and (activeObject['owner'] != neighbour['owner']):
messageText = "ENGAGED TO ENEMY"
sounds.append(SND_ENGAGED)
# print(f"Result: True")
return True
# print( f"Neighbours: {[d['name'] for d in neighbours]}" )
# print(f"Result: no change\n")
return alreadyEngaged
def check_los(originObject, x1, y1):
""" This uses the Bresenham line algorithm to incrementally check each grid cell from (x0,y0) to (x1,y1).
If any blocked cell is encountered, it returns False. Otherwise it returns True if LoS is clear.
"""
x0,y0 = originObject['x'], originObject['y']
dx = abs(x1 - x0)
dy = abs(y1 - y0)
if dx + dy == 0: return True # No obstacles at no distance
sx = -1 if x0 > x1 else 1
sy = -1 if y0 > y1 else 1
if dx > dy:
err = dx / 2.0
x = x0 + sx
while x != x1:
if get_obstruction(x, y0, originObject, ignoreEthereals=True):
return False
err -= dy
if err < 0:
y0 += sy
err += dx
x += sx
else:
err = dy / 2.0
y = y0 + sy
while y != y1:
if get_obstruction(x0, y, originObject, ignoreEthereals=True):
return False
err -= dx
if err < 0:
x0 += sx
err += dy
y += sy
return True
def get_spiral_ring(radius):
""" This oddly specific spiral pattern is just an attempt to more authentically
replicate the behaviour of the original Z80 code where it made more sense. """
coords = []
def add(x, y):
# if minWidth <= x <= widthLimit and minHeight <= y <= heightLimit and (x, y) not in coords:
coords.append((a, b))
a,b = 0, radius
while a > 0 - radius:
add(a, b)
a -= 1
while b > 0 - radius: # Left edge
add(a, b)
b -= 1
while a < radius: # Top row left to right
add(a, b)
a += 1
while b < radius: # Right edge
add (a, b)
b += 1
while a > 0: # Closing section of bottom if necessary
add(a, b)
a -= 1
# return coords as a list of mutable lists instead of a list of tuples
return [list(coord_tuple) for coord_tuple in coords]
def get_all_neighbours(list_of_dicts: list, x0: int, y0: int, n: int = 1, ring: bool = True):
neighbours = []
for item in list_of_dicts:
chebyshev_distance = max(abs(item['x'] - x0), abs(item['y'] - y0))
if ring:
# Include if Chebyshev distance is exactly 'n'
if chebyshev_distance == n:
neighbours.append(item)
else:
# Include if within 'n' Chebyshev distance
if chebyshev_distance <= n:
neighbours.append(item)
return neighbours
def get_random_neighbour_location(x, y, grid_width, grid_height):
# Generate the set of valid neighbouring coordinates
neighbours = [(x + dx, y + dy) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]
if 0 <= x + dx < grid_width and 0 <= y + dy < grid_height]
# Return a random neighbour
return random.choice(neighbours)
def spread_spreaders():
global creations, victims
for creation in creations:
# We use 'has_moved' flag to indicate freshly created elements shouldn't replicate in the same turn
if F_SPREADS in creation['data']['status'] and not creation['has_moved']:
print(f"found a spreader at {creation['x']},{creation['y']}")
if random.randint(1, 10) <= 9: # 90% chance of spreading
# Spreading
(newX, newY) = get_random_neighbour_location(creation['x'], creation['y'], ARENA_COLUMNS, ARENA_ROWS)
victim = get_obstruction(newX, newY)
if victim:
if not is_wizard(victim): # Some things can't be burned or engulfed but wizards aren't one of them
if any(s in victim['data']['status'] for s in [F_SPREADS, F_STRUCT, F_TREE]): continue
# Different spreaders behave differently
if (F_ENGULFS not in creation['data']['status']):
# Lethal spreader e.g. fire
rider = get_rider(victim)
if rider: kill(rider)
else: kill(victim)
# Fire clears corpses too:
for corpse in corpses:
if corpse['x'] == newX and corpse['y'] == newY: corpses.remove(corpse)
continue # to next element
else:
# Non-lethal spreader e.g. Blobs, which avoid wizards and mounted mounts
if (is_wizard(victim) or get_rider(victim)):
# This blob will not engulf this wizard, whether on foot mounted
continue
else:
# Everything else, except the permanent exclusions, gets gobbled
victims.append(victim)
kill_creation(victim) # Not really killed, just buried
print(f"{victim['name']} overwhelmed by {creation['name']}")
# Victim or not, we are still creating a new element
print(f"New {creation['name']} at {newX},{newY}")
create_creation(creation['name'], creation['owner'], newX, newY, False, True)
if random.randint(1,10) <= 1: # Also 10% chance of disappearing
print(f"{creation['name']} expires")
kill_creation(creation, False)
# Liberate blob victim
for victim in victims:
if (creation['x'], creation['y']) == (victim['x'], victim['y']):
print(f"{victim['name']} liberated!")
creations.append(victim)
victims.remove(victim)
# We've done spreaders. We'll squeeze expirations in here too
run_expirations()
return
def run_expirations():
""" Checking magic trees and castles for expiration """
# Loop through creations looking for F_EXPIRES and F_EXPIRES_SPELL flags
for creation in creations:
if F_EXPIRES in creation['data']['status']:
if random.randint(1,10) <= 2: # 20% chance of disappearing
if F_EXPIRES_SPELL in creation['data']['status']:
for wizard in wizards:
if wizard['x'] == creation['x'] and wizard['y'] == creation['y'] and wizard['mounted']:
print(f"{wizard['name']} has {len(wizard['spell_book'])} spells")
if len(wizard['spell_book']) < MAX_SPELLS:
wizard['spell_book'].append(random.choice(spell_list[2:][:-1]))
messageText = f"NEW SPELL FOR {wizard['name']} ({wizard['spell_book'][-1]['spell_name']})"
print(messageText)
else: print('spell blocked')
print(f"{creation['name']} expires")
kill_creation(creation, False)
break
else:
print(f"{creation['name']} expires")
kill_creation(creation, False, True)
def get_world_alignment_string():
global worldAlignment
if worldAlignment > 0: return f"(LAW {'↥' * (worldAlignment - 1)})"
elif worldAlignment < 0: return f"(CHAOS {'*' * (abs(worldAlignment) - 1)})"
else: return ""
def get_sprite_info(name):
global animation_list
# Convert the name parameter to lowercase and replace spaces with underscores to match the format
name = name.replace(' ', '_').lower()
# Search for the matching animation by name
for animation in animation_list:
if animation['name'] == name:
# Return the sprites list if the name matches
return animation['sprites']
# Return an empty list if no match is found
return []
def clean_label(label):
return label.replace('_',' ').title()
def have_same_sign(a, b):
return (a > 0 and b > 0) or (a < 0 and b < 0) or (a == 0 and b == 0)
def get_alignment_character(ChaosValue: int) -> str:
if ChaosValue>0:return '↥'
elif ChaosValue==0:return '-'
return '*'
def get_cast_chance(wizardID: int, spell = None):
global worldAlignment, wizards
if not spell: # No spell specified; assume selected
spell = wizards[wizardID]['selected']
chance = spell['chance']
if have_same_sign(worldAlignment ,spell['law']):
chance = chance + (abs(worldAlignment) // 4)
# Add wizard's ability and clamp 0-9
chance = max(1, min(chance + wizards[wizardID]['ability'], 9))
# print(chance)
return chance + 1
def get_chance_color(chance: int):
return PALETTE[2 + (chance // 2)]
def unpack_coordinates(sequential_position, num_columns=15, num_rows=10) -> tuple:
"""
Convert a sequential position number to x, y coordinates in a 15x10 arena.
Parameters:
- sequential_position: The sequential position (0-indexed)
- num_columns: The number of columns in the arena
- num_rows: The number of rows in the arena
Returns:
- A tuple of (x, y) coordinates
"""
# if sequential_position < 0 or sequential_position >= num_columns * num_rows:
# raise ValueError("Sequential position is out of bounds for the arena size")
x = sequential_position % num_columns
y = sequential_position // num_columns
return x, y
def highest_survivor():
indices = [index for index, item in enumerate(wizards) if not item.get('defeated', True)]
# print(f"Highest Survivor: {wizards[max(indices)]['name']}")
return max(indices) if indices else None
def nextWizard():
global wizards, current_wizard, num_wizards, cursor_pos, cursor_type, current_screen, messageText, turn
if current_wizard == highest_survivor():
# New round
current_wizard = 1
if current_screen == GS_ARENA: turn += 1
else:
current_wizard += 1
while wizards[current_wizard]['defeated']: nextWizard()
if current_screen == GS_CAST:
if wizards[current_wizard]['selected']:
messageText = clean_label(wizards[current_wizard]['selected']['label'])
cursor_type = CURSOR_S
cursor_pos = [ wizards[current_wizard]['x'], wizards[current_wizard]['y'] ]
messageText = f"{wizards[current_wizard]['name']}"
if wizards[current_wizard]['selected']: messageText += f" {clean_label(wizards[current_wizard]['selected']['label'])}" + (f" {wizards[current_wizard]['selected']['distance']}" if wizards[current_wizard]['selected']['distance'] > 0 else "") + (f" ({wizards[current_wizard]['multicast']})" if wizards[current_wizard]['multicast'] > 1 else "") # spell label or blank
elif current_screen == GS_ARENA:
cursor_type = CURSOR_FRAME
cursor_pos = [ wizards[current_wizard]['x'], wizards[current_wizard]['y'] ]
messageText = f"{wizards[current_wizard]['name']}'s turn"
print(f"turn: {turn} current_screen: {current_screen} current_wizard: {current_wizard} ")
return
if current_screen == GS_CAST:
if wizards[current_wizard]['selected']:
messageText = clean_label(wizards[current_wizard]['selected']['label'])
cursor_type = CURSOR_S
def prepare_wizards():
global wizards, num_wizards
this_wizard = 1
while this_wizard <= num_wizards:
level = wizards[this_wizard]['level']
wizards[this_wizard]['combat'] = (random.randint(0, 9) // 2) + 1 + (level // 2)
wizards[this_wizard]['defense'] = (random.randint(0, 9) // 2) + 1 + (level // 2)
wizards[this_wizard]['manvr'] = (random.randint(0, 9) // 2) + 3 + (level // 4)
wizards[this_wizard]['magic resistance'] = (random.randint(0, 9) // 4) + 6
wizards[this_wizard]['ability'] = (level // 2) + random.randint(0, 1)
wizards[this_wizard]['defeated'] = False
# All wizards:
wizards[this_wizard]['spell_book'] = [spell_list[0],spell_list[1]] # Everyone gets Disbelieve and Meditate
try:
if TEST_SPELL: wizards[this_wizard]['spell_book'] += [spell_list[TEST_SPELL]] # Everyone gets the test spell
except:
print("No test spell has been set")
wizards[this_wizard]['spell_book'] += [random.choice(spell_list[2:][:-1]) for _ in range( min(20,(random.randint(0,9) // 2) + 10 + level // 2) )]
this_wizard += 1
def prepare_starting_positions():
global wizards, num_wizards
positions = starting_position_data[num_wizards - 2] # Starting positions table rows start with 2 players
# print(positions)
for i, position in enumerate(positions):
wizards[i + 1]['x'], wizards[i + 1]['y'] = unpack_coordinates(position + 17, ARENA_COLUMNS + 1)
# print(f"{wizards[i+1]['name']} starts at {wizards[i+1]['x']},{wizards[i+1]['y']}")
def get_creature_frames(creatureName: str):
global animation_list
for creature in animation_list:
if creature['name'] == creatureName: return creature['frames']
def get_distance(point1: list, point2: list) -> float:
""" Not using Manhattan, Chebyshev or Pythagorean. Nope.
We're using my take on the Gollop algorithm. """
x0, y0 = point1
x1, y1 = point2
# Calculate horizontal and vertical distances
dx = abs(x1 - x0)
dy = abs(y1 - y0)
# Determine the number of diagonal moves
diagonal_moves = min(dx, dy)
# Calculate the remaining straight moves
straight_moves = abs(dx - dy)
# Sum up the distances
gollop_distance = math.floor(diagonal_moves * 1.5 + straight_moves)
return gollop_distance
def get_collisions(list_of_dicts, x, y):
# Return a list of collisions at these coordinates
matching_items = [d for d in list_of_dicts if d.get('x') == x and d.get('y') == y]
return matching_items
def select_at(x,y, includeCorpses: bool = False):
# Returns a single collision for selection or targeting
objectList = wizards + creations
if includeCorpses: objectList += corpses
potential_selections = get_collisions(objectList, cursor_pos[0], cursor_pos[1])
# potential_selections = get_all_collisions(cursor_pos[0], cursor_pos[1], includeCorpses)
if potential_selections:
selection = potential_selections[-1]
else:
selection = None
return(selection)
def get_obstruction(x, y, ignoreSubject=None, ignoreEthereals: bool = False):
# Returns single object from wizards and creations, optionally ignoring the subject and/or ethereal creatures
if ignoreEthereals:
matching_items = [d for d in creations
if d['x'] == x and d['y'] == y
and d != ignoreSubject
and not d.get('mounted')
and not F_ETH in d['data']['status']]
matching_items += [d for d in wizards
if d['x'] == x and d['y'] == y
and d != ignoreSubject
and not d.get('mounted')]
else:
matching_items = [d for d in wizards + creations
if d['x'] == x and d['y'] == y
and d != ignoreSubject
and not d.get('mounted')]
if matching_items:
return matching_items[0]
return None
def remove_spell(wizard: int, spell_name: str):
for spell in wizards[wizard]['spell_book']:
if spell.get('spell_name') == spell_name:
wizards[wizard]['spell_book'].remove(spell)
break # Return early if the item is found and removed
def create_creation(creatureName: str, owner: int, x: int, y: int, illusion: bool = False, hasMoved: bool = True):
""" Note that creations are shifted from newCreations to Creations during the draw_animations() call """
global newCreations
data = get_creature_stats(creatureName)
newCreations += [
{'name': creatureName,
'owner': owner,
'frame_set': get_creature_frames(creatureName),
'x': x,
'y': y,
'illusion': illusion,
'has_moved': hasMoved,
'engaged': False,
'disbelieved': False,
'data': data}]
return
def kill_creation(target, generateCorpse: bool = True, forceInvulnerableDestruction: bool = False):
global creations, corpses
for creation in creations:
if target == creation:
if (F_INVULN not in creation['data']['status']) or forceInvulnerableDestruction:
if F_MOUNT in creation['data']['status'] or F_MOUNT_ANY in creation['data']['status']:
mounted_wizards = [d for d in wizards if d['x'] == target['x'] and d['y'] == target['y'] and d['mounted']]
if mounted_wizards:
mounted_wizards[0]['mounted'] = False
if generateCorpse and (F_NOCORPSE not in creation['data']['status']):
print(f"Corpse appeared at {creation['x']},{creation['y']}")
corpses.append(creation)
creations.remove(creation)
return True
return False
def kill_wizards_creations(thisWizard: int):
global creations
for creation in creations:
if creation['owner'] == thisWizard:
animations.append({'title': 'woop', 'rate': 30, 'x': creation['x'], 'y': creation['y'], 'frame_set': [("woop" + str(i), PALETTE[wizards[thisWizard]['palette']]) for i in range(1,10)], 'destination': None})
if F_MOUNT_ANY in creation['data']['status'] or F_MOUNT in creation['data']['status']:
if get_rider(creation):
dismount(thisWizard, creation['x'], creation['y'])
creations.remove(creation)
return
def kill_wizard(thisWizard: int):
global wizards, current_screen
print(f"Wizard {wizards[thisWizard]['name']} dying! 'x': {wizards[thisWizard]['x']}, 'y': {wizards[thisWizard]['y']}")
animations.append({'title': 'woop', 'rate': 30, 'x': wizards[thisWizard]['x'], 'y': wizards[thisWizard]['y'], 'frame_set': [("woop" + str(i), PALETTE[wizards[thisWizard]['palette']]) for i in range(1,10)], 'destination': None})
kill_wizards_creations(thisWizard)
wizards[thisWizard]['defeated'] = True
wizards[thisWizard]['mounted'] = True # Also ensures no attempt to draw them in arena
wizards[thisWizard]['x'], wizards[thisWizard]['y'] = 255, 255
# Game Over check:
survivors = len([w for w in wizards if w['defeated'] is False])
print(f"Survivors: {survivors} out of {num_wizards}")
if survivors == 1:
# Victory!
current_screen = GS_GAME_OVER
print(f"Victory for {[w['name'] for w in wizards if w['defeated'] is False]}!")
return True
def kill(target, generateCorpse: bool = True):
""" Kills either a wizard or a creation """
return kill_wizard(target['owner']) if is_wizard(target) else kill_creation(target, generateCorpse)
def attack(target, attack_stat: int, magical: bool = False):
global creations, wizards
if is_wizard(target): # Target is a wizard!
defence = target['magicRes'] if magical else target['defence']
else: # Target is a creation
defence = target['data']['res'] if magical else target['data']['def']
attack_roll = attack_stat + random.randint(0,6)
defence_roll = defence + random.randint(0,6)
print(f"[{target['name']} attacked] Attacker: {attack_roll}({attack_stat}) Defender: {defence_roll}({defence}) Result: {('Succeeds' if attack_roll >= defence_roll else 'Fails')}")
# sounds.append(SND_ATTACK)
return True if attack_roll >= defence_roll else False
def melee_attack(target, attack_stat: int, magical: bool = False):
global creations, wizards
animations.append({'title': 'attack', 'rate': 20, 'x': target['x'], 'y': target['y'], 'frame_set': [("attack" + str(i), BRIGHT_CYAN) for i in range(1,5)], 'destination': None})
success = attack(target, attack_stat, magical)
if success:
if kill(target):
print(f"{target['name']} destroyed")
return True
return False
def string_in_object(dicts, target: str):
"""
Recursively checks if a target string is present in a list of dictionaries, including nested dictionaries and lists.
Args:
dicts (list): A list of dictionaries (or lists) to search through.
target (str): The string to search for.
Returns:
bool: True if the target string is found, False otherwise.
This function iterates through each element in the list `dicts`. If an element is a dictionary, it checks each of its values.
If the value is the target string, it returns True. If the value is another list or dictionary, it calls itself recursively on that value.
If an element is a list, the function calls itself recursively on that list.
"""
if isinstance(dicts, dict):
for value in dicts.values():
if target == value or string_in_object(value, target):
return True
elif isinstance(dicts, list):
for item in dicts:
if target == item or string_in_object(item, target):
return True
return False
def adjacent_tree_check(x,y):
neighbours = get_all_neighbours(creations + newCreations, x, y)
if string_in_object(neighbours, F_TREE):
return True
return False
def cast_attempt():
buffs = ['magic_sword_spell', 'magic_knife_spell', 'magic_armour_spell', 'magic_shield_spell', 'magic_wings_spell', 'magic_bow_spell']
global cursor_pos, wizards, current_wizard, creations, messageText, animations, worldAlignment, selection, sounds
def spell_succeeded(count: int = 1, removeSpell = True):
global wizards, worldAlignment
worldAlignment += wizards[current_wizard]['selected']['law']
if removeSpell: remove_spell(current_wizard, wizards[current_wizard]['selected']['spell_name'])
messageText = "SPELL SUCCEEDS"
wizards[current_wizard]['multicast'] = 0
wizards[current_wizard]['selected'] = None
for i in range(0, count):
sounds.append(SND_SUCCESS)
return
def spell_failed(removeSpell = True):
if removeSpell: remove_spell(current_wizard, wizards[current_wizard]['selected']['spell_name'])
messageText = "SPELL FAILS"
wizards[current_wizard]['selected'] = None
return
def spell_test():
chance = get_cast_chance(current_wizard)
roll = random.randint(0,100)
if roll <= chance * 10:
print(f"Success ({roll} / {chance * 10}%)")
return True
else:
print(f"Failure ({roll} / {chance * 10}%)")
return False
# Range check
distance = get_distance( [wizards[current_wizard]['x'], wizards[current_wizard]['y']], cursor_pos )
print(f"Distance: {distance} Limit: {wizards[current_wizard]['selected']['distance']}")
if (distance > wizards[current_wizard]['selected']['distance']) and wizards[current_wizard]['selected']['distance'] != 0:
messageText = "OUT OF RANGE"
return False
# Line of Sight check; note exemptions
if 'dark_power_spell' not in wizards[current_wizard]['selected']['spell_name'] and wizards[current_wizard]['selected']['spell_name'] != 'disbelieve':
if not check_los(wizards[current_wizard], cursor_pos[0], cursor_pos[1]):
messageText = "NO LINE OF SIGHT"
return False
if 'disbelieve' in wizards[current_wizard]['selected']['spell_name']:
collisions = get_collisions(creations, cursor_pos[0], cursor_pos[1])
if collisions:
if collisions[0]['illusion']:
# print(f"Illusion to be destroyed! ({collisions[0]['name']})")
kill_creation(collisions[0], False)
animations.append({'title': 'explosion', 'rate': 30, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("explosion" + str(i), PALETTE[random.randint(1,7)]) for i in range(0,7)], 'destination': None})
sounds.append(SND_EXPLOSION)
spell_succeeded(1, False)
else:
spell_failed(False)
animations.append({'title': 'attack', 'rate': 20, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("attack" + str(i), PALETTE[random.randint(1,7)]) for i in range(1,5)], 'destination': None})
animations.append({'title': 'beam', 'rate': 10, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'dest_x': cursor_pos[0], 'dest_y': cursor_pos[1], 'colour': BRIGHT_WHITE})
return True
else: return False
elif 'meditate' in wizards[current_wizard]['selected']['spell_name']:
# chance = get_cast_chance(current_wizard)
# print(f"Meditate chance: {chance * 10}%")
if spell_test() and len(wizards[current_wizard]['spell_book']) < MAX_SPELLS:
wizards[current_wizard]['spell_book'].append(random.choice(spell_list[2:][:-1]))
animations.append({'title': 'spell', 'rate': 200, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'frame_set': [("attack" + str(i), PALETTE[random.randint(1,14)]) for i in range(1,5)], 'destination': None})
spell_succeeded(1, False)
else:
spell_failed(False)
wizards[current_wizard]['has_moved'] = True
# if wizards[current_wizard]['mounted'] == True:
# TODO: Set mount's has_moved to True if mounted
return True
elif 'creature_cast_spell' in wizards[current_wizard]['selected']['spell_name']:
if not wizards[current_wizard]['illusion']:
if not spell_test():
animations.append({'title': 'summon', 'rate': 20, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("twirl" + str(i), PALETTE[random.randint(1,7)]) for i in range(10)] + [('twirl0', BRIGHT_WHITE)], 'destination': None})
spell_failed()
return True # Even though the spell failed, the attempt has successfully completed
obstructions = [d for d in wizards + creations if d.get('x') == cursor_pos[0] and d.get('y') == cursor_pos[1]]
if obstructions:
print(f"Can't cast over {obstructions[0]['name']}")
return False
animations.append({'title': 'summon', 'rate': 20, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("twirl" + str(i), PALETTE[random.randint(1,7)]) for i in range(10)] + [('twirl0', BRIGHT_WHITE)], 'destination': None})
animations.append({'title': 'beam', 'rate': 5, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'dest_x': cursor_pos[0], 'dest_y': cursor_pos[1], 'colour': CYAN})
create_creation(get_creature_name_from_spell(wizards[current_wizard]['selected']['spell_name']),
current_wizard, cursor_pos[0], cursor_pos[1], wizards[current_wizard]['illusion'], False)
spell_succeeded()
return True
elif wizards[current_wizard]['selected']['spell_name'] in buffs:
# Buff spell
animations.append({'title': 'spell', 'rate': 10, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'frame_set': [("attack" + str(i), PALETTE[random.randint(1,7)]) for i in range(1,5)], 'destination': None})
if not spell_test():
spell_failed()
return True
if buffs[0] in wizards[current_wizard]['selected']['spell_name']:
# Sword
wizards[current_wizard]['frame_set'] = [('modwizard' + str(i), PALETTE[wizards[current_wizard]['palette']]) for i in range(0, 3)]
wizards[current_wizard]['combat'] += 4
wizards[current_wizard]['armed'] = True
elif buffs[1] in wizards[current_wizard]['selected']['spell_name']:
# Knife
wizards[current_wizard]['frame_set'] = [('modwizard' + str(i), PALETTE[wizards[current_wizard]['palette']]) for i in range(3, 6)]
wizards[current_wizard]['combat'] += 2
wizards[current_wizard]['armed'] = True
elif buffs[2] in wizards[current_wizard]['selected']['spell_name']:
# Armour
wizards[current_wizard]['frame_set'] = [('modwizard6', PALETTE[wizards[current_wizard]['palette']])]
wizards[current_wizard]['defence'] = 8
elif buffs[3] in wizards[current_wizard]['selected']['spell_name']:
# Shield
wizards[current_wizard]['frame_set'] = [('modwizard7', PALETTE[wizards[current_wizard]['palette']])]
wizards[current_wizard]['defence'] += 2
elif buffs[4] in wizards[current_wizard]['selected']['spell_name']:
# Wings
wizards[current_wizard]['flying'] = True
wizards[current_wizard]['movement'] = 6
wizards[current_wizard]['frame_set'] = [('modwizard' + hex(i)[2:].upper(), PALETTE[wizards[current_wizard]['palette']]) for i in range(8, 11)]
elif buffs[5] in wizards[current_wizard]['selected']['spell_name']:
# Bow
wizards[current_wizard]['rangedCombat'] = 3
wizards[current_wizard]['rangedCombatRange'] = 6
wizards[current_wizard]['frame_set'] = [('modwizard' + hex(i)[2:].upper(), PALETTE[wizards[current_wizard]['palette']]) for i in range(11, 15)]
else:
print('uncaught buff')
return False
spell_succeeded()
return True
elif 'chaos_law_spell' in wizards[current_wizard]['selected']['spell_name']:
spell_succeeded()
return True
elif 'shadow_form_spell' in wizards[current_wizard]['selected']['spell_name']:
animations.append({'title': 'spell', 'rate': 10, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'frame_set': [("attack" + str(i), PALETTE[random.randint(1,7)]) for i in range(1,5)], 'destination': None})
if not spell_test():
spell_failed()
return True
wizards[current_wizard]['movement'] = 3
wizards[current_wizard]['shadow'] = True
wizards[current_wizard]['frame_set'] = [('', PALETTE[wizards[current_wizard]['palette']]), ('', BLACK)]
spell_succeeded()
return True
elif 'lightning_spell' in wizards[current_wizard]['selected']['spell_name']:
animations.append({'title': 'beam', 'rate': 90, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'dest_x': cursor_pos[0], 'dest_y': cursor_pos[1], 'colour': BRIGHT_BLUE})
attack_stat = 4 if 'Magic Bolt' in wizards[current_wizard]['selected']['spell_name'] else 8
attack_stat += wizards[current_wizard]['ability']
collisions = get_collisions(creations, cursor_pos[0], cursor_pos[1])
if collisions:
animations.append({'title': 'attack', 'rate': 20, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("attack" + str(i), BRIGHT_BLUE) for i in range(1,5)], 'destination': None})
if attack(collisions[0], attack_stat, True):
kill(collisions[0], False)
animations.append({'title': 'explosion', 'rate': 30, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("explosion" + str(i), BRIGHT_WHITE) for i in range(0,7)], 'destination': None})
spell_succeeded()
return True
spell_failed()
return True
elif 'subversion_spell' in wizards[current_wizard]['selected']['spell_name']:
animations.append({'title': 'beam', 'rate': 10, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'dest_x': cursor_pos[0], 'dest_y': cursor_pos[1], 'colour': PALETTE[wizards[current_wizard]['palette']]})
collisions = get_collisions(creations, cursor_pos[0], cursor_pos[1])
if collisions:
if get_rider(collisions[0]):
print(f"Can't subvert a ridden mount")
spell_failed()
return True
if spell_test():
collisions[0]['owner'] = current_wizard
print(f"{collisions[0]['name']} has defected to {wizards[current_wizard]['name']}!")
animations.append({'title': 'attack', 'rate': 20, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("attack" + str(i), PALETTE[wizards[current_wizard]['palette']]) for i in range(1,5)], 'destination': None})
spell_succeeded()
else:
spell_failed()
return True
return False
elif 'raise_dead_spell' in wizards[current_wizard]['selected']['spell_name']:
animations.append({'title': 'beam', 'rate': 1, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'dest_x': cursor_pos[0], 'dest_y': cursor_pos[1], 'colour': MAGENTA})
collisions = get_collisions(corpses, cursor_pos[0], cursor_pos[1])
if collisions:
if spell_test():
creatures.append(collsion[0])
corpses.remove(collision[0])
ceatures[-1]['owner'] = current_wizard
creatures[-1]['data']['status'].append(F_UNDEAD)
print(f"{creatures[-1]['name']} has been raised by {wizards[current_wizard]['name']}!")
animations.append({'title': 'attack', 'rate': 2, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("attack" + str(i), MAGENTA) for i in range(1,5)], 'destination': None})
spell_succeeded()
else: spell_failed()
return True
return False
elif 'wall_spell' in wizards[current_wizard]['selected']['spell_name']:
castsRemaining = wizards[current_wizard]['multicast']
messageText = f"{wizards[current_wizard]['name']} {clean_label(wizards[current_wizard]['selected']['label'])}" + (f" {wizards[current_wizard]['selected']['distance']}" if wizards[current_wizard]['selected']['distance'] > 0 else "") + (f" ({wizards[current_wizard]['multicast']})" if wizards[current_wizard]['multicast'] > 1 else "")
print(f"{wizards[current_wizard]['name']} casting {wizards[current_wizard]['selected']['spell_name']} ({castsRemaining})")
if select_at(cursor_pos[0], cursor_pos[1]) :
return False
if not spell_test:
animations.append({'title': 'beam', 'rate': 5, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'dest_x': cursor_pos[0], 'dest_y': cursor_pos[1], 'colour': CYAN})
castsRemaining = 0
spell_failed()
return True
animations.append({'title': 'summon', 'rate': 20, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("twirl" + str(i), PALETTE[random.randint(1,7)]) for i in range(10)] + [('twirl0', BRIGHT_WHITE)], 'destination': None})
animations.append({'title': 'beam', 'rate': 5, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'dest_x': cursor_pos[0], 'dest_y': cursor_pos[1], 'colour': CYAN})
create_creation('wall', current_wizard, cursor_pos[0], cursor_pos[1], False, False)
if castsRemaining <= 1:
spell_succeeded()
return True
else:
wizards[current_wizard]['multicast'] -= 1
print(f"Casts remaining: {wizards[current_wizard]['multicast']}")
return False
elif 'trees_castles_spell' in wizards[current_wizard]['selected']['spell_name']:
castsRemaining = wizards[current_wizard]['multicast']
messageText = f"{wizards[current_wizard]['name']} {clean_label(wizards[current_wizard]['selected']['label'])}" + (f" {wizards[current_wizard]['selected']['distance']}" if wizards[current_wizard]['selected']['distance'] > 0 else "") + (f" ({wizards[current_wizard]['multicast']})" if wizards[current_wizard]['multicast'] > 1 else "") # spell label or blank
print(f"{messageText}")
if not spell_test:
# Failed
if F_EXPIRES_SPELL not in data['status']: animations.append({'title': 'beam', 'rate': 5, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'dest_x': cursor_pos[0], 'dest_y': cursor_pos[1], 'colour': CYAN})
castsRemaining = 0
spell_failed()
return True
creatureName = get_creature_name_from_spell(wizards[current_wizard]['selected']['spell_name'])
data = get_creature_stats(creatureName)
if F_EXPIRES_SPELL in data['status']:
# Auto cast Magic Woods: Proceed through progressively further away rings (squares with a hole) around the centre
for radius in range(1, wizards[current_wizard]['selected']['distance']):
# ring = get_ring(wizards[current_wizard]['x'], wizards[current_wizard]['y'], radius, 1, 1) # Get a list of mutable lists describing a square ring n tiles away
ring = get_spiral_ring(radius)
for location in ring:
locX, locY = location[0] + wizards[current_wizard]['x'], location[1] + wizards[current_wizard]['y']
obstruction = get_obstruction(locX, locY)
if not check_los(wizards[current_wizard], locX, locY):
continue
if obstruction:
continue # Something in the way
if adjacent_tree_check(locX, locY):
continue
if locX < 2 or locX > ARENA_COLUMNS - 1:
continue # outside horizontal bounds
if locY < 2 or locY > ARENA_ROWS - 1:
continue # outside vertical bounds
# placement
animations.append({'title': 'summon', 'rate': 20, 'x': locX, 'y': locY, 'frame_set': [("twirl" + str(i), PALETTE[random.randint(1,7)]) for i in range(10)] + [('twirl0', BRIGHT_WHITE)], 'destination': None})
animations.append({'title': 'beam', 'rate': 20, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'dest_x': locX, 'dest_y': locY, 'colour': WHITE})
create_creation(creatureName, current_wizard, locX, locY, False, False)
castsRemaining -= 1
if castsRemaining <= 0: break
if castsRemaining <= 0: break
spell_succeeded(8)
return True
else: # Not a Magic Wood, manual casting is allowed
if select_at(cursor_pos[0], cursor_pos[1]) :
# Can't place a tree or castle over a live obstruction
return False
if 'shadow' in wizards[current_wizard]['selected']['spell_name'].lower():
if adjacent_tree_check(cursor_pos[0], cursor_pos[1]):
print("Can't place a tree next to any other tree.")
return False
animations.append({'title': 'summon', 'rate': 20, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("twirl" + str(i), PALETTE[random.randint(1,7)]) for i in range(10)] + [('twirl0', BRIGHT_WHITE)], 'destination': None})
animations.append({'title': 'beam', 'rate': 5, 'x': wizards[current_wizard]['x'], 'y': wizards[current_wizard]['y'], 'dest_x': cursor_pos[0], 'dest_y': cursor_pos[1], 'colour': CYAN})
create_creation(creatureName, current_wizard, cursor_pos[0], cursor_pos[1], False, False)
castsRemaining -= 1
if castsRemaining < 1:
spell_succeeded()
return True
wizards[current_wizard]['multicast'] -= 1
print(f"Casts remaining: {wizards[current_wizard]['multicast']}")
return False
elif 'dark_power_spell':
castsRemaining = wizards[current_wizard]['multicast']
messageText = f"{wizards[current_wizard]['name']} {clean_label(wizards[current_wizard]['selected']['label'])}" + (f" {wizards[current_wizard]['selected']['distance']}" if wizards[current_wizard]['selected']['distance'] > 0 else "") + (f" ({wizards[current_wizard]['multicast']})" if wizards[current_wizard]['multicast'] > 1 else "")
print(f"{wizards[current_wizard]['name']} casting {wizards[current_wizard]['selected']['spell_name']} ({castsRemaining})")
target = select_at(cursor_pos[0], cursor_pos[1])
if not target: return False # This spell needs a target
if string_in_object(target, F_INVULN): return False # This spell can't target walls, castles, fire etc.
if not spell_test:
# Failed
castsRemaining = 0
spell_failed()
return True
attack_stat = 3 * abs(wizards[current_wizard]['selected']['law'])
attack_stat += wizards[current_wizard]['ability']
animations.append({'title': 'attack', 'rate': 20, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("attack" + str(i), BRIGHT_BLUE) for i in range(1,5)], 'destination': None})
if attack(target, attack_stat, True):
if not is_wizard(target):
kill_creation(target, False)
animations.append({'title': 'explosion', 'rate': 30, 'x': cursor_pos[0], 'y': cursor_pos[1], 'frame_set': [("explosion" + str(i), BRIGHT_WHITE) for i in range(0,7)], 'destination': None})
spell_succeeded()
return True
else:
kill_wizards_creations(target['owner'])
spell_succeeded()
return True
else:
castsRemaining -=1
if castsRemaining < 1:
spell_succeeded()
return True
else:
wizards[current_wizard]['multicast'] -= 1
print(f"Casts remaining: {wizards[current_wizard]['multicast']}")
return False
return False
def is_wizard(object):
return True if 'spell_book' in object else False
def is_flyer(object):