-
Notifications
You must be signed in to change notification settings - Fork 11
/
life.py
3858 lines (2882 loc) · 107 KB
/
life.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
from globals import *
from overwatch import core
from alife import *
import graphics as gfx
import damage as dam
import pathfinding
import scripting
import missions
import crafting
import language
import contexts
import drawing
import logging
import weapons
import bad_numbers
import effects
import weather
import random
import damage
import timers
import dialog
import melee
import logic
import zones
import alife
import items
import menus
import maps
import copy
import time
import json
import fov
import sys
import os
try:
import render_los
CYTHON_RENDER_LOS = True
except:
CYTHON_RENDER_LOS = False
def load_life(name):
"""Returns life (`name`) structure from disk."""
if not '.json' in name:
name += '.json'
with open(os.path.join(LIFE_DIR, name), 'r') as e:
return json.loads(''.join(e.readlines()))
def calculate_base_stats(life):
"""Calculates and returns intital stats for `life`."""
stats = {'arms': None,
'legs': None,
'melee': None,
'speed_max': LIFE_MAX_SPEED}
_flags = life['flags'].split('|')
for flag in _flags:
if flag.count('['):
if not flag.count('[') == flag.count(']'):
raise Exception('No matching brace in ALife type %s: %s' % (species_type, flag))
stats[flag.lower().partition('[')[0]] = flag.partition('[')[2].partition(']')[0].split(',')
elif flag == 'HUNGER':
life['eaten'] = []
if not 'hands' in life:
life['hands'] = []
life['life_flags'] = life['flags']
stats['base_speed'] = bad_numbers.clip(LIFE_MAX_SPEED-len(stats['legs']), 0, LIFE_MAX_SPEED)
stats['speed_max'] = stats['base_speed']
for var in life['vars'].split('|'):
key,val = var.split('=')
try:
life[key] = int(val)
continue
except:
pass
try:
life[key] = life[val]
continue
except:
pass
try:
life[key] = val
continue
except:
pass
return stats
def get_max_speed(life):
"""Returns max speed based on items worn."""
_speed = life['base_speed']
_legs = get_legs(life)
for limb in life['body']:
if limb in _legs[:]:
_legs.remove(limb)
_limb = life['body'][limb]
_speed += _limb['cut']
for item in [get_inventory_item(life, i) for i in get_items_attached_to_limb(life, limb)]:
if not 'mods' in item:
continue
if 'speed' in item['mods']:
_speed -= item['mods']['speed']
_speed += len(_legs)*2
return bad_numbers.clip(_speed, 0, 255)
def initiate_raw(life):
"""Loads rawscript file for `life` from disk."""
life['raw'] = alife.rawparse.read(os.path.join(LIFE_DIR, life['raw_name']+'.dat'))
if not 'goap_goals_blacklist' in life:
life['goap_goals_blacklist'] = []
life['goap_goals'] = {}
life['goap_actions'] = {}
life['goap_plan'] = {}
alife.planner.parse_goap(life)
for goal in life['goap_goals_blacklist']:
del life['goap_goals'][goal]
def initiate_needs(life):
"""Creates innate needs for `life`."""
life['needs'] = {}
alife.survival.add_needed_item(life,
{'type': 'drink'},
satisfy_if=action.make_small_script(function='get_flag',
args={'flag': 'thirsty'}),
satisfy_callback=action.make_small_script(return_function='consume'))
alife.survival.add_needed_item(life,
{'type': 'food'},
satisfy_if=action.make_small_script(function='get_flag',
args={'flag': 'hungry'}),
satisfy_callback=action.make_small_script(return_function='consume'))
alife.survival.add_needed_item(life,
{'type': 'gun'},
satisfy_if=action.make_small_script(function='get_flag',
args={'flag': 'no_weapon'}),
satisfy_callback=action.make_small_script(return_function='pick_up_and_hold_item'))
def initiate_life(name):
"""Loads (and returns) new life type into memory."""
if name in LIFE_TYPES:
logging.warning('Life type \'%s\' is already loaded. Reloading...' % name)
life = load_life(name)
life['raw_name'] = name
#try:
initiate_raw(life)
#except:
# print 'FIXME: Exception on no .dat for life'
print 'MOVE GOAP INIT. HERE' * 50
if not 'icon' in life:
logging.warning('No icon set for life type \'%s\'. Using default (%s).' % (name,DEFAULT_LIFE_ICON))
_life['tile'] = DEFAULT_LIFE_ICON
if not 'flags' in life:
logging.error('No flags set for life type \'%s\'. Errors may occur.' % name)
for key in life:
if isinstance(life[key],unicode):
life[key] = str(life[key])
life.update(calculate_base_stats(life))
LIFE_TYPES[name] = life
return life
def initiate_limbs(life):
"""Creates skeleton of a character and all related variables. Returns nothing."""
body = life['body']
for limb in body:
#Unicode fix:
_val = body[limb].copy()
del body[limb]
body[str(limb)] = _val
body[limb] = body[str(limb)]
body[limb]['_flags'] = body[limb]['flags'].split('|')
body[limb]['flags'] = []
body[limb]['holding'] = []
body[limb]['cut'] = 0
body[limb]['bleeding'] = 0
body[limb]['bruised'] = False
body[limb]['broken'] = False
body[limb]['artery_ruptured'] = False
body[limb]['pain'] = 0
body[limb]['wounds'] = []
for flag in body[limb]['_flags']:
if not '[' in flag:
body[limb]['flags'].append(flag)
continue
_flag = flag.rstrip(']')
_key, _value = _flag.split('[')
try:
body[limb].update(json.loads(_value))
except:
logging.error('Limb %s of life type %s has an error in flag %s' % (limb, life['species'], _key))
if 'thickness' in body[limb]:
body[limb]['max_thickness'] = body[limb]['thickness']
if not 'parent' in body[limb]:
continue
if not 'children' in body[body[limb]['parent']]:
body[body[limb]['parent']]['children'] = [str(limb)]
else:
body[body[limb]['parent']]['children'].append(str(limb))
def get_raw(life, section, identifier):
if not alife.rawparse.raw_has_section(life, section) or not alife.rawparse.raw_section_has_identifier(life, section, identifier):
return []
return life['raw']['sections'][section][identifier]
def execute_raw(life, section, identifier, break_on_true=False, break_on_false=True, debug=False, dialog=[], **kwargs):
""" break_on_false is defaulted to True because the majority of situations in which this
function is used involves making sure all the required checks return True.
break_on_true doesn't see much usage - it implies that if one statement returns true, then
the rest do not need to be checked and True is returned.
"""
_broke_on_false = 0
if debug and not dialog:
print 'Grabbing raw: %s, %s' % (section, identifier)
if dialog:
_raw = dialog
else:
_raw = get_raw(life, section, identifier)
if not _raw:
logging.warning('Cannot grab raw for %s: %s, %s' % (life['raw_name'], section, identifier))
for rule_group in _raw:
if debug:
print 'Function group:', rule_group
for rule in rule_group:
if rule['string']:
return rule['string'].lower()
_func_args = {}
for value in rule['values']:
if 'key' in value:
_func_args[value['key']] = value['value']
if rule['no_args']:
if _func_args:
_func = rule['function'](**_func_args)
else:
_func = rule['function']()
elif rule['self_call']:
if _func_args:
_func = rule['function'](life, **_func_args)
else:
_func = rule['function'](life)
else:
try:
_func = rule['function'](life, **kwargs)
except Exception as e:
logging.critical('Function \'%s\' got invalid argument.' % rule['function'])
print rule
import traceback
traceback.print_exc()
sys.exit(1)
if debug:
print 'Function:', _func
print 'Function arguments:', _func_args
if rule['true'] == '*' or _func == rule['true']:
for value in rule['values']:
if 'flag' in value:
brain.knows_alife_by_id(life, kwargs['life_id'])[value['flag']] += value['value']
if break_on_true:
if _func:
return _func
return True
else:
if break_on_false:
_broke_on_false += 1
break
if break_on_true:
return False
if break_on_false and _broke_on_false==len(get_raw(life, section, identifier)):
return False
return True
def reset_think_rate(life):
life['think_rate'] = 1
def get_limb(life, limb):
"""Helper function. Finds and returns a limb."""
return life['body'][limb]
def get_all_limbs(body):
"""Deprecated helper function. Returns all limbs."""
#logging.warning('Deprecated: life.get_all_limbs() will be removed in next version.')
return body
def create_and_update_self_snapshot(life):
_ss = snapshots.create_snapshot(life)
snapshots.update_self_snapshot(life,_ss)
#logging.debug('%s updated their snapshot.' % ' '.join(life['name']))
def create_life(type, position=(0,0,2), name=None, map=None):
"""Initiates and returns a deepcopy of a life type."""
if not type in LIFE_TYPES:
raise Exception('Life type \'%s\' does not exist.' % type)
#TODO: Any way to get rid of this call to `copy`?
_life = copy.deepcopy(LIFE_TYPES[type])
if not name and _life['name'] == '$FIRST_AND_LAST_NAME_FROM_SPECIES':
_life['name'] = language.generate_first_and_last_name_from_species(_life['species'])
elif isinstance(name, list):
_life['name'] = name
elif name:
_life['name'] = name.split(' ')
elif not name:
_life['name'] = LIFE_TYPES[type]['name'].split(' ')
_life['id'] = str(WORLD_INFO['lifeid'])
_life['speed'] = _life['speed_max']
_life['pos'] = list(position)
_life['prev_pos'] = list(position)
_life['realpos'] = list(position)
_life['velocity'] = [0.0, 0.0, 0.0]
_life['created'] = WORLD_INFO['ticks']
maps.enter_chunk(get_current_chunk_id(_life), _life['id'])
try:
LIFE_MAP[_life['pos'][0]][_life['pos'][1]].append(_life['id'])
except:
logging.critical('Failed to add life at position %s, %s to LIFE_MAP.' % (_life['pos'][0], _life['pos'][1]))
raise Exception('Unrecoverable error. See previous log entry.')
_life['animation'] = {}
_life['path'] = []
_life['path_state'] = None
_life['actions'] = []
_life['conversations'] = []
_life['contexts'] = [] #TODO: Make this exclusive to the player
_life['dialogs'] = []
_life['encounters'] = []
_life['heard'] = []
_life['item_index'] = 0
_life['inventory'] = []
_life['flags'] = {}
_life['fov'] = None
_life['seen'] = []
_life['seen_items'] = []
_life['state'] = 'idle'
_life['state_action'] = ''
_life['state_tier'] = 9999
_life['state_flags'] = {}
_life['states'] = []
_life['gravity'] = 0.05
_life['targeting'] = None
_life['pain_tolerance'] = .15
_life['pain_threshold'] = 4
_life['asleep'] = 0
_life['asleep_reason'] = ''
_life['blood'] = calculate_max_blood(_life)
_life['consciousness'] = 100
_life['dead'] = False
_life['snapshot'] = {}
_life['shoot_timer'] = 0
_life['shoot_timer_max'] = 300
_life['strafing'] = False
_life['recoil'] = 0.0
_life['stance'] = 'standing'
_life['stances'] = {'tackle': 7,
'leap': 6,
'roll': 5,
'crawling': 5,
'duck': 4,
'crouching': 2,
'kick': 2,
'punch': 2,
'dodge': 2,
'deflect': 1,
'parry': 0,
'grapple': 0,
'standing': 0,
'off-balance': -1,
'trip': -1}
_life['next_stance'] = {'delay': 0,
'stance': None,
'towards': None,
'forced': False}
#TODO: Hardcoded for now
_life['moves'] = {'punch': {'effective_stance': -1, 'counters': ['deflect', 'dodge'], 'damage': {'force': 1}},
'kick': {'effective_stance': 2, 'counters': [], 'damage': {'force': 3}}}
_life['strafing'] = False
_life['aim_at'] = _life['id']
_life['discover_direction_history'] = []
_life['discover_direction'] = 270
_life['tickers'] = {}
_life['think_rate_max'] = LIFE_THINK_RATE
_life['think_rate'] = random.randint(0, _life['think_rate_max'])
_life['time_of_death'] = -1000
#Various icons...
# expl = #chr(15)
# up = chr(24)
# down = chr(25)
#ALife
_life['online'] = True
_life['know'] = {}
_life['know_items'] = {}
_life['known_items_type_cache'] = {}
_life['memory'] = []
_life['known_chunks'] = {}
_life['known_camps'] = {}
_life['known_groups'] = {}
_life['camp'] = None
_life['tempstor2'] = {}
_life['job'] = None
_life['jobs'] = []
_life['task'] = None
_life['completed_tasks'] = []
_life['completed_jobs'] = []
_life['rejected_jobs'] = []
_life['group'] = None
_life['needs'] = {}
_life['need_id'] = 1
_life['faction'] = None
_life['missions'] = {}
_life['mission_id'] = None
_life['stats'] = {}
alife.stats.init(_life)
initiate_needs(_life)
#Stats
_life['engage_distance'] = 15+random.randint(-5, 5)
initiate_limbs(_life)
WORLD_INFO['lifeid'] += 1
LIFE[_life['id']] = _life
return _life
def ticker(life, name, time, fire=False):
if name in life['tickers']:
if life['tickers'][name]>0:
life['tickers'][name] -= 1
return False
else:
del life['tickers'][name]
return True
else:
life['tickers'][name] = time
return fire
def clear_ticker(life, name):
if name in life['tickers']:
del life['tickers'][name]
def focus_on(life):
SETTINGS['following'] = life['id']
gfx.camera_track(life['pos'])
gfx.refresh_view('map')
def sanitize_heard(life):
del life['heard']
def sanitize_know(life):
for entry in life['know'].values():
entry['life'] = entry['life']['id']
if alife.brain.alife_has_flag(life, entry['life'], 'search_map'):
alife.brain.unflag_alife(life, entry['life'], 'search_map')
def prepare_for_save(life):
_delete_keys = ['raw', 'dialogs', 'fov']
_sanitize_keys = {'heard': sanitize_heard,
'know': sanitize_know}
for key in life.keys():#_delete_keys:
if key in _sanitize_keys:
_sanitize_keys[key](life)
elif key in _delete_keys:
del life[key]
#print life.keys()
#_save_string = json.dumps(life)
def post_save(life):
'''This is for getting the entity back in working order after a save.'''
life['heard'] = []
life['dialogs'] = []
life['fov'] = fov.fov(life['pos'], sight.get_vision(life))
for entry in life['know'].values():
entry['life'] = LIFE[entry['life']]
#NOTE: This section is for updating life entities after keys have been added
initiate_raw(life)
def load_all_life():
for life in LIFE.values():
post_save(life)
def save_all_life():
for life in LIFE.values():
prepare_for_save(life)
for key in life.keys():
try:
json.dumps(life[key])
except:
print life[key]
logging.critical('Life key cannot be offloaded: %s' % key)
raise Exception(key)
_life = json.dumps(LIFE)
for life in LIFE.values():
post_save(life)
return _life
def show_debug_info(life):
print ' '.join(life['name'])
print '*'*10
print 'Dumping memory'
print '*'*10
for memory in life['memory']:
print memory['target'], memory['text']
def get_engage_distance(life):
return 0
def change_goal(life, goal, tier, plan):
life['goap_plan'] = plan
if life['state'] == goal:
return False
logging.debug('%s set new goal: %s (%s) -> %s (%s)' % (' '.join(life['name']), life['state'], life['state_tier'], goal, tier))
life['state'] = goal
life['state_flags'] = {}
life['state_tier'] = tier
#stop(life)
life['states'].append(goal)
if len(life['states'])>SETTINGS['state history size']:
life['states'].pop(0)
#if groups.is_leader_of_any_group(life):
# speech.announce(life, 'group_leader_state_change', group=life['group'])
def set_pos(life, pos):
maps.leave_chunk(get_current_chunk_id(life), life['id'])
life['pos'] = list(pos[:])
maps.enter_chunk(get_current_chunk_id(life), life['id'])
def set_animation(life, animation, speed=2, loops=0):
life['animation'] = {'images': animation,
'speed': speed,
'speed_max': speed,
'index': 0,
'loops': loops}
#logging.debug('%s set new animation (%s loops).' % (' '.join(life['name']), loops))
def tick_animation(life):
if not life['animation']:
return life['icon']
if life['animation']['speed']:
life['animation']['speed'] -= 1
else:
life['animation']['index'] += 1
life['animation']['speed'] = life['animation']['speed_max']
if life['animation']['index']>=len(life['animation']['images']):
if life['animation']['loops']:
life['animation']['loops'] -= 1
life['animation']['index'] = 0
life['animation']['speed'] = 0
else:
life['animation'] = {}
return life['icon']
return life['animation']['images'][life['animation']['index']]
def get_current_camp(life):
return life['known_camps'][life['camp']]
def get_current_known_chunk(life):
_chunk_id = get_current_chunk_id(life)
if _chunk_id in life['known_chunks']:
return life['known_chunks'][_chunk_id]
return False
def get_current_known_chunk_id(life):
_chunk_key = '%s,%s' % ((life['pos'][0]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], (life['pos'][1]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'])
if _chunk_key in life['known_chunks']:
return _chunk_key
return False
def get_current_chunk(life):
_chunk_id = get_current_chunk_id(life)
return maps.get_chunk(_chunk_id)
def get_current_chunk_id(life):
return '%s,%s' % ((life['pos'][0]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], (life['pos'][1]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'])
def get_known_life(life, id):
if id in life['know']:
return life['know'][id]
return False
def create_conversation(life, gist, matches=[], radio=False, msg=None, **kvargs):
#logging.debug('%s started new conversation (%s)' % (' '.join(life['name']), gist))
_conversation = {'gist': gist,
'from': life,
'start_time': WORLD_INFO['ticks'],
'timeout_callback': None,
'id': time.time()}
_conversation.update(kvargs)
_for_player = False
for ai in [LIFE[i] for i in matches]:
#TODO: Do we really need to support more than one match?
#TODO: can_hear
if ai['id'] == life['id']:
continue
if not alife.stats.can_talk_to(life, ai['id']):
continue
if not alife.sight.can_see_position(ai, life['pos']):
if not get_all_inventory_items(life, matches=[{'name': 'radio'}]):
continue
if 'player' in ai:
_for_player = True
hear(ai, _conversation)
if msg:
say(life, msg, context=_for_player)
def get_surrounding_unknown_chunks(life, distance=1):
_current_chunk_id = get_current_chunk_id(life)
_surrounding_chunks = []
_start_x,_start_y = [int(value) for value in _current_chunk_id.split(',')]
for y in range(-distance,distance+1):
for x in range(-distance,distance+1):
if not x and not y:
continue
_next_x = _start_x+(x*WORLD_INFO['chunk_size'])
_next_y = _start_y+(y*WORLD_INFO['chunk_size'])
if _next_x<0 or _next_x>=MAP_SIZE[0]:
continue
if _next_y<0 or _next_y>=MAP_SIZE[1]:
continue
_chunk_key = '%s,%s' % (_next_x, _next_y)
if _chunk_key in life['known_chunks']:
continue
_surrounding_chunks.append(_chunk_key)
return _surrounding_chunks
def hear(life, what):
what['age'] = 0
life['heard'].append(what)
if 'player' in life:
_menu = []
_context = contexts.create_context(life, what, timeout_callback=what['timeout_callback'])
for reaction in _context['reactions']:
if reaction['type'] == 'say':
_menu.append(menus.create_item('single',
reaction['type'],
reaction['text'],
target=what['from'],
communicate=reaction['communicate'],
life=life))
elif reaction['type'] == 'action':
if 'communicate' in reaction:
_menu.append(menus.create_item('single',
reaction['type'],
reaction['text'],
target=what['from'],
action=reaction['action'],
score=reaction['score'],
delay=reaction['delay'],
communicate=reaction['communicate'],
life=life))
else:
_menu.append(menus.create_item('single',
reaction['type'],
reaction['text'],
target=what['from'],
action=reaction['action'],
score=reaction['score'],
delay=reaction['delay'],
life=life))
elif reaction['type'] == 'dialog':
life['dialogs'].append(reaction)
if _menu:
_context['items'] = _menu
life['contexts'].append(_context)
life['shoot_timer'] = DEFAULT_CONTEXT_TIME
#logging.debug('%s heard %s: %s' % (' '.join(life['name']), ' '.join(what['from']['name']) ,what['gist']))
def avoid_react(reaction):
life = reaction['life']
target = reaction['target']
#TODO: Target
add_action(life,
{'action': 'communicate',
'what': 'resist',
'target': target},
900,
delay=0)
def react(reaction):
life = reaction['life']
type = reaction['key']
text = reaction['values'][0]
target = reaction['target']
score = reaction.get('score', 0)
if 'communicate' in reaction:
for comm in reaction['communicate'].split('|'):
add_action(life,
{'action': 'communicate',
'what': comm,
'target': target},
score-1,
delay=0)
if type == 'say':
say(life, text)
elif type == 'action':
add_action(life,
reaction['action'],
reaction['score'],
delay=reaction['delay'])
menus.delete_menu(ACTIVE_MENU['menu'])
def say(life, text, action=False, volume=30, context=False, event=True):
if action:
set_animation(life, ['\\', '|', '/', '-'])
text = text.replace('@n', language.get_introduction(life))
_style = 'action'
else:
set_animation(life, ['!'], speed=8)
text = '%s: %s' % (' '.join(life['name']),text)
_style = 'speech'
if SETTINGS['following']:
#if bad_numbers.distance(LIFE[SETTINGS['following']]['pos'],life['pos'])<=volume:
if alife.sound.can_hear(life, SETTINGS['following']):
if context:
_style = 'important'
gfx.message(text, style=_style)
if action and event:
logic.show_event(text, life=life)
def memory(life, gist, *args, **kvargs):
_entry = {'text': gist, 'id': WORLD_INFO['memoryid']}
_entry['time_created'] = WORLD_INFO['ticks']
WORLD_INFO['memoryid'] += 1
for arg in args:
_entry.update(arg)
_entry.update(kvargs)
life['memory'].append(_entry)
#logging.debug('%s added a new memory: %s' % (' '.join(life['name']), gist))
if 'target' in kvargs:
create_and_update_self_snapshot(LIFE[kvargs['target']])
if 'trust' in kvargs:
brain.knows_alife_by_id(life, kvargs['target'])['trust'] += kvargs['trust']
logging.debug('%s changed trust in %s (%s): %s -> %s' % (' '.join(life['name']),
' '.join(LIFE[kvargs['target']]['name']),
gist,
brain.knows_alife_by_id(life, kvargs['target'])['trust']-1,
brain.knows_alife_by_id(life, kvargs['target'])['trust']))
return _entry['id']
def has_dialog(life):
for dialog_id in life['dialogs']:
if dialog.is_turn_to_talk(life, dialog_id):
return dialog_id
return False
def has_dialog_with(life, life_id):
for dialog_id in life['dialogs']:
_dialog = dialog.get_dialog(dialog_id)
_talkers = [_dialog['started_by'], _dialog['target']]
if _dialog['started_by'] in _talkers and _dialog['target'] in _talkers:
return dialog_id
return False
def has_group(life):
return life['group']
def get_memory(life, matches={}):
_memories = []
for memory in life['memory']:
_break = False
for key in matches:
if not key in memory or not (matches[key] == '*' or memory[key] == matches[key]):
_break = True
break
if not _break:
_memories.append(memory)
return _memories
def get_memory_via_id(life, memory_id):
for memory in life['memory']:
if memory['id'] == memory_id:
return memory
raise Exception('Invalid memory passed to get_memory_via_id(): %s' % memory_id)
def delete_memory(life, matches={}):
for _memory in get_memory(life, matches=matches):
life['memory'].remove(_memory)
logging.debug('%s deleted memory: %s' % (' '.join(life['name']), _memory['text']))
def get_recent_memories(life,number):
return life['memory'][len(life['memory'])-number:]
def create_recent_history(life,depth=10):
_story = ''
_line = '%s %s ' % (life['name'][0],life['name'][1])
for entry in life['memory'][len(life['memory'])-depth:]:
_line += '%s.' % entry['text']
return _line
def crouch(life):
if life['stance'] == 'standing':
_delay = 5
elif life['stance'] == 'crawling':
_delay = 15
else:
_delay = melee.get_stance_score(life, 'crouching')
set_animation(life, ['n', '@'], speed=_delay/2)
add_action(life,{'action': 'crouch'},
200,
delay=_delay)
def stand(life):
if life['stance'] == 'crouching':
_delay = 5
elif life['stance'] == 'crawling':
_delay = 15
else:
_delay = melee.get_stance_score(life, 'standing')
set_animation(life, ['^', '@'], speed=_delay/2)
add_action(life,{'action': 'stand'},
200,
delay=_delay)
def crawl(life, force=False):
if force:
life['stance'] = 'crawling'
set_animation(life, ['v', '@'], speed=15)
return True
if life['stance'] == 'standing':
_delay = 15
elif life['stance'] == 'crouching':
_delay = 5
else:
_delay = melee.get_stance_score(life, 'crawling')
set_animation(life, ['v', '@'], speed=_delay/2)
add_action(life,{'action': 'crawl'},
200,
delay=_delay)
def stop(life):
clear_actions(life)
alife.brain.unflag(life, 'chunk_path')
life['path'] = []
def path_dest(life):
"""Returns the end of the current path."""
if not life['path']:
return None
_existing_chunk_map = brain.get_flag(life, 'chunk_path')
if _existing_chunk_map:
return _existing_chunk_map['end']
return tuple(life['path'][len(life['path'])-1])
def can_traverse(life, pos):
if WORLD_INFO['map'][pos[0]][pos[1]][life['pos'][2]+1]:
if WORLD_INFO['map'][pos[0]][pos[1]][life['pos'][2]+2]:
return False
return True
if not WORLD_INFO['map'][pos[0]][pos[1]][life['pos'][2]]:
if WORLD_INFO['map'][pos[0]][pos[1]][life['pos'][2]-1]:
return True
if WORLD_INFO['map'][pos[0]][pos[1]][life['pos'][2]]:
return True
return False
def can_walk_to(life, pos):
if len(pos) == 3:
pos = list(pos)