-
Notifications
You must be signed in to change notification settings - Fork 1
/
combat.py
2062 lines (1836 loc) · 72.7 KB
/
combat.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
__filename__ = "combat.py"
__author__ = "Bob Mottram"
__credits__ = ["Bob Mottram"]
__license__ = "AGPL3+"
__version__ = "1.0.0"
__maintainer__ = "Bob Mottram"
__email__ = "[email protected]"
__status__ = "Production"
__module_group__ = "DnD Mechanics"
import os
import time
from random import randint
from functions import update_player_attributes
from functions import get_free_key
from functions import player_inventory_weight
from functions import stow_hands
from functions import prepare_spells
from functions import random_desc
from functions import decrease_affinity_between_players
from functions import deepcopy
from functions import player_is_prone
from functions import set_player_prone
from functions import item_in_room
from environment import get_temperature_at_coords
from proficiencies import damage_proficiency
from traps import player_is_trapped
defense_clothing = (
'clo_chest',
'clo_head',
'clo_neck',
'clo_larm',
'clo_rarm',
'clo_lleg',
'clo_rleg',
'clo_lwrist',
'clo_rwrist',
'clo_lhand',
'clo_rhand',
'clo_lfinger',
'clo_rfinger',
'clo_waist',
'clo_gloves')
def holding_throwable(players: {}, id: int, items_db: {}) -> int:
"""Is the given player holding a throwable weapon?
"""
hand_locations = ('clo_rhand', 'clo_lhand')
for hand in hand_locations:
item_id = int(players[id][hand])
if item_id <= 0:
continue
if 'thrown' in items_db[item_id]['type']:
return item_id
return 0
def _drop_throwables(players: {}, id: int, items_db: {}, items: {}) -> bool:
"""A player drops a weapon which was thrown
"""
print('Dropping throwables')
plyr = players[id]
hand_locations = ('clo_rhand', 'clo_lhand')
for hand in hand_locations:
item_id = int(plyr[hand])
if item_id <= 0:
continue
if 'thrown' not in items_db[item_id]['type']:
continue
# drop
print('dropping')
if item_id in plyr['inv']:
plyr['inv'].remove(item_id)
print('Dropping item inventory ' + str(plyr['inv']))
update_player_attributes(id, players, items_db,
item_id, -1)
plyr['wei'] = \
player_inventory_weight(id, players, items_db)
# remove from clothing
plyr[hand] = 0
# Create item on the floor in the same room as the player
room_id = plyr['room']
if not item_in_room(items, item_id, room_id):
print('Dropping item in room ' +
str(item_id) + ' ' + str(room_id))
items[get_free_key(items)] = {
'id': item_id,
'room': room_id,
'whenDropped': int(time.time()),
'lifespan': 900000000,
'owner': id
}
else:
print('Dropping item not in room ' +
str(item_id) + ' ' + str(room_id))
return True
else:
print('Dropping item not in inventory')
print('No throwables dropped')
return False
def remove_prepared_spell(players: {}, id: int, spell_name: str):
"""Remove a prepared spell
"""
del players[id]['preparedSpells'][spell_name]
del players[id]['spellSlots'][spell_name]
def _player_is_available(id: int, players: {}, items_db: {}, rooms: {},
map_area: {}, clouds: {},
max_terrain_difficulty: int) -> bool:
"""Returns True if the player is available.
Availability is encumbered by weight, temperature and terrain
"""
plyr = players[id]
curr_room = plyr['room']
weight_difficulty = \
int(_get_encumberance_from_weight(id, players, items_db) * 2)
temperature_difficulty = \
_get_temperature_difficulty(curr_room, rooms, map_area, clouds)
terrain_difficulty = \
int(rooms[plyr['room']]['terrainDifficulty'] * 10 /
max_terrain_difficulty)
# Agility of NPC
modifier = \
10 - plyr['agi'] - \
_armor_agility(id, players, items_db) + terrain_difficulty + \
temperature_difficulty + weight_difficulty
if modifier < 6:
modifier = 6
elif modifier > 25:
modifier = 25
if int(time.time()) < plyr['lastCombatAction'] + modifier:
return False
return True
def _get_encumberance_from_weight(id: int, players: {}, items_db: {}) -> int:
"""Returns the light medium or heavy encumberance (0,1,2)
"""
total_weight = player_inventory_weight(id, players, items_db)
plyr = players[id]
strength = int(plyr['str'])
if strength < 1:
strength = 1
# encumberance for light, medium and heavy loads
encumberance = {
"1": [3, 6, 10],
"2": [6, 13, 20],
"3": [10, 20, 30],
"4": [13, 26, 40],
"5": [16, 33, 50],
"6": [20, 40, 60],
"7": [23, 46, 70],
"8": [26, 53, 80],
"9": [30, 60, 90],
"10": [33, 66, 100],
"11": [38, 76, 115],
"12": [43, 86, 130],
"13": [50, 100, 150],
"14": [58, 116, 175],
"15": [66, 133, 200],
"16": [76, 153, 230],
"17": [86, 173, 260],
"18": [100, 200, 300],
"19": [116, 233, 350],
"20": [133, 266, 400],
"21": [153, 306, 460],
"22": [173, 346, 520],
"23": [200, 400, 600],
"24": [233, 466, 700],
"25": [266, 533, 800],
"26": [306, 613, 920],
"27": [346, 693, 1040],
"28": [400, 800, 1200],
"29": [466, 933, 1400]
}
if strength <= 29:
thresholds = encumberance[str(strength)]
else:
str_index = 20 + (strength % 10)
multiplier = int((strength - 20) / 10)
thresholds = encumberance[str(str_index)]
for idx, _ in enumerate(thresholds):
thresholds[idx] = int(thresholds[idx] * (multiplier*4))
# multiplier for creature size
size = int(plyr['siz'])
mult = 1
if size == 3:
mult = 2
elif size == 4:
mult = 4
elif size == 5:
mult = 8
elif size == 6:
mult = 16
for idx, _ in enumerate(thresholds):
if total_weight < int(thresholds[idx] * mult):
return idx
return 2
def _player_shoves(mud, id: int, players1: {}, s2id: int, players2: {},
races_db: {}) -> bool:
"""One player attempts to shove another
"""
plyr1 = players1[id]
plyr2 = players2[s2id]
player1_size = plyr1['siz']
player2_size = plyr2['siz']
if plyr2.get('race'):
race = plyr2['race'].lower()
if races_db.get(race):
if races_db[race].get('siz'):
player2_size = races_db[race]['siz']
if player2_size < player1_size or player2_size > player1_size + 1:
if player2_size > player1_size:
descr = random_desc("They're too large to shove")
else:
descr = random_desc("They're too small to shove")
mud.send_message(id, descr + '.\n')
plyr1['shove'] = 0
return False
player1_strength = plyr1['str']
player2_strength = plyr2['str']
if plyr2.get('race'):
race = plyr2['race'].lower()
if races_db.get(race):
if races_db[race].get('str'):
player2_strength = races_db[race]['str']
plyr1['shove'] = 0
if player_is_prone(s2id, players2):
mud.send_message(
id,
'You attempt to shove ' + plyr2['name'] +
', but they are already prone.\n')
return False
descr = random_desc('You shove ' + plyr2['name'])
mud.send_message(id, descr + '.\n')
if randint(1, player1_strength) > randint(1, player2_strength):
plyr2['prone'] = 1
desc = (
'They stumble and fall',
'They stumble and fall to the ground',
'They come crashing to the ground',
'They become unsteady and fall',
'They fall over',
'They fall heavily to the ground',
'They topple and fall to the ground',
'They topple over',
'They stagger and fall backwards',
'They stagger and fall',
'They stagger and fall to the ground',
'They lose balance and fall',
'They lose balance and fall to the ground',
'They lose balance and fall backwards'
)
descr = random_desc(desc)
mud.send_message(id, descr + '.\n')
return True
desc = (
'They remain standing',
'They remain sturdy',
'They remain in place',
'They resist being shoved',
'They stand firm',
'They push back and remain standing',
'They remain steady'
)
descr = random_desc(desc)
mud.send_message(id, descr + '.\n')
return False
def _combat_update_max_hit_points(id: int, players: {}, races_db: {}) -> None:
"""Updates the hp_max value
"""
plyr = players[id]
# some npcs are invincible
if plyr['hpMax'] >= 999:
return
level = plyr['lvl']
hit_die = '1d10'
if plyr.get('race'):
race = plyr['race'].lower()
if races_db.get(race):
if races_db[race].get('hitDie'):
hit_die = races_db[race]['hitDie']
hp_max = int(hit_die.split('d')[1])
if level > 1:
hp_max = hp_max + (int(hp_max/2) * (level - 1))
plyr['hpMax'] = hp_max
def health_of_player(pid: int, players: {}) -> str:
"""Returns a description of health status
"""
plyr = players[pid]
hp_val = plyr['hp']
hp_max = 11
if plyr.get('hpMax'):
hp_max = plyr['hpMax']
health_percent = int(hp_val * 100 / hp_max)
health_msg = 'in full health'
if health_percent < 100:
if health_percent >= 99:
health_msg = 'lightly wounded'
elif health_percent >= 84:
health_msg = 'moderately wounded'
elif health_percent >= 70:
health_msg = 'considerably wounded'
elif health_percent >= 56:
health_msg = 'quite wounded'
elif health_percent >= 42:
health_msg = 'badly wounded'
elif health_percent >= 28:
health_msg = 'extremely wounded'
elif health_percent >= 14:
health_msg = 'critically wounded'
elif health_percent > 0:
health_msg = 'close to death'
else:
health_msg = 'dead'
# add color for critical health
if health_percent < 50:
health_msg = '<f15><b88>' + health_msg + '<r>'
elif health_percent < 70:
health_msg = '<f15><b166>' + health_msg + '<r>'
return health_msg
def _combat_ability_modifier(score: int) -> int:
"""Returns the ability modifier
"""
if score > 30:
return 10
# min and max score and the corresponding
# ability modifier
ability_table = (
[1, 1, -5],
[2, 3, -4],
[4, 5, -3],
[6, 7, -2],
[8, 9, -1],
[10, 11, 0],
[12, 13, 1],
[14, 15, 2],
[16, 17, 3],
[18, 19, 4],
[20, 21, 5],
[22, 23, 6],
[24, 25, 7],
[26, 27, 8],
[28, 29, 9],
[30, 30, 10]
)
for ability_range in ability_table:
if score in range(ability_range[0], ability_range[1] + 1):
return ability_range[2]
return 0
def _combat_race_resistance(id: int, players: {},
races_db: {}, weapon_type: str) -> int:
"""How much resistance does the player have to the weapon type
based upon their race
"""
resistance = 0
resist_param = 'resist_' + weapon_type.lower()
if weapon_type.endswith('bow') or weapon_type == 'pole':
resist_param = 'resist_piercing'
if weapon_type.endswith('sling') or \
'flail' in weapon_type or \
'whip' in weapon_type:
resist_param = 'resist_bludgeoning'
if players[id].get('race'):
race = players[id]['race'].lower()
if races_db.get(race):
if races_db[race].get(resist_param):
resistance = races_db[race][resist_param]
return resistance
def _combat_damage_from_weapon(id: str, players: {},
items_db: {}, weapon_type: str,
character_class_db: {},
is_critical: bool, thrown: int) -> (int, str):
"""find the weapon being used and return its damage value
"""
weapon_locations = (
'clo_lhand',
'clo_rhand',
'clo_gloves'
)
# bare knuckle fight
damage_roll_best = '1d3'
max_damage = 1
max_modifier = 0
for wpn in weapon_locations:
item_id = int(players[id][wpn])
if item_id <= 0:
continue
damage_roll = items_db[item_id]['damage']
if not damage_roll:
continue
if 'd' not in damage_roll:
continue
die = int(damage_roll.split('d')[1])
no_of_rolls = int(damage_roll.split('d')[0])
if is_critical:
# double the damage for a critical hit
no_of_rolls *= 2
score = 0
if not items_db[item_id].get('damageChart'):
# linear damage
for _ in range(no_of_rolls):
score += randint(1, die + 1)
else:
# see https://andregarzia.com/
# 2021/12/in-defense-of-the-damage-chart.html
for _ in range(no_of_rolls):
chart_index = randint(0, die)
if chart_index < len(items_db[item_id]['damageChart']):
score += items_db[item_id]['damageChart'][chart_index]
else:
score += items_db[item_id]['damageChart'][-1]
modifier = 0
# did we throw it?
if thrown > 0:
# is this weapon throwable?
if 'thrown' in items_db[item_id]['type']:
# increased damage from thrown weapons
modifier = 2
if score > max_damage:
max_damage = score
damage_roll_best = damage_roll
max_modifier = modifier
return max_damage, damage_roll_best, max_modifier
def _combat_armor_class(id: int, players: {},
races_db: {}, attack_weapon_type: str,
items_db: {}) -> int:
"""Returns the armor class for the given player
when attacked by the given weapon type
"""
armor_class = 0
for clth in defense_clothing:
item_id = int(players[id][clth])
if item_id <= 0:
continue
armor_class += items_db[item_id]['armorClass']
if armor_class < 10:
armor_class += 10
race_armor = _combat_race_resistance(id, players, races_db,
attack_weapon_type)
if armor_class < race_armor:
armor_class = race_armor
if players[id].get('magicShield'):
armor_class += players[id]['magicShield']
return armor_class
def _combat_proficiency_bonus(id: int, players: {}, weapon_type: str,
character_class_db: {}) -> int:
"""Returns the proficiency bonus with the given weapon type
"""
return damage_proficiency(id, players, weapon_type,
character_class_db)
def _combat_attack_roll(id: int, players: {}, weapon_type: str,
target_armor_class: int,
character_class_db: {},
dodge_modifier: int) -> (bool, bool):
"""Returns true if an attack against a target succeeds
"""
d20 = randint(1, 20)
if d20 == 1:
# miss
return False, False
if d20 == 20:
# critical hit
return True, True
ability_modifier = 0
if 'ranged' in weapon_type:
ability_modifier = _combat_ability_modifier(players[id]['agi'])
else:
ability_modifier = _combat_ability_modifier(players[id]['str'])
proficiency_bonus = \
_combat_proficiency_bonus(id, players, weapon_type,
character_class_db)
if d20 + ability_modifier + proficiency_bonus >= \
target_armor_class + dodge_modifier:
return True, False
return False, False
def _send_combat_image(mud, id: int, players: {}, race: str,
weapon_type: str) -> None:
"""Sends an image based on a character of a given race using a given weapon
"""
if not (race and weapon_type):
return
if players[id].get('graphics'):
if players[id]['graphics'] == 'off':
return
combat_image_filename = 'images/combat/' + race + '_' + weapon_type
if not os.path.isfile(combat_image_filename):
return
try:
with open(combat_image_filename, 'r', encoding='utf-8') as fp_img:
mud.send_image(id, '\n' + fp_img.read())
except OSError:
print('EX: _send_combat_image ' + combat_image_filename)
def update_temporary_incapacitation(mud, players: {}, is_npc: bool) -> None:
"""Checks if players are incapacitated by spells and removes them
after the duration has elapsed
"""
now = int(time.time())
for plyr_id, plyr in players.items():
this_player = plyr
if this_player['name'] is None:
continue
if this_player['frozenStart'] == 0:
continue
st_time = \
this_player['frozenStart'] + this_player['frozenDuration']
if now < st_time:
continue
this_player['frozenStart'] = 0
this_player['frozenDuration'] = 0
this_player['frozenDescription'] = ""
if not is_npc:
mud.send_message(
plyr_id, "<f220>You find that you can move again.<r>\n\n")
def update_temporary_hit_points(mud, players: {}, is_npc: bool) -> None:
"""Updates any hit points added for a temporary period
as the result of a spell
"""
now = int(time.time())
for plyr_id, plyr in players.items():
this_player = plyr
if this_player['name'] is None:
continue
if this_player['tempHitPoints'] == 0:
continue
if this_player['tempHitPointsStart'] == 0 and \
this_player['tempHitPointsDuration'] > 0:
this_player['tempHitPointsStart'] = now
else:
if now > this_player['tempHitPointsStart'] + \
this_player['tempHitPointsDuration']:
this_player['tempHitPoints'] = 0
this_player['tempHitPointsStart'] = 0
this_player['tempHitPointsDuration'] = 0
if not is_npc:
mud.send_message(
plyr_id,
"<f220>Your magical protection expires.<r>\n\n")
def update_temporary_charm(mud, players: {}, is_npc: bool) -> None:
"""Updates any charm added for a temporary period
as the result of a spell
"""
now = int(time.time())
for plyr_id, plyr in players.items():
this_player = plyr
if this_player['name'] is None:
continue
if this_player['tempCharm'] == 0:
continue
if this_player['tempCharmStart'] == 0 and \
this_player['tempCharmDuration'] > 0:
this_player['tempCharmStart'] = now
else:
if not this_player.get('tempCharmDuration'):
return
if now > this_player['tempCharmStart'] + \
this_player['tempCharmDuration']:
this_player['tempCharmStart'] = 0
this_player['tempCharmDuration'] = 0
if this_player['affinity'].get(this_player['tempCharmTarget']):
charm_targ = this_player['tempCharmTarget']
this_player['affinity'][charm_targ] -= \
this_player['tempCharm']
this_player['tempCharm'] = 0
if not is_npc:
mud.send_message(
plyr_id,
"<f220>A charm spell wears off.<r>\n\n")
def update_magic_shield(mud, players: {}, is_npc: bool) -> None:
"""Updates any magic shield for a temporary period
as the result of a spell
"""
now = int(time.time())
for plyr_id, plyr in players.items():
this_player = plyr
if this_player['name'] is None:
continue
if not this_player.get('magicShield'):
continue
if this_player['magicShieldStart'] == 0 and \
this_player['magicShieldDuration'] > 0:
this_player['magicShieldStart'] = now
else:
if not this_player.get('magicShieldDuration'):
return
if now > this_player['magicShieldStart'] + \
this_player['magicShieldDuration']:
this_player['magicShieldStart'] = 0
this_player['magicShieldDuration'] = 0
this_player['magicShield'] = 0
if not is_npc:
mud.send_message(
plyr_id,
"<f220>Your magic shield wears off.<r>\n\n")
def players_rest(mud, players: {}) -> None:
"""Rest restores hit points
"""
for plyr_id, plyr in players.items():
this_player = plyr
if this_player['name'] is not None and \
this_player['authenticated'] is not None:
if this_player['hp'] < this_player['hpMax'] + \
this_player['tempHitPoints']:
if randint(0, 100) > 90:
this_player['hp'] += 1
else:
this_player['hp'] = this_player['hpMax'] + \
this_player['tempHitPoints']
this_player['restRequired'] = 0
prepare_spells(mud, plyr_id, players)
def _item_in_npc_inventory(npcs, id: int, item_name: str,
items_db: {}) -> bool:
"""Is an item in the NPC's inventory?
"""
npc1 = npcs[id]
if len(list(npc1['inv'])) > 0:
item_name_lower = item_name.lower()
for idx in list(npc1['inv']):
itemobj = items_db[int(idx)]
if itemobj['name'].lower() == item_name_lower:
return True
return False
def _npc_update_luck(nid: int, npcs: {}, items: {}, items_db: {}) -> None:
"""Calculate the luck of an NPC based on what items they are carrying
"""
npc1 = npcs[nid]
luck = 0
for i in npc1['inv']:
itemobj = items_db[int(i)]
luck = luck + itemobj['mod_luc']
npc1['luc'] = luck
def _npc_wields_weapon(mud, id: int, nid: int, npcs: {},
items: {}, items_db: {}, rooms: {}) -> bool:
"""what is the best weapon which the NPC is carrying?
"""
item_id = 0
max_protection = 0
max_damage = 0
npc1 = npcs[nid]
if int(npc1['canWield']) != 0:
for i in npc1['inv']:
itemobj = items_db[int(i)]
if itemobj['clo_rhand'] > 0:
if itemobj['mod_str'] > max_damage:
max_damage = itemobj['mod_str']
item_id = int(i)
elif itemobj['clo_lhand'] > 0:
if itemobj['mod_str'] > max_damage:
max_damage = itemobj['mod_str']
item_id = int(i)
put_on_armor = False
if int(npc1['canWear']) != 0:
for i in npc1['inv']:
itemobj = items_db[int(i)]
if itemobj['clo_chest'] < 1:
continue
if itemobj['mod_endu'] > max_protection:
max_protection = itemobj['mod_endu']
item_id = int(i)
put_on_armor = True
# search for any weapons on the floor
picked_up_weapon = False
item_weapon_index = 0
if int(npc1['canWield']) != 0:
items_in_world_copy = deepcopy(items)
for iid, itemobj in items_in_world_copy.items():
if itemobj['room'] != npc1['room']:
continue
itemobj2 = items[iid]
itemobj2_id = itemobj2['id']
if items_db[itemobj2_id]['weight'] == 0:
continue
if items_db[itemobj2_id]['clo_rhand'] == 0:
continue
if items_db[itemobj2_id]['mod_str'] <= max_damage:
continue
if _confined_space(nid, npcs, items_db, itemobj2_id, rooms):
continue
item_name = items_db[itemobj2_id]['name']
if _item_in_npc_inventory(npcs, nid, item_name, items_db):
continue
max_damage = items_db[itemobj2_id]['mod_str']
item_id = int(itemobj2_id)
item_weapon_index = iid
picked_up_weapon = True
# Search for any armor on the floor
picked_up_armor = False
item_armor_index = 0
if int(npc1['canWear']) != 0:
for iid, itemobj in items_in_world_copy.items():
if itemobj['room'] != npc1['room']:
continue
itemobj2 = items[iid]
itemobj2_id = itemobj2['id']
if items_db[itemobj2_id]['weight'] == 0:
continue
if items_db[itemobj2_id]['clo_chest'] == 0:
continue
if items_db[itemobj2_id]['mod_endu'] <= max_protection:
continue
item_name = items_db[itemobj2_id]['name']
if _item_in_npc_inventory(npcs, nid, item_name, items_db):
continue
max_protection = \
items_db[itemobj2_id]['mod_endu']
item_id = int(itemobj2_id)
item_armor_index = iid
picked_up_armor = True
if item_id > 0:
if put_on_armor:
if npc1['clo_chest'] != item_id:
npc1['clo_chest'] = item_id
mud.send_message(
id, '<f220>' + npc1['name'] +
'<r> puts on ' +
items_db[item_id]['article'] +
' ' + items_db[item_id]['name'] + '\n')
return True
return False
if picked_up_armor:
if npc1['clo_chest'] != item_id:
npc1['inv'].append(str(item_id))
npc1['clo_chest'] = item_id
del items[item_armor_index]
mud.send_message(
id, '<f220>' + npc1['name'] +
'<r> picks up and wears ' +
items_db[item_id]['article'] +
' ' + items_db[item_id]['name'] + '\n')
return True
return False
if npc1['clo_rhand'] != item_id:
# Transfer weapon to hand
npc1['clo_rhand'] = item_id
npc1['clo_lhand'] = 0
if picked_up_weapon:
npc1['inv'].append(str(item_id))
del items[item_weapon_index]
mud.send_message(
id, '<f220>' + npc1['name'] +
'<r> picks up ' +
items_db[item_id]['article'] +
' ' + items_db[item_id]['name'] + '\n')
else:
mud.send_message(
id, '<f220>' + npc1['name'] +
'<r> has drawn their ' +
items_db[item_id]['name'] + '\n')
return True
return False
def _npc_wears_armor(id: int, npcs: {}, items_db: {}) -> None:
"""An NPC puts on armor
"""
npc1 = npcs[id]
if len(npc1['inv']) == 0:
return
for clth in defense_clothing:
item_id = 0
# what is the best defense which the NPC is carrying?
max_defense = 0
for idx in npc1['inv']:
if items_db[int(idx)][clth] < 1:
continue
if items_db[int(idx)]['mod_str'] != 0:
continue
if items_db[int(idx)]['mod_endu'] > max_defense:
max_defense = items_db[int(idx)]['mod_endu']
item_id = int(idx)
if item_id > 0:
# Wear the armor
npc1[clth] = item_id
def _two_handed_weapon(id: int, players: {}, items_db: {}) -> None:
""" If carrying a two handed weapon then make sure
that the other hand is empty
"""
plyr = players[id]
item_idleft = plyr['clo_lhand']
item_idright = plyr['clo_rhand']
# items on both hands
if item_idleft == 0 or item_idright == 0:
return
# at least one item is two handed
if items_db[item_idleft]['bothHands'] == 0 and \
items_db[item_idright]['bothHands'] == 0:
return
if items_db[item_idright]['bothHands'] == 1:
plyr['clo_lhand'] = 0
else:
plyr['clo_rhand'] = 0
def _armor_agility(id: int, players: {}, items_db: {}) -> int:
"""Modify agility based on armor worn
"""
agility = 0
for clth in defense_clothing:
item_id = int(players[id][clth])
if item_id > 0:
agility = agility + int(items_db[item_id]['mod_agi'])
# Total agility for clothing
return agility
def _can_use_weapon(id: int, players: {}, items_db: {}, item_id: int) -> bool:
"""Can the given player use the given weapon?
eg. use of a weapon requires some other item to be in the inventory
"""
if item_id == 0:
return True
lock_item_id = items_db[item_id]['lockedWithItem']
if str(lock_item_id).isdigit():
if lock_item_id > 0:
item_name = items_db[lock_item_id]['name']
for i in list(players[id]['inv']):
if items_db[int(i)]['name'] == item_name:
return True
return False
return True
def _confined_space(id: int, players: {}, items_db: {},
item_id: int, rooms: {}) -> bool:
"""Is the given player in a confined space?
"""
if item_id > 0:
if items_db[item_id]['bothHands'] > 0:
room_id = players[id]['room']
if rooms[room_id]['maxPlayers'] < 3:
return True
return False
def _get_weapon_held(id: int, players: {}, items_db: {}) -> (int, str, int):
"""Returns the type of weapon held, or fists if none
is held and the rounds of fire
"""
fighter = players[id]
if fighter['clo_rhand'] > 0 and fighter['clo_lhand'] == 0:
# something in right hand
item_id = int(fighter['clo_rhand'])
if items_db[item_id]['mod_str'] > 0:
if len(items_db[item_id]['type']) > 0:
return item_id, items_db[item_id]['type'], \
items_db[item_id]['rof']
if fighter['clo_lhand'] > 0 and fighter['clo_rhand'] == 0:
# something in left hand
item_id = int(fighter['clo_lhand'])
if items_db[item_id]['mod_str'] > 0:
if len(items_db[item_id]['type']) > 0:
return item_id, items_db[item_id]['type'], \
items_db[item_id]['rof']
if fighter['clo_lhand'] > 0 and fighter['clo_rhand'] > 0:
# something in both hands
item_right_id = int(fighter['clo_rhand'])
item_right = items_db[item_right_id]
item_left_id = int(fighter['clo_lhand'])
item_left = items_db[item_left_id]
if randint(0, 1) == 1:
if item_right['mod_str'] > 0:
if len(item_right['type']) > 0:
return item_right_id, item_right['type'], item_right['rof']
if item_left['mod_str'] > 0:
if len(item_left['type']) > 0:
return item_left_id, item_left['type'], item_left['rof']
else:
if item_left['mod_str'] > 0:
if len(item_left['type']) > 0:
return item_left_id, item_left['type'], item_left['rof']
if item_right['mod_str'] > 0:
if len(item_right['type']) > 0:
return item_right_id, item_right['type'], item_right['rof']
return 0, "fists", 1
def _get_attack_description(animal_type: str, weapon_type: str,
attack_db: {}, is_critical: bool,
thrown: int) -> (str, str):
"""Describes an attack with a given type of weapon. This
Returns both the first person and second person
perspective descriptions
"""
weapon_type = weapon_type.lower()
if not animal_type:
attack_strings = [
"swing a fist at",
"punch",
"crudely swing a fist at",
"ineptly punch"
]
attack_description_first = random_desc(attack_strings)
attack_strings = [
"swung a fist at",
"punched",
"crudely swung a fist at",
"ineptly punched"
]
attack_description_second = random_desc(attack_strings)
for attack_type, attack_desc in attack_db.items():
if animal_type.startswith('animal '):
continue
attack_type_list = attack_type.split('|')
for attack_type_str in attack_type_list:
if not weapon_type.startswith(attack_type_str):
continue
if thrown > 0 and 'thrown' not in attack_type_str:
continue
if thrown <= 0 and 'thrown' in attack_type_str:
continue
if not is_critical: