-
Notifications
You must be signed in to change notification settings - Fork 1
/
npcs.py
1564 lines (1447 loc) · 65.4 KB
/
npcs.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__ = "npcs.py"
__author__ = "Bob Mottram"
__credits__ = ["Bob Mottram"]
__license__ = "AGPL3+"
__version__ = "1.0.0"
__maintainer__ = "Bob Mottram"
__email__ = "[email protected]"
__status__ = "Production"
__module_group__ = "NPCs"
import os
import datetime
import time
from random import randint
from suntime import Sun
from functions import add_to_scheduler
from functions import message_to_room_players
from functions import log
from functions import player_inventory_weight
from functions import update_player_attributes
from functions import increase_affinity_between_players
from functions import decrease_affinity_between_players
from functions import get_sentiment
from functions import random_desc
from functions import deepcopy
from functions import parse_cost
# from copy import deepcopy
from familiar import get_familiar_modes
from familiar import familiar_default_mode
from familiar import familiar_scout
from familiar import familiar_hide
from familiar import familiar_sight
from environment import get_rain_at_coords
from environment import get_room_culture
def corpse_exists(corpses: {}, room: str, name: str) -> bool:
"""Returns true if a corpse with the given name exists in the given room
"""
corpses_copy = deepcopy(corpses)
for _, cor_obj in corpses_copy.items():
if cor_obj['room'] == room and \
cor_obj['name'] == name:
return True
return False
def npcs_rest(npcs: {}) -> None:
"""Rest restores hit points of NPCs
"""
for _, plyr in npcs.items():
this_npc = plyr
if this_npc['hp'] < this_npc['hpMax'] + this_npc['tempHitPoints']:
if randint(0, 100) > 97:
this_npc['hp'] += 1
else:
this_npc['hp'] = this_npc['hpMax'] + this_npc['tempHitPoints']
this_npc['restRequired'] = 0
def _get_leader_room_index(npcs: {}, players: {}, mud,
now, nid: int, move_type: str) -> str:
"""An NPC follows another NPC or player
This returns the index of the room where the leader is located
"""
if not move_type.startswith('leader:'):
return ''
leader_name = move_type.split(':')[1]
if len(leader_name) == 0:
return ''
# is the leader an NPC
for _, leader_npc in npcs.items():
if leader_npc['name'] != leader_name:
continue
if leader_npc['room'] == npcs[nid]['room']:
continue
# follower NPCs are in the same guild
npcs[nid]['guild'] = leader_npc['guild']
return leader_npc['room']
# is the leader a player
for _, plyr in players.items():
if plyr['name'] != leader_name:
continue
if plyr['room'] == npcs[nid]['room']:
continue
npcs[nid]['guild'] = plyr['guild']
return plyr['room']
return ''
def get_solar():
return Sun(52.414, 4.081)
def _entity_is_active(id: int, players: {}, rooms: {},
move_times: [], map_area: [], clouds: {},
curr_time, curr_hour, sun,
curr_day_of_week: int,
curr_month_number: int) -> bool:
if len(move_times) == 0:
return True
# These variables are used for matching a number of days
# as separate time ranges, eg X or Y or Z
matching_days = False
days_are_matched = False
for time_range in move_times:
if len(time_range) >= 2:
time_range_type = time_range[0].lower()
if time_range_type in ('day', 'weekday', 'dayofweek', 'dow'):
dow_matched = False
time_range_len = len(time_range)
for dow in range(1, time_range_len):
day_of_week = time_range[dow].lower()
if day_of_week.startswith('m') and curr_day_of_week == 0:
dow_matched = True
break
if day_of_week.startswith('tu') and curr_day_of_week == 1:
dow_matched = True
break
if day_of_week.startswith('w') and curr_day_of_week == 2:
dow_matched = True
break
if day_of_week.startswith('th') and curr_day_of_week == 3:
dow_matched = True
break
if day_of_week.startswith('f') and curr_day_of_week == 4:
dow_matched = True
break
if day_of_week.startswith('sa') and curr_day_of_week == 5:
dow_matched = True
break
if day_of_week.startswith('su') and curr_day_of_week == 6:
dow_matched = True
break
if not dow_matched:
return False
continue
elif time_range_type == 'season':
season_matched = False
for season_index in range(1, len(time_range)):
season_name = time_range[season_index].lower()
if season_name == 'spring':
if curr_month_number in range(2, 5):
season_matched = True
break
if season_name == 'summer':
if curr_month_number in range(5, 10):
season_matched = True
break
if season_name == 'autumn':
if curr_month_number in range(10, 11):
season_matched = True
break
if season_name == 'winter':
if curr_month_number > 10 or curr_month_number <= 1:
season_matched = True
break
if not season_matched:
return False
continue
if len(time_range) != 3:
continue
time_range_type = time_range[0].lower()
time_range_start = time_range[1]
time_range_end = time_range[2]
# sunrise
if time_range_type in ('sunrise', 'dawn'):
sun_rise_time = sun.get_local_sunrise_time(curr_time).hour
if 'true' in time_range_start.lower() or \
'y' in time_range_start.lower():
if not (curr_hour in range(sun_rise_time - 1,
sun_rise_time + 1)):
return False
else:
if not (curr_hour < sun_rise_time - 1 or
curr_hour > sun_rise_time):
return False
elif time_range_type in ('sunset', 'dusk'):
sun_set_time = sun.get_local_sunset_time(curr_time).hour
if 'true' in time_range_start.lower() or \
'y' in time_range_start.lower():
if curr_hour not in range(sun_set_time, sun_set_time + 2):
return False
else:
if not (curr_hour < sun_set_time or
curr_hour > sun_set_time + 1):
return False
elif time_range_type == 'rain':
rm = players[id]['room']
coords = rooms[rm]['coords']
if 'true' in time_range_start.lower() or \
'y' in time_range_start.lower():
if not get_rain_at_coords(coords, map_area, clouds):
return False
else:
if get_rain_at_coords(coords, map_area, clouds):
return False
elif time_range_type == 'rainday':
sun_rise_time = sun.get_local_sunrise_time(curr_time).hour
sun_set_time = sun.get_local_sunset_time(curr_time).hour
if curr_hour < sun_rise_time or curr_hour > sun_set_time:
return False
rmid = players[id]['room']
coords = rooms[rmid]['coords']
if 'true' in time_range_start.lower() or \
'y' in time_range_start.lower():
if not get_rain_at_coords(coords, map_area, clouds):
return False
else:
if get_rain_at_coords(coords, map_area, clouds):
return False
elif time_range_type == 'rainnight':
sun_rise_time = sun.get_local_sunrise_time(curr_time).hour
sun_set_time = sun.get_local_sunset_time(curr_time).hour
if curr_hour in range(sun_rise_time, sun_set_time + 1):
return False
rmid = players[id]['room']
coords = rooms[rmid]['coords']
if 'true' in time_range_start.lower() or \
'y' in time_range_start.lower():
if not get_rain_at_coords(coords, map_area, clouds):
return False
else:
if get_rain_at_coords(coords, map_area, clouds):
return False
elif time_range_type == 'rainmorning':
sun_rise_time = sun.get_local_sunrise_time(curr_time).hour
if curr_hour < sun_rise_time or \
curr_hour > 12:
return False
rmid = players[id]['room']
coords = rooms[rmid]['coords']
if 'true' in time_range_start.lower() or \
'y' in time_range_start.lower():
if not get_rain_at_coords(coords, map_area, clouds):
return False
else:
if get_rain_at_coords(coords, map_area, clouds):
return False
elif time_range_type == 'rainafternoon':
if curr_hour < 12 or curr_hour > 17:
return False
rmid = players[id]['room']
coords = rooms[rmid]['coords']
if 'true' in time_range_start.lower() or \
'y' in time_range_start.lower():
if not get_rain_at_coords(coords, map_area, clouds):
return False
else:
if get_rain_at_coords(coords, map_area, clouds):
return False
elif time_range_type == 'rainevening':
sun_set_time = sun.get_local_sunset_time(curr_time).hour
if curr_hour < 17 or \
curr_hour > sun_set_time:
return False
rmid = players[id]['room']
coords = rooms[rmid]['coords']
if 'true' in time_range_start.lower() or \
'y' in time_range_start.lower():
if not get_rain_at_coords(coords, map_area, clouds):
return False
else:
if get_rain_at_coords(coords, map_area, clouds):
return False
elif time_range_type.startswith('hour'):
# hour of day
start_hour = int(time_range_start)
end_hour = int(time_range_end)
if end_hour >= start_hour:
if curr_hour < start_hour or curr_hour > end_hour:
return False
else:
if curr_hour in range(end_hour + 1, start_hour):
return False
elif time_range_type.startswith('month'):
# between months
curr_month = int(datetime.datetime.today().strftime("%m"))
start_month = int(time_range_start)
end_month = int(time_range_end)
if end_month >= start_month:
if curr_month < start_month or curr_month > end_month:
return False
else:
if curr_month in range(end_month + 1, start_month):
return False
elif time_range_type.startswith('dayofmonth'):
# a particular day of a month
curr_month = int(datetime.datetime.today().strftime("%m"))
curr_day_of_month = int(datetime.datetime.today().strftime("%d"))
month = int(time_range_start)
monthday = int(time_range_end)
matching_days = True
if curr_month == month and curr_day_of_month == monthday:
days_are_matched = True
elif time_range_type == 'daysofyear':
# between days of year
curr_day_of_year = int(datetime.datetime.today().strftime("%j"))
start_day = int(time_range_start)
end_day = int(time_range_end)
if end_day >= start_day:
if curr_day_of_year < start_day or curr_day_of_year > end_day:
return False
else:
if curr_day_of_year in range(end_day + 1, start_day):
return False
# if we are matching a set of days, where any matched?
if matching_days:
if not days_are_matched:
return False
return True
def _move_npcs(npcs: {}, players: {}, mud, now, nid: int) -> None:
"""If movement is defined for an NPC this moves it around
"""
this_npc = npcs[nid]
if now > this_npc['lastMoved'] + \
int(this_npc['moveDelay']) + this_npc['randomizer']:
# Move types:
# random, cycle, inverse cycle, patrol, follow, leader:name
move_type_lower = this_npc['moveType'].lower()
follow_cycle = False
if move_type_lower.startswith('f'):
if len(this_npc['follow']) == 0:
follow_cycle = True
# Look for a player to follow
for _, plyr in players.items():
if this_npc['room'] == plyr['room']:
# follow by name
# print(this_npc['name'] + ' starts following ' +
# plyr['name'] + '\n')
this_npc['follow'] = plyr['name']
follow_cycle = False
if not follow_cycle:
return
if move_type_lower.startswith('c') or \
move_type_lower.startswith('p') or follow_cycle:
npc_room_index = 0
npc_room_curr = this_npc['room']
for npc_room in this_npc['path']:
if npc_room == npc_room_curr:
npc_room_index = npc_room_index + 1
break
npc_room_index = npc_room_index + 1
if npc_room_index >= len(this_npc['path']):
if move_type_lower.startswith('p'):
this_npc['moveType'] = 'back'
npc_room_index = len(this_npc['path']) - 1
if npc_room_index > 0:
npc_room_index = npc_room_index - 1
else:
npc_room_index = 0
else:
if move_type_lower.startswith('i') or \
move_type_lower.startswith('b'):
npc_room_index = 0
npc_room_curr = this_npc['room']
for npc_room in this_npc['path']:
if npc_room == npc_room_curr:
npc_room_index = npc_room_index - 1
break
npc_room_index = npc_room_index + 1
if npc_room_index >= len(this_npc['path']):
npc_room_index = len(this_npc['path']) - 1
if npc_room_index < 0:
if move_type_lower.startswith('b'):
this_npc['moveType'] = 'patrol'
npc_room_index = 0
if npc_room_index < len(this_npc['path']) - 1:
npc_room_index = npc_room_index + 1
else:
npc_room_index = len(this_npc['path']) - 1
else:
npc_room_index = \
_get_leader_room_index(npcs, players, mud, now,
nid, move_type_lower)
if len(npc_room_index) == 0:
npc_room_index = randint(0, len(this_npc['path']) - 1)
rmid = this_npc['path'][npc_room_index]
if this_npc['room'] != rmid:
for pid, plyr in players.items():
if this_npc['room'] == plyr['room']:
mud.send_message(
pid, '<f220>' + this_npc['name'] + "<r> " +
random_desc(this_npc['outDescription']) +
"\n\n")
this_npc['room'] = rmid
this_npc['lastRoom'] = rmid
for pid, plyr in players.items():
if this_npc['room'] == plyr['room']:
mud.send_message(
pid, '<f220>' + this_npc['name'] + "<r> " +
random_desc(this_npc['inDescription']) +
"\n\n")
this_npc['randomizer'] = randint(0, this_npc['randomFactor'])
this_npc['lastMoved'] = now
def _remove_inactive_entity(nid: int, npcs: {}, nid2, npcs_db: {},
npc_active: bool) -> bool:
"""Moves inactive NPCs to and from purgatory
Returns true when recovering from purgatory
"""
# Where NPCs go when inactive by default
purgatory_room = "$rid=1386$"
for time_range in npcs_db[nid2]['moveTimes']:
if len(time_range) != 2:
continue
if time_range[0].startswith('inactive') or \
time_range[0].startswith('home'):
purgatory_room = "$rid=" + str(time_range[1]) + "$"
break
this_npc = npcs[nid]
if this_npc['room'] == purgatory_room:
if npc_active:
if this_npc.get('lastRoom'):
# recover from purgatory
this_npc['room'] = this_npc['lastRoom']
return True
return False
if not npc_active:
# Move the NPC to purgatory
this_npc['lastRoom'] = this_npc['room']
this_npc['room'] = purgatory_room
return False
def npc_respawns(npcs: {}) -> None:
"""Respawns inactive NPCs
"""
for _, this_npc in npcs.items():
if not this_npc['whenDied']:
continue
if not (int(time.time()) >=
this_npc['whenDied'] + this_npc['respawn']):
continue
if len(this_npc['familiarOf']) > 0:
continue
this_npc['whenDied'] = None
# this_npc['room'] = npcs_template[nid]['room']
this_npc['room'] = this_npc['lastRoom']
hp_str = str(this_npc['hp'])
log("respawning " + this_npc['name'] +
" with " + hp_str +
" hit points", "info")
def run_mobile_items(items_db: {}, items: {}, event_schedule,
scripted_events_db,
rooms: {}, map_area, clouds: {}) -> None:
"""Updates all NPCs
"""
curr_time = datetime.datetime.today()
curr_hour = curr_time.hour
sun = get_solar()
curr_day_of_week = datetime.datetime.today().weekday()
curr_month_number = \
int(datetime.datetime.today().strftime("%m"))
for item, item_obj in items.items():
item_id = item_obj['id']
item_obj2 = items_db[item_id]
# only non-takeable items
if item_obj2['weight'] > 0:
continue
if not item_obj2.get('moveTimes'):
continue
# Active now?
item_active = \
_entity_is_active(item_id, items, rooms,
item_obj2['moveTimes'],
map_area, clouds,
curr_time, curr_hour, sun,
curr_day_of_week,
curr_month_number)
# Remove if not active
if not item_active:
_remove_inactive_entity(item, items, item_id, items_db,
item_active)
continue
def run_npcs(mud, npcs: {}, players: {}, fights: {}, corpses: {},
scripted_events_db,
items_db: {}, npcs_template, rooms: {}, map_area, clouds: {},
event_schedule) -> None:
"""Updates all NPCs
"""
curr_time = datetime.datetime.today()
curr_hour = curr_time.hour
sun = get_solar()
now = int(time.time())
curr_day_of_week = datetime.datetime.today().weekday()
curr_month_number = \
int(datetime.datetime.today().strftime("%m"))
removed_fights = []
add_fights = []
for nid, this_npc in npcs.items():
# is the NPC a familiar?
npc_is_familiar = False
if len(this_npc['familiarOf']) > 0:
for pid, plyr in players.items():
if this_npc['familiarOf'] == plyr['name']:
npc_is_familiar = True
break
if not npc_is_familiar:
# is the NPC active according to moveTimes?
npc_active = \
_entity_is_active(nid, npcs, rooms,
this_npc['moveTimes'],
map_area, clouds,
curr_time, curr_hour, sun,
curr_day_of_week,
curr_month_number)
if not npc_active:
_remove_inactive_entity(nid, npcs, nid, npcs, npc_active)
continue
# Check if any player is in the same room, then send a random
# message to them
vocabulary_len = len(this_npc['vocabulary'])
if vocabulary_len > 0:
if now > \
this_npc['timeTalked'] + \
this_npc['talkDelay'] + \
this_npc['randomizer']:
rnd = randint(0, vocabulary_len - 1)
if vocabulary_len > 1:
while rnd is this_npc['lastSaid']:
rnd = randint(0, vocabulary_len - 1)
if this_npc['vocabulary'][rnd]:
for pid, plyr in players.items():
if this_npc['room'] == plyr['room']:
msg = '<f220>' + this_npc['name'] + \
'<r> says: <f86>' + \
this_npc['vocabulary'][rnd] + "\n\n"
mud.send_message(pid, msg)
this_npc['randomizer'] = \
randint(0, this_npc['randomFactor'])
this_npc['lastSaid'] = rnd
this_npc['timeTalked'] = now
# Iterate through fights and see if anyone is attacking an NPC -
# if so, attack him too if not in combat (TODO: and isAggressive =
# true)
is_in_fight = False
for fid, fght in fights.items():
if fght['s2id'] == nid and \
npcs[fght['s2id']]['isInCombat'] == 1 and \
fght['s2type'] == 'npc' and \
fght['s1type'] == 'pc' and \
fght['retaliated'] == 0:
# print('player is attacking npc')
# BETA: set las combat action to now when attacking a
# player
npcs[fght['s2id']]['lastCombatAction'] = \
int(time.time())
fght['retaliated'] = 1
npcs[fght['s2id']]['isInCombat'] = 1
new_fight = {
's1': npcs[fght['s2id']]['name'],
's2': players[fght['s1id']]['name'],
's1id': nid,
's2id': fght['s1id'],
's1type': 'npc',
's2type': 'pc',
'retaliated': 1
}
add_fights.append(new_fight)
is_in_fight = True
elif (fght['s2id'] == nid and
npcs[fght['s2id']]['isInCombat'] == 1 and
fght['s1type'] == 'npc' and
fght['retaliated'] == 0):
# print('npc is attacking npc')
# BETA: set last combat action to now when attacking a player
npcs[fght['s2id']]['lastCombatAction'] = \
int(time.time())
fght['retaliated'] = 1
npcs[fght['s2id']]['isInCombat'] = 1
new_fight = {
's1': npcs[fght['s2id']]['name'],
's2': players[fght['s1id']]['name'],
's1id': nid,
's2id': fght['s1id'],
's1type': 'npc',
's2type': 'npc',
'retaliated': 1
}
add_fights.append(new_fight)
is_in_fight = True
# NPC moves to the next location
if is_in_fight is False and \
len(this_npc['path']) > 0:
_move_npcs(npcs, players, mud, now, nid)
# Check if NPC is still alive, if not, remove from room and
# create a corpse, set isInCombat to 0, set whenDied to now
# and remove any fights NPC was involved in
if this_npc['hp'] <= 0:
this_npc['isInCombat'] = 0
this_npc['lastRoom'] = this_npc['room']
this_npc['whenDied'] = int(time.time())
# if the NPC is a familiar detach it from player
for _, plyr in players.items():
if plyr['name'] is None:
continue
if plyr['familiar'] == int(nid):
plyr['familiar'] -= 1
for fight, fght in fights.items():
if ((fght['s1type'] == 'npc' and
fght['s1id'] == nid) or
(fght['s2type'] == 'npc' and
fght['s2id'] == nid)):
# clear the combat flag
if fght['s1type'] == 'pc':
fid = fght['s1id']
players[fid]['isInCombat'] = 0
elif fght['s1type'] == 'npc':
fid = fght['s1id']
npcs[fid]['isInCombat'] = 0
if fght['s2type'] == 'pc':
fid = fght['s2id']
players[fid]['isInCombat'] = 0
elif fght['s2type'] == 'npc':
fid = fght['s2id']
npcs[fid]['isInCombat'] = 0
if fight not in removed_fights:
removed_fights.append(fight)
corpse_name = str(this_npc['name'] + "'s corpse")
if not corpse_exists(corpses,
this_npc['room'],
corpse_name):
corpses[len(corpses)] = {
'room': this_npc['room'],
'name': corpse_name,
'inv': deepcopy(this_npc['inv']),
'died': int(time.time()),
'TTL': this_npc['corpseTTL'],
'owner': 1
}
# inform players about the death of an npc
for pid, plyr in players.items():
if plyr['authenticated'] is not None:
if plyr['authenticated'] is not None and \
plyr['room'] == this_npc['room']:
mud.send_message(
pid,
"<f220>{}<r> ".format(this_npc['name']) +
"<f88>has been killed.\n")
this_npc['lastRoom'] = this_npc['room']
this_npc['room'] = None
this_npc['hp'] = npcs_template[nid]['hp']
# Drop NPC loot on the floor
dropped_items = []
for i in this_npc['inv']:
if not str(i).isdigit():
for pid, _ in players.items():
mud.send_message(
pid, 'NPC drops item: ' +
str(i) + ' is not an item number\n')
continue
if randint(0, 100) < 50:
item_id_str = str(i)
last_room_str = str(this_npc['lastRoom'])
add_to_scheduler("0|spawnItem|" + item_id_str + ";" +
last_room_str + ";0;0",
-1, event_schedule, scripted_events_db)
print("Dropped!" + str(items_db[int(i)]['name']))
dropped_items.append(str(items_db[int(i)]['name']))
# Inform other players in the room what items got dropped on NPC
# death
if len(dropped_items) > 0:
for _, plyr in players.items():
if plyr['name'] is None:
continue
if plyr['room'] == this_npc['lastRoom']:
mud.send_message(
plyr, "Right before <f220>" +
str(this_npc['name']) +
"<r>'s lifeless body collapsed to the floor, " +
"it had dropped the following items: " +
"<f220>{}".format(', '.join(dropped_items)) + "\n")
for fight in removed_fights:
del fights[fight]
for fight in add_fights:
fights[len(fights)] = fight
def _conversation_state(word: str, conversation_states: {},
nid: int, npcs: {},
match_ctr: int) -> (bool, bool, int):
"""Is the conversations with this npc in the given state?
Returns True if the conversation is in the given state
Also returns True if subsequent words can also be matched
and the current word match counter
"""
this_npc = npcs[nid]
if word.lower().startswith('state:'):
required_state = word.lower().split(':')[1].strip()
if this_npc['name'] in conversation_states:
if conversation_states[this_npc['name']] != required_state:
return False, False, match_ctr
return True, True, match_ctr + 1
return False, True, match_ctr
def _conversation_condition(word: str, conversation_states: {},
nid: int, npcs: {}, match_ctr: int,
players: {}, rooms: {},
id: int, cultures_db: {}) -> (bool, bool, int):
condition_type = ''
if '>' in word.lower():
condition_type = '>'
if '<' in word.lower():
condition_type = '<'
if '=' in word.lower():
condition_type = condition_type + '='
if len(condition_type) == 0:
return False, True, match_ctr
var_str = word.lower().split(condition_type)[0].strip()
curr_value = -99999
target_value = None
if var_str in ('hp', 'hitpoints'):
curr_value = players[id]['hp']
if var_str in ('hpPercent', 'hitpointspercent'):
curr_value = int(players[id]['hp'] * 100 / players[id]['hp'])
if var_str in ('cul', 'culture'):
if players[id].get('culture'):
curr_value = players[id]['culture']
target_value = word.lower().split(condition_type)[1].strip()
if var_str in ('roomcul', 'roomculture'):
curr_value = get_room_culture(cultures_db, rooms, players[id]['room'])
target_value = word.lower().split(condition_type)[1].strip()
if var_str in ('str', 'strength'):
curr_value = players[id]['str']
if var_str in ('wei', 'weight'):
curr_value = players[id]['wei']
if var_str in ('per', 'perception'):
curr_value = players[id]['per']
if var_str in ('lvl', 'level'):
curr_value = players[id]['lvl']
if var_str in ('exp', 'experience'):
curr_value = players[id]['exp']
if var_str in ('endu', 'endurance'):
curr_value = players[id]['endu']
if var_str in ('cha', 'charisma'):
curr_value = players[id]['cha']
if var_str in ('int', 'intelligence'):
curr_value = players[id]['int']
if var_str in ('agi', 'agility'):
curr_value = players[id]['agi']
if var_str in ('luc', 'luck'):
curr_value = players[id]['luc']
if var_str == 'cred':
curr_value = players[id]['cred']
if var_str == 'pp':
curr_value = players[id]['pp']
if var_str == 'ep':
curr_value = players[id]['ep']
if var_str == 'sp':
curr_value = players[id]['sp']
if var_str == 'cp':
curr_value = players[id]['cp']
if var_str == 'gp':
curr_value = players[id]['gp']
if var_str == 'reflex':
curr_value = players[id]['ref']
if var_str == 'cool':
curr_value = players[id]['cool']
if var_str == 'rest':
curr_value = players[id]['restRequired']
if var_str == 'language':
curr_value = players[id]['speakLanguage'].lower()
target_value = word.lower().split(condition_type)[1].strip()
condition_type = '='
if var_str == 'notlanguage':
curr_value = players[id]['speakLanguage'].lower()
target_value = word.lower().split(condition_type)[1].strip()
condition_type = '!='
if var_str == 'guild':
curr_value = players[id]['guild'].lower()
target_value = word.lower().split(condition_type)[1].strip()
condition_type = '='
if var_str == 'region':
rmid = players[id]['room']
curr_value = rooms[rmid]['region'].lower()
target_value = word.lower().split(condition_type)[1].strip()
condition_type = '='
if var_str == 'notguild':
curr_value = players[id]['guild'].lower()
target_value = word.lower().split(condition_type)[1].strip()
condition_type = '!='
if var_str == 'race':
curr_value = players[id]['race'].lower()
target_value = word.lower().split(condition_type)[1].strip()
condition_type = '='
if var_str == 'notrace':
curr_value = players[id]['race'].lower()
target_value = word.lower().split(condition_type)[1].strip()
condition_type = '!='
if var_str == 'characterclass':
curr_value = players[id]['characterClass'].lower()
target_value = word.lower().split(condition_type)[1].strip()
condition_type = '='
if var_str == 'notcharacterclass':
curr_value = players[id]['characterClass'].lower()
target_value = word.lower().split(condition_type)[1].strip()
condition_type = '!='
if var_str == 'enemy':
curr_value = players[id]['enemy'].lower()
target_value = word.lower().split(condition_type)[1].strip()
condition_type = '='
if var_str == 'notenemy':
curr_value = players[id]['enemy'].lower()
target_value = word.lower().split(condition_type)[1].strip()
condition_type = '!='
if var_str == 'affinity':
if npcs[nid]['affinity'].get(players[id]['name']):
curr_value = npcs[nid]['affinity'][players[id]['name']]
else:
curr_value = 0
if target_value is None:
target_value = int(word.lower().split(condition_type)[1].strip())
if not isinstance(curr_value, str):
if curr_value == -99999:
return False, True, match_ctr
if condition_type == '>':
if curr_value <= target_value:
return False, False, match_ctr
if condition_type == '<':
if curr_value >= target_value:
return False, False, match_ctr
if condition_type == '>=':
if curr_value < target_value:
return False, False, match_ctr
if condition_type == '<=':
if curr_value > target_value:
return False, False, match_ctr
if condition_type == '=':
if curr_value != target_value:
return False, False, match_ctr
if condition_type == '!=':
if curr_value == target_value:
return False, False, match_ctr
return True, True, match_ctr + 1
def _conversation_word_count(message: str, words_list: [], npcs: {},
nid: int, conversation_states: {},
players: {}, rooms: {}, id: int,
cultures_db: {}) -> int:
"""Returns the number of matched words in the message.
This is a 'bag of words/conditions' type of approach.
"""
match_ctr = 0
for possible_word in words_list:
if possible_word.lower().startswith('image:'):
continue
# Is the conversation required to be in a certain state?
state_matched, continue_matching, match_ctr = \
_conversation_state(possible_word,
conversation_states,
nid, npcs, match_ctr)
if not continue_matching:
break
if not state_matched:
# match conditions such as "strength < 10"
word_matched, continue_matching, match_ctr = \
_conversation_condition(possible_word,
conversation_states,
nid, npcs,
match_ctr,
players, rooms, id,
cultures_db)
if not continue_matching:
break
if not word_matched:
if possible_word.lower() in message:
match_ctr += 1
return match_ctr
def _conversation_give(best_match: str, best_match_action: str,
thing_given_id_str: str, players: {}, id: int,
mud, npcs: {}, nid: int, items_db: {},
puzzled_str: str, guilds_db: {}) -> bool:
"""Conversation in which an NPC gives something to you
"""
if best_match_action in ('give', 'gift'):
this_npc = npcs[nid]
if len(thing_given_id_str) > 0:
item_id = int(thing_given_id_str)
if item_id not in list(players[id]['inv']):
players[id]['inv'].append(str(item_id))
update_player_attributes(id, players, items_db, item_id, 1)
players[id]['wei'] = \
player_inventory_weight(id, players, items_db)
increase_affinity_between_players(players, id, npcs, nid,
guilds_db)
increase_affinity_between_players(npcs, nid, players, id,
guilds_db)
if '#' not in best_match:
mud.send_message(
id, "<f220>" + this_npc['name'] + "<r> says: " +
best_match + ".")
else:
mud.send_message(id, "<f220>" +
best_match.replace('#', '').strip() + ".")
mud.send_message(
id, "<f220>" + this_npc['name'] +
"<r> gives you " + items_db[item_id]['article'] +
' ' + items_db[item_id]['name'] + ".\n\n")
return True
mud.send_message(
id, "<f220>" + this_npc['name'] +
"<r> looks " + puzzled_str + ".\n\n")
return True
return False
def _conversation_skill(best_match: str, best_match_action: str,
best_match_action_param0: str,
best_match_action_param1: str,
players: {}, id: int, mud, npcs: {},
nid: int, items_db: {},
puzzled_str: str, guilds_db: {}) -> bool:
"""Conversation in which an NPC gives or alters a skill
"""
if best_match_action in ('skill', 'teach'):
this_npc = npcs[nid]
if len(best_match_action_param0) > 0 and \
len(best_match_action_param1) > 0:
new_skill = best_match_action_param0.lower()
skill_value_str = best_match_action_param1
if not players[id].get(new_skill):
log(new_skill + ' skill does not exist in player instance',
'info')
return False
if '+' in skill_value_str:
# increase skill
players[id][new_skill] = \
players[id][new_skill] + \
int(skill_value_str.replace('+', ''))
else:
# decrease skill
if '-' in skill_value_str:
players[id][new_skill] = \
players[id][new_skill] - \
int(skill_value_str.replace('-', ''))
else:
# set skill to absolute value
players[id][new_skill] = \
players[id][new_skill] + \
int(skill_value_str)
increase_affinity_between_players(players, id, npcs,
nid, guilds_db)
increase_affinity_between_players(npcs, nid, players,