-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.py
executable file
·2047 lines (2004 loc) · 102 KB
/
net.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
"""
Connect to nethack.alt.org
and play some nethack.
"""
import profile
import socket
import select
import sys
import time
import random
import re
from AscTelnet import Telnet
from AscTelnet import STATE_WANT_TO_SEND_DATA
from AscTelnet import STATE_WAITING_FOR_DATA
from AscTelnet import STATE_WANT_TO_SEND_PING
from AscTelnet import STATE_WAITING_FOR_DATA_AND_PONG
from AscAnsi import Ansi, AnsiSquare
from AscSelect import ObjectPicker
from AscUtil import ascii_to_meta
from AscUtil import get_bounding_coordinates
from AscInventory import AscInventory
from AscInventory import gen_things_that_are_here, get_pick_up_what, gen_floor_items, item_selection_helper
from AscLore import AscLore, IdGenerator
import AscSokoban
# Some important constants are imported here:
# HM_*
# SM_*
# Also:
# LevelMap
# LevelSquare
from AscLevel import *
# Some important constants are imported here:
# BURDEN_LEVEL_*
# HUNGER_LEVEL_*
# Also:
# BotStatus
from AscStatus import *
class CidBot:
def get_username(self):
return '...'
def get_password(self):
return '...'
def get_role(self):
return 'Plunderer'
class GatherBot(CidBot):
"""
This ball of mud constantly needs refactoring.
"""
def __init__(self):
self.id_generator = IdGenerator()
self.dungeon = Dungeon()
self.log = open('gatherer.log', 'a')
print >> self.log, '__init__'
self.message_log = open('messages.log', 'a')
self.levelmap = None
self.lore = AscLore()
self.inventory = AscInventory(self.lore)
# open adjacent doors
self.last_door_opening_location = None
self.last_door_opening_direction = None
# identify adjacent traps
self.unidentified_adjacent_trap_location = None
self.unidentified_adjacent_trap_direction = None
# vital stats of the bot; also turns and dlvl
self.status = BotStatus()
# this gathers messages across '--More--' screens.
self.messages = []
# where was the cursor last real turn?
self.last_cursor_location = None
# these variables are for keeping track of when and
# where we started searching for traps or secret doors.
self.search_location = None
self.search_turn_begin = None
# this is the location of an object we chose
# using the remote object viewer
self.pick_an_object_location = None
# flag selection mode
# the words "Pick an object." are not always at the top of the screen
# while in this mode if symbols are used to move the cursor.
self.moving_the_selection_cursor = False
# did we read a message that indicates that we should look at the ground?
self.should_look_at_ground = False
# are we in the process of looking at the ground?
self.ground_check = False
# are we trapped in a pit?
# if we are then we cannot reach over the edge of a pit to open a door.
self.trapped_pit = False
# which region is trying to link to another region?
self.linking_region = None
# this is only true before looking at the first square with ':'.
self.checked_first_square = False
# these variables help enforce the separation between
# reading messages and taking actions.
self.should_pray = False
self.should_enhance = False
self.should_quit = False
# we should check our inventory when we start
self.should_do_inventory = True
# do we know if something on the ground is worth picking up?
self.should_pick_up = False
# the inventory-like screens provide annoyingly little context so we have to do this ourselves
self.should_read_inventory = False
self.should_continue_pick_up = False
self.should_continue_drop = False
self.should_continue_looting = False
# which item to apply?
self.apply_letter = None
# which item to eat?
self.eating_letter = None
# what is the throwing state?
self.missile_letter = None
self.missile_direction = None
# which location are we trying to attack?
# this is important for distinguishing between friendly and hostile monsters
self.attack_location = None
# this is a list of letters remaining in the name of an item that is being named
self.remaining_moniker_letters = None
# this is to help keep track of where we are within the dungeon
self.expecting_level_change = False
# do we have lycanthropy?
# this is not in the status object because its state is only known through messages
self.lycanthropic = False
# how much nutrition have we consumed since the last time we prayed?
self.consumed_nutrition = 500
# are we turning to stone?
self.turning_to_stone = False
# are we stuck?
self.recent_initiative_commands = []
self.recent_initiative_hashes = []
# do we need to look at a square to see why we are stuck?
self.stuck_target_location = None
self.stuck_target_direction = None
# if we have determined that the bot is stuck
# and it is not because of something embedded in a dungeon feature
# then try to open it in case it is something on an open door
self.should_open_stuck_target = False
# which way did we try to push the boulder and where do we expect to end up?
self.last_sokoban_push_delta = None
self.last_sokoban_push_target = None
# did our last attempt to push the boulder fail?
self.boulder_failure = False
# which direction are we trying to untrap something?
self.untrap_direction = None
# what is the name of the large container we are trying to untrap?
self.untrap_moniker = None
# in what direction do we want to lock a container?
self.container_unlocking_direction = None
# what is the name of the large container we are trying to unlock?
# this is relevant for interpreting a message that something seems to be locked
self.unlock_moniker = None
# what is the name of the large container we are trying to loot?
# this is relevant for interpreting a message that something seems to be locked
self.loot_moniker = None
def loops_forever(self):
return True
def invalidate_inventory(self):
self.should_do_inventory = True
def notify_dropped_letter(self, letter):
"""
This is called just before the drop of a letter from inventory is committed.
Use this to update the names of large containers on the square.
"""
item = self.inventory.letter_to_item.get(letter, None)
if not item:
print >> self.log, 'ERROR: the dropped letter', letter, 'does not correspond to anything in inventory'
return
if item.is_large_container():
moniker = item.get_moniker()
if moniker:
level_square = self.levelmap.level[self.last_cursor_location]
if moniker in level_square.large_container_names:
print >> self.log, 'ERROR: the large container named', moniker, 'has been dropped here before'
else:
print >> self.log, 'dropping a large container named', moniker, 'on the last known player location', self.last_cursor_location
level_square.large_container_names.append(moniker)
self.lore.get_or_create_item(moniker).untrap_attempt_count = 0
def process_incoming_message(self, ansi, incoming_ascii_strings, bloated_string):
"""
Add messages to the message buffer.
This deals with stuff like notifications of cheese on the floor
or when multiple messages arrive at once.
Return values:
a return value if this is a --More-- message or an (end) message.
None otherwise (i.e. we need to do something more sophisticated than hit return)
"""
# read the message bar at the top of the screen
top_string = incoming_ascii_strings[0]
# if there is a handful of items on the floor then see if anything is worth picking up
if 'Things that are here' in bloated_string:
items = list(gen_things_that_are_here(incoming_ascii_strings, bloated_string))
if items:
print >> self.log, 'found a pile of items on the floor:'
for item in items:
print >> self.log, '\t', item
if self.inventory.should_pick_up_something(items):
print >> self.log, 'something seems interesting'
self.should_pick_up = True
else:
print >> self.log, 'nothing seems interesting'
# see if we're supposed to press a key
# otherwise print all messages since the last real move
if '--More--' in bloated_string:
line_index = 0
while True:
line = ''.join(x.to_ascii_char() for x in ansi.lines[line_index])
index = line.find('--More--')
if index >= 0:
message = line[:index]
if message:
self.messages.append(message)
break
else:
self.messages.append(line)
line_index += 1
print >> self.log, 'Responding to --More--'
return '\n'
else:
if top_string.strip():
self.messages.append(top_string)
for message in self.messages:
print >> self.message_log, message
return None
def process_incoming_special(self, incoming_ascii_strings, bloated_string):
"""
Process only a few well defined screens.
All of the screens processed here have been immediately requested the prior bot turn.
This includes:
'i' : single or multi-page showing inventory
',' : single or multi-page picking stuff up
'D' : single or multi-page dropping stuff
'#loot in' : single or multi-page putting stuff in a container
'#loot out' : single or multi-page getting stuff out of a container
"""
top_string = incoming_ascii_strings[0]
# Respond to the inventory screen if we are expecting one.
if self.should_read_inventory:
self.should_read_inventory = False
if 'Not carrying anything' in bloated_string:
# We are carrying nothing except possibly gold
print >> self.log, 'the bot has been completely robbed'
self.inventory = AscInventory(self.lore)
elif '(end)' in bloated_string:
# We are carrying a single page of inventory
self.inventory.add_inventory(incoming_ascii_strings, bloated_string)
print >> self.log, 'finished reading the single page of inventory'
print >> self.log, self.inventory
return '\n'
else:
# We are carrying multiple pages of inventory
pattern = r'\((\d+) of (\d+)\)'
m = re.search(pattern, bloated_string)
if m:
self.inventory.add_inventory(incoming_ascii_strings, bloated_string)
first, last = m.groups()
if first == last:
print >> self.log, 'finished reading the last page of a multi-page inventory'
print >> self.log, self.inventory
return '\n'
else:
print >> self.log, 'finished reading inventory page', first, 'of', last
self.should_read_inventory = True
return ' '
else:
print >> self.log, 'ERROR: expected an inventory message but none was found'
# Respond to the pick up screen if we see one or are expecting one.
if self.should_continue_pick_up or 'Pick up what' in top_string:
# When we get this prompt it means we are on the first page.
# Reset the inventory reading flag so that if we end up not picking anything up
# then we do not check our inventory unnecessarily.
if 'Pick up what' in top_string:
print >> self.log, 'we do not need to check our inventory if nothing is selected'
self.should_do_inventory = False
# This is set to true if we discover that more pages remain.
self.should_continue_pick_up = False
response = get_pick_up_what(incoming_ascii_strings, bloated_string)
if response:
unselected_letter_item_pairs, selected_letter_item_pairs = response
selected_items = [item for (letter, item) in selected_letter_item_pairs]
if selected_items:
print >> self.log, 'something was selected so we need to check our inventory when we are finished'
self.invalidate_inventory()
letters = list(self.inventory.gen_letter_acquisition_selection(unselected_letter_item_pairs, selected_items))
if letters:
letter = letters[0]
self.should_continue_pick_up = True
print >> self.log, 'selecting letter', letter
return letter
pattern = r'\((\d+) of (\d+)\)'
m = re.search(pattern, bloated_string)
if m:
first, last = m.groups()
if first == last:
print >> self.log, 'committing the last page of a multi-page pick up action'
return '\n'
else:
self.should_continue_pick_up = True
print >> self.log, 'committing a page of a multi-page pick up action'
return ' '
elif '(end)' in bloated_string:
print >> self.log, 'committing the single page pick up action'
return '\n'
else:
print >> self.log, 'WARNING: the selection screen for picking up an item was not well terminated'
else:
print >> self.log, 'WARNING: tried to pick up something but nothing could be read'
# Respond to a looting screen if we are expecting one.
if self.should_continue_looting or 'Take out what?' in top_string:
# When we get this prompt it means we are on the first page.
# Reset the inventory reading flag so that if we end up not picking anything up
# then we do not check our inventory unnecessarily.
if 'Take out what?' in top_string:
self.should_do_inventory = False
# This is set to true if we discover that more pages remain.
self.should_continue_looting = False
response = get_pick_up_what(incoming_ascii_strings, bloated_string)
if response:
unselected_letter_item_pairs, selected_letter_item_pairs = response
selected_items = [item for (letter, item) in selected_letter_item_pairs]
if selected_items:
print >> self.log, 'something was selected so we need to check our inventory when we are finished'
letters = list(self.inventory.gen_letter_acquisition_selection(unselected_letter_item_pairs, selected_items))
if letters:
letter = letters[0]
self.should_continue_looting = True
self.invalidate_inventory()
print >> self.log, 'selecting letter', letter
return letter
pattern = r'\((\d+) of (\d+)\)'
m = re.search(pattern, bloated_string)
if m:
first, last = m.groups()
if first == last:
print >> self.log, 'committing the last page of a multi-page looting action'
return '\n'
else:
self.should_continue_looting = True
print >> self.log, 'committing a page of a multi-page looting action'
return ' '
elif '(end)' in bloated_string:
print >> self.log, 'committing the single page looting action'
return '\n'
else:
print >> self.log, 'WARNING: the selection screen for looting was not well terminated'
else:
print >> self.log, 'WARNING: tried to take something out of a container but nothing could be read'
# Respond to the drop screen if we see one or are expecting one.
if self.should_continue_drop or 'What would you like to drop' in top_string:
self.should_continue_drop = False
response = item_selection_helper(incoming_ascii_strings, bloated_string)
if response:
unselected_letter_item_pairs, selected_letter_item_pairs = response
cursor_square = self.levelmap.level[self.last_cursor_location]
total_drop_letters = set(self.inventory.gen_letter_drop_selection(cursor_square))
current_page_drop_letters = (total_drop_letters & set(unselected_letter_item_pairs))
if current_page_drop_letters:
letter = current_page_drop_letters[0]
self.should_continue_drop = True
self.invalidate_inventory()
self.notify_dropped_letter(letter)
print >> self.log, 'selecting letter', letter
return letter
pattern = r'\((\d+) of (\d+)\)'
m = re.search(pattern, bloated_string)
if m:
first, last = m.groups()
if first == last:
print >> self.log, 'committing the last page of a multi-page drop action'
return '\n'
else:
self.should_continue_drop = True
print >> self.log, 'committing a page of a multi-page drop action'
return ' '
elif '(end)' in bloated_string:
print >> self.log, 'committing the single page drop action'
return '\n'
else:
print >> self.log, 'WARNING: the selection screen for dropping an item was not well terminated'
else:
print >> self.log, 'WARNING: tried to drop something but nothing could be read'
# no special messages
return None
def process_incoming_request(self, ansi, incoming_ascii_strings, bloated_string):
"""
Process requests that use only the top line.
Also process requests for which the cursor is not in the map region.
"""
top_string = incoming_ascii_strings[0]
# get a request from the top line of the screen
print >> self.log, top_string
# enhance the first available skill
if 'Pick a skill to enhance' in top_string:
print >> self.log, 'enhancing a skill'
return 'a'
# respond to a loot confirmation request
if 'loot it?' in top_string:
print >> self.log, 'got a nethack loot confirmation request'
if self.loot_moniker:
lore_item = self.lore.get_existing_item(self.loot_moniker)
if lore_item:
pattern = r'There is (.+) named ([\da-zA-Z]+) here, loot it'
m = re.search(pattern, top_string)
if m:
description, moniker = m.groups()
if moniker == self.loot_moniker:
lore_item.locked = False
if not lore_item.looted:
print >> self.log, 'confirmed the request to loot the unlooted container named', self.loot_moniker
return 'y'
else:
print >> self.log, 'declined the request to loot the previously looted container named', self.loot_moniker
return 'n'
else:
print >> self.log, 'WARNING: the expected moniker', self.loot_moniker, 'did not match the observed moniker', moniker
else:
print >> self.log, 'WARNING: no named container was visible here'
else:
print >> self.log, 'WARNING: no existing lore item could be found for the name', self.loot_moniker
else:
print >> self.log, 'WARNING: self.loot_moniker was not present'
# unlock or pick the lock of a locked large container
if 'unlock it?' in top_string or 'pick its lock?' in top_string:
if self.unlock_moniker:
lore_item = self.lore.get_existing_item(self.unlock_moniker)
if lore_item:
return 'y'
return 'n'
# do not put anything into a looted container
# TODO stash something in the container
# TODO reset self.loot_moniker to None when looting has finished
if 'Do you wish to put something in' in top_string:
if self.loot_moniker:
lore_item = self.lore.get_existing_item(self.loot_moniker)
if lore_item:
lore_item.looted = True
lore_item.locked = False
return 'n'
# do not take anything out of a looted container
# TODO reset self.loot_moniker to None when looting has finished
if 'Do you want to take something out of' in top_string:
if self.loot_moniker:
lore_item = self.lore.get_existing_item(self.loot_moniker)
if lore_item:
lore_item.locked = False
if not lore_item.looted:
lore_item.looted = True
lore_item.locked = False
return 'y'
return 'n'
# untrap a large container, door, or floor trap
if 'Check it for traps' in top_string:
pattern = r'named ([\da-zA-Z]+)'
m = re.search(pattern, top_string)
if m:
moniker = m.groups()[0]
lore_item = self.lore.get_existing_item(moniker)
if lore_item:
if lore_item.untrap_attempt_count < 3:
print >> self.log, 'untrapping large container', moniker
lore_item.untrap_attempt_count += 1
self.untrap_moniker = moniker
return 'y'
else:
print >> self.log, 'the name of the large container to untrap was not found in memory'
print >> self.log, 'strange name:', moniker
return 'n'
else:
print >> self.log, 'the large container to untrap was unnamed'
return 'n'
# do not try to remove a spider web
if 'Remove the web?' in top_string:
return 'n'
# do not try to disarm a trap on a chest
if 'Disarm it?' in top_string:
if self.untrap_moniker:
moniker = self.untrap_moniker
self.untrap_moniker = None
print >> self.log, 'found a trap on the item named', moniker
lore_item = self.lore.get_existing_item(moniker)
lore_item.trapped = True
else:
print >> self.log, 'ERROR: we were asked to disarm an unknown item'
return 'n'
# begin, continue, or finish naming an object
# invalidate the inventory when the moniker is committed
if 'What do you want to name this' in top_string or 'What do you want to name these' in top_string:
if self.remaining_moniker_letters is None:
name = self.id_generator.get_next_id()
if not name:
print >> self.log, 'ERROR: no id was generated'
elif len(name) == 1:
self.remaining_moniker_letters = [name]
else:
self.remaining_moniker_letters = list(name)
if self.remaining_moniker_letters:
letter = self.remaining_moniker_letters.pop(0)
return letter
else:
self.remaining_moniker_letters = None
self.invalidate_inventory()
return '\n'
# No we do not want to eat carrion.
if 'eat it?' in top_string:
return 'n'
# yes I want to name an individual object
if 'Name an individual object' in top_string:
return 'y'
# We want to eat the item that we have chosen previously.
# Request that the inventory be checked after eating.
if 'What do you want to eat' in top_string:
eating_letter = self.eating_letter
self.eating_letter = None
if eating_letter:
self.invalidate_inventory()
return eating_letter
else:
print >> self.log, 'WARNING: expected an item to eat'
# We want to throw the item that we have chosen previously
# in the direction that was chosen previously.
# Request that the inventory be checked after throwing.
if 'What do you want to throw' in top_string:
missile_letter = self.missile_letter
self.missile_letter = None
if missile_letter:
self.invalidate_inventory()
return missile_letter
else:
print >> self.log, 'WARNING: expected an item to throw'
# Decide which object to name.
# Request that the inventory be checked after naming.
if 'What do you want to name?' in top_string:
letters = tuple(self.inventory.gen_letter_naming_selection())
if letters:
self.invalidate_inventory()
return letters[0]
else:
print >> self.log, 'WARNING: expected an item to name'
# decide what to drop using the single item drop menu
if 'What do you want to drop' in top_string:
cursor_square = self.levelmap.level[self.last_cursor_location]
letters = tuple(self.inventory.gen_letter_drop_selection(cursor_square))
if len(letters) == 1:
letter = letters[0]
self.invalidate_inventory()
self.notify_dropped_letter(letter)
return letter
else:
print >> self.log, 'WARNING: expected to choose a single item to drop but found %d items: %s' % (len(letters), str(letters))
# decide what to take off
if 'What do you want to take off' in top_string:
take_letter = self.inventory.get_take_letter()
if take_letter:
self.invalidate_inventory()
return take_letter
return '\x1b'
# decide what to wear
if 'What do you want to wear' in top_string:
wear_letter = self.inventory.get_wear_letter()
if wear_letter:
self.invalidate_inventory()
return wear_letter
return '\x1b'
# confirm that we want to unlock the door
if 'Unlock it?' in top_string:
return 'y'
# look for the 'Pick an object.' prompt and respond appropriately
if 'Pick an object.' in top_string or self.moving_the_selection_cursor:
return self.pick_an_object(ansi)
# handle a potential attack on a peaceful monster
if 'Really attack' in top_string:
if self.attack_location:
# get the target square and reset the attack location
target_square = self.levelmap.level[self.attack_location]
self.attack_location = None
monster = target_square.monster
if monster:
if monster.is_peaceful():
# if it is already known to be peaceful then we must be attacking it for a reason
print >> self.log, 'deliberately attacking a peaceful monster'
return 'y'
elif self.levelmap.level_branch == LEVEL_BRANCH_SOKOBAN and self.levelmap.sokoban_queue:
# if we are in sokoban and have not finished the puzzle then attack a peaceful monster so it does not get in the way
print >> self.log, 'deliberately attacking a peaceful monster because we are not finished with this sokoban puzzle yet'
return 'y'
else:
# if it is not known to be peaceful then mark it as peaceful and leave it alone for now
monster.set_peaceful()
print >> self.log, 'refraining from attacking a peaceful monster'
return 'n'
else:
print >> self.log, 'ERROR: we are attacking or moving onto a square that unexpectedly has a monster, and it is peaceful'
else:
print >> self.log, 'ERROR: we are unexpectedly attacking or moving onto a monster, and it is peaceful'
# apply an item for unlocking a door for example
if 'What do you want to use or apply' in top_string:
if self.apply_letter:
letter = self.apply_letter
self.apply_letter = None
return letter
else:
print >> self.log, 'ERROR: no item was selected for application'
# do something in some direction
if 'In what direction?' in top_string:
if self.unidentified_adjacent_trap_direction:
# identify an adjacent trap
direction = self.unidentified_adjacent_trap_direction
self.unidentified_adjacent_trap_direction = None
return direction
elif self.last_door_opening_direction:
# open, kick, pick, or unlock a door
direction = self.last_door_opening_direction
self.last_door_opening_direction = None
return direction
elif self.missile_direction:
# throw something and look at the inventory afterwards
# this is for throwing food to tame pets,
# for throwing gems to teleport unicorns,
# and for throwing weapons at monsters behind boulders in sokoban.
direction = self.missile_direction
self.missile_direction = None
self.missile_letter = None
self.invalidate_inventory()
return direction
elif self.untrap_direction:
# untrap a large container, door, or floor trap.
direction = self.untrap_direction
self.untrap_direction = None
return direction
elif self.container_unlocking_direction:
# unlock a container
direction = self.container_unlocking_direction
self.container_unlocking_direction
return direction
# use the default value for whatever unknown request is putting
# the cursor outside the map region.
if self.levelmap:
loc = (ansi.row, ansi.col)
if loc not in self.levelmap.level:
print >> self.log, 'unknown request such that the cursor is outside the map region'
return '\n'
# if we did not find anything useful to do then return None
return None
def pick_an_object(self, ansi):
"""
Generate a response to the 'Pick an object.' prompt.
This involves pathing the semicolon to a target.
The target could be an unknown trap or a square that is causing the bot to be stuck.
"""
# TODO do not create a new ObjectPicker for each sub-move
self.moving_the_selection_cursor = True
# first determine the set of interesting locations
if self.stuck_target_location:
# we are trying to figure out why we are stuck
interesting_set = set([self.stuck_target_location])
else:
# we are trying to figure out the identity of some traps
interesting_set = set(self.levelmap.gen_unidentified_trap_locations(ansi))
# make sure we have an interesting set
if not interesting_set:
print >> self.log, 'there was nothing interesting for the "Pick an object." prompt'
return '\x1b'
# note the location of the cursor
current_location = (ansi.row, ansi.col)
# if we are at an interesting location then remember it and press the semicolon
if current_location in interesting_set:
self.pick_an_object_location = current_location
self.moving_the_selection_cursor = False
print >> self.log, 'selecting the target square'
return ';'
# otherwise return the command that goes towards an interesting object
location_to_ascii = {}
for row, line in enumerate(ansi.lines):
for col, ansi_square in enumerate(line):
location_to_ascii[(row, col)] = ansi_square.char
picker = ObjectPicker(location_to_ascii, interesting_set)
result = picker.get_best_move(current_location)
if not result:
print >> self.log, 'the picker thinks we are already at the location'
assert False
else:
print >> self.log, 'moving the selection cursor towards the target square with this command:', result
return result
def detect_sokoban_level(self, ansi):
"""
Look through the eight or so levels of sokoban that are hardcoded in AscSokoban.
If any have an identical wall pattern to the current level then return the name of the level.
If no sokoban level was detected then return None.
For detection purposes any ascii '-' or '|' is a wall.
The match must be bidirectional.
"""
# Define wall ascii symbols for the purpose of sokoban level detection.
sokoban_wall_characters = ('-', '|')
# Get the set of wall locations on the observed ansi map.
raw_wall_locations = set()
for loc in self.levelmap.level:
row, col = loc
ansi_square = ansi.lines[row][col]
if ansi_square.char in sokoban_wall_characters:
raw_wall_locations.add(loc)
# If no walls were observed then the level was not detected.
# TODO what about engulfing?
if not raw_wall_locations:
print >> self.log, 'no matching sokoban level was found (no walls were seen)'
return None
# Get the bounding wall rectangle of the observed ansi map on the screen.
row_min, col_min, row_max, col_max = get_bounding_coordinates(raw_wall_locations)
# Spacially translate wall locations to the upper left.
translated_wall_locations = set()
for loc in raw_wall_locations:
row, col = loc
translated_location = (row - row_min, col - col_min)
translated_wall_locations.add(translated_location)
# See if the wall pattern matches that of a hard coded Sokoban level.
matching_level_names = []
for level_string, level_name in AscSokoban.all_level_strings_and_names:
level = AscSokoban.sokoban_string_to_map(level_string)
sokoban_wall_locations = set(loc for loc, c in level.items() if c in sokoban_wall_characters)
if sokoban_wall_locations == translated_wall_locations:
matching_level_names.append(level_name)
# If we got no matches or more than one match then fail.
if not matching_level_names:
print >> self.log, 'no matching sokoban level was found'
return None
elif len(matching_level_names) > 1:
print >> self.log, 'ERROR: multiple matching sokoban levels were found'
return None
else:
level_name = matching_level_names[0]
print >> self.log, 'found a unique matching sokoban level:', level_name
return level_name
def process_dlvl_change(self, new_ansi, old_dlvl, new_dlvl, old_cursor_location, new_cursor_location):
"""
"""
# Was the dlvl change degenerate?
if old_dlvl is None:
print >> self.log, 'descending to the starting location'
return
# Decide if the level change was a descent or an ascent.
if old_dlvl < new_dlvl:
change_string = 'descent'
else:
change_string = 'ascent'
# See if the new level matches a sokoban level.
sokoban_name = self.detect_sokoban_level(new_ansi)
# Remove the player region from the old level.
old_player_region = self.levelmap.get_player_region()
self.levelmap.regions = [r for r in self.levelmap.regions if r is not old_player_region]
# Remove links from the old level that include the player region.
self.levelmap.region_links = [link for link in self.levelmap.region_links if old_player_region not in link.region_pair]
# Can we find a linking region from the old level?
self.linking_region = None
if self.expecting_level_change:
self.expecting_level_change = False
if abs(old_dlvl - new_dlvl) == 1:
matching_regions = []
for region in self.levelmap.regions:
if region.location == old_cursor_location:
if old_dlvl < new_dlvl:
if region.region_type == REGION_DOWN:
matching_regions.append(region)
else:
if region.region_type == REGION_UP:
matching_regions.append(region)
if matching_regions:
if len(matching_regions) > 1:
print >> self.log, 'ERROR: %d potentially linking regions' % len(matching_regions)
self.linking_region = matching_regions[0]
# If the level change was controlled and known, then update the level.
taboo_levels = []
if self.linking_region:
print >> self.log, 'presumably controlled %s from dlvl %d to dlvl %d' % (change_string, old_dlvl, new_dlvl)
if self.linking_region.target_region:
print >> self.log, 'the target region was known:'
print >> self.log, self.linking_region.target_region
print >> self.log, 'loading the target level'
self.levelmap = self.linking_region.target_region.level
return
else:
print >> self.log, 'the target region was unknown'
# Exclude levels that are already accessible from the linking region.
taboo_regions = self.linking_region.get_connected_regions()
taboo_levels = [region.level for region in taboo_regions]
else:
print >> self.log, 'uncontrolled %s from dlvl %d to dlvl %d' % (change_string, old_dlvl, new_dlvl)
print >> self.log, 'looking for a matching level'
# If we are descending from the mines branch then stay in the mines branch.
# If we are descending in an uncontrolled manner from the doom branch then stay in the doom branch.
forced_branch = None
fork_level = self.levelmap.dungeon.get_doom_fork_level()
if old_dlvl < new_dlvl:
# Descent from a mines branch level always goes to a mines branch level.
if self.levelmap.level_branch == LEVEL_BRANCH_MINES:
forced_branch = LEVEL_BRANCH_MINES
# Uncontrolled descent from a doom branch level always goes to a doom branch level.
if not self.linking_region:
if self.levelmap.level_branch == LEVEL_BRANCH_DOOM:
forced_branch = LEVEL_BRANCH_DOOM
# Controlled descent from a doom branch level deeper than the fork level always goes to a doom branch level.
if fork_level:
if old_dlvl > fork_level.level_dlvl:
if self.levelmap.level_branch == LEVEL_BRANCH_DOOM:
forced_branch = LEVEL_BRANCH_DOOM
# If we are ascending to a level deeper than the doom fork then stay in the same branch.
if fork_level:
if new_dlvl < old_dlvl:
if new_dlvl > fork_level.level_dlvl:
if self.levelmap.level_branch == LEVEL_BRANCH_MINES:
forced_branch = LEVEL_BRANCH_MINES
if self.levelmap.level_branch == LEVEL_BRANCH_DOOM:
forced_branch = LEVEL_BRANCH_DOOM
# If we are at a named sokoban level then the forced branch should be sokoban
if sokoban_name:
print >> self.log, 'forcing a sokoban branch'
forced_branch = LEVEL_BRANCH_SOKOBAN
# Look for existing matching levels.
matching_levels = []
for level in self.dungeon.levels:
if level.level_dlvl != new_dlvl:
# if the target level is the wrong dlvl then we know it cannot be a match
continue
if forced_branch == LEVEL_BRANCH_SOKOBAN:
# if we know the target is a sokoban level then do not accept levels with an uncertain branch
if level.level_branch != LEVEL_BRANCH_SOKOBAN:
continue
elif forced_branch is not None:
# if the target branch is forced but is not a sokoban level then accept levels with an uncertain branch
if level.level_branch not in (forced_branch, LEVEL_BRANCH_UNKNOWN):
continue
matching_levels.append(level)
print >> self.log, 'found %d raw matching levels' % len(matching_levels)
# Exclude taboo levels.
if taboo_levels:
new_matching_levels = [level for level in matching_levels if level not in taboo_levels]
if len(new_matching_levels) < len(matching_levels):
print >> self.log, 'removed %d taboo levels from the list of matching levels' % (len(matching_levels) - len(new_matching_levels))
matching_levels = new_matching_levels
else:
print >> self.log, 'taboo levels exist but none was found in the list of matching levels'
else:
print >> self.log, 'no taboo levels were available'
# Load the matching level or create a new level
if len(matching_levels) == 1:
print >> self.log, 'a unique matching level was found and loaded'
self.levelmap = matching_levels[0]
elif len(matching_levels) > 1:
print >> self.log, 'WARNING: multiple matching levels were found and an arbitrary one was loaded'
self.levelmap = matching_levels[0]
else:
print >> self.log, 'no matching level was found so one was created and loaded'
newlevel = LevelMap(self.dungeon)
newlevel.level_dlvl = new_dlvl
if forced_branch:
newlevel.level_branch = forced_branch
if forced_branch == LEVEL_BRANCH_SOKOBAN:
# initialize the sokoban level
print >> self.log, 'initializing a sokoban level'
newlevel.init_sokoban(new_ansi, sokoban_name)
self.levelmap = newlevel
self.dungeon.levels.append(newlevel)
def process_incoming_status(self, ansi):
"""
This function processes controlled and uncontrolled dlvl changes.
This is where new LevelMap objects are created.
"""
# Initialize the top level.
if not self.levelmap:
self.levelmap = LevelMap(self.dungeon)
self.levelmap.level_dlvl = 1
self.levelmap.level_branch = LEVEL_BRANCH_DOOM
self.levelmap.level_special = LEVEL_SPECIAL_TOP
self.levelmap.exploration_status = EXP_UNEXPLORED
self.dungeon.levels.append(self.levelmap)
cursor_location = (ansi.row, ansi.col)
status_string = ''.join(x.to_ascii_char() for x in ansi.lines[23])
newstatus = BotStatus()
if newstatus.scrape(status_string):
# log blinding and unblinding events
if newstatus.blind and (not self.status.blind):
print >> self.log, 'blinded'
if (not newstatus.blind) and self.status.blind:
print >> self.log, 'unblinded'
# log hunger level changes
if newstatus.hunger_level > self.status.hunger_level:
print >> self.log, 'hunger level increased'
elif newstatus.hunger_level < self.status.hunger_level:
print >> self.log, 'hunger level decreased'
# log polymorph events and have them trigger an inventory check
if newstatus.polymorphed and (not self.status.polymorphed):
print >> self.log, 'polymorphed'
self.invalidate_inventory()
if (not newstatus.polymorphed) and self.status.polymorphed:
print >> self.log, 'returned to normal form'
self.invalidate_inventory()
# if we just got weak from hunger then pray
if newstatus.hunger_level >= HUNGER_LEVEL_WEAK and self.status.hunger_level < HUNGER_LEVEL_WEAK:
print >> self.log, 'we just got weak, so praying for food'
self.should_pray = True
# process a dlvl change
if newstatus.dlvl != self.status.dlvl:
self.process_dlvl_change(ansi, self.status.dlvl, newstatus.dlvl, self.last_cursor_location, cursor_location)
# update the level time
if self.levelmap.level_time is None:
self.levelmap.level_time = 0
if not self.status.turns:
self.levelmap.level_time += newstatus.turns
else:
self.levelmap.level_time += (newstatus.turns - self.status.turns)
# do not forget to update the status
self.status = newstatus
else:
print >> self.log, 'this status string could not be processed:', status_string
def create_region(self, region_type, cursor_location):
"""
The created region will be refined when the level is updated.
For example, its branch and type will be defined.
"""
# create a region
region = Region()
region.level = self.levelmap
region.location = cursor_location
region.region_type = region_type
self.levelmap.regions.append(region)
# possibly link the region
if self.linking_region:
region.target_region = self.linking_region
self.linking_region.target_region = region
print >> self.log, 'created region:', str(region)
print >> self.log, 'linking with region:', str(self.linking_region)
else:
print >> self.log, 'created unlinked region:', str(region)
self.linking_region = None
def read_post_status_messages(self, ansi):
"""
Read messages that should be processed after processing the status.
"""
# concatenate all of the messages
s = ''.join(self.messages)
# get the cursor location and the corresponding square
cursor_location = (ansi.row, ansi.col)
cursor_square = self.levelmap.level[cursor_location]
# if we just finished searching then mark the square as having
# been searched for some number of turns
if self.search_location:
if cursor_location != self.search_location:
print >> self.log, 'we stopped searching on a different square than we started'
else:
search_turns = self.status.turns - self.search_turn_begin
self.levelmap.level[self.search_location].search_count_from += search_turns
for neighbor_location in self.levelmap.cached_neighbor_locations[self.search_location]:
self.levelmap.level[neighbor_location].search_count_to += search_turns
self.search_location = None
self.search_turn_begin = None
# we succeeded in unlocking a large container
if self.unlock_moniker:
lore_item = self.lore.get_existing_item(self.unlock_moniker)
if lore_item:
container_unlocking_messages = (
'You succeed in unlocking the box',
'You succeed in unlocking the chest',
'You succeed in picking the lock',
)
for message in container_unlocking_messages:
if message in s:
lore_item.locked = False
self.unlock_moniker = None
# we tried to loot a large container but it was locked
if 'Hmmm, it seems to be locked' in s:
if self.loot_moniker:
lore_item = self.lore.get_existing_item(self.loot_moniker)
if lore_item:
print >> self.log, 'the large container assumed to be named', self.loot_moniker, 'was discovered to be locked'
lore_item.locked = True
else:
print >> self.log, 'WARNING: the assumed name of a container that seems to be locked was unrecognized'