-
Notifications
You must be signed in to change notification settings - Fork 0
/
nethack.py
executable file
·2478 lines (2309 loc) · 70.9 KB
/
nethack.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
"""
This is initial code for a Nethack bot, written by Tim Newsome
<[email protected]> in 2004. I've abandoned this code for now, but
maybe I'll pick it up again some day.
This code is not going to just run on your system, if only because the path to
nethack is hard-coded. If you can't make the code run, just play back the
included .tty files (using ttyplay) and pretend you did. If you do get the
code to run on your system, and are hacking on it somewhat productively,
please let me know. If at that stage you have any questions, I'll try to
answer them.
A few .tty files are included for your enjoyment. They're not all made with
exactly this code. I can't easily make new ones because ttyrec doesn't like
devfs, or something.
The bot uses a named pipe to tee Nethack's output into a ttyrec xterm as well
as this program. Then it explores the dungeon, charges every monster, and
prays when hungry. It'll likely throw an exception when it encounters
something it hasn't seen yet. ISTR that the last thing I was working on was
making the bot push boulders out of the way in case it can't get to the down
staircase. The bot will already search the level for hidden doors if that is
the case.
I abandoned the code in favor of rewriting in ocaml because I was getting
annoyed at python's lack of type checking. Specifically I really feel the need
for a type-checked enum thing. I've also wanted to learn ocaml for a while,
and this seemed like a project that would really let me get a feel for the
language. So far I like the type system, but not the lack of name spaces, and
definitely not the need for prototypes.
"""
from __future__ import generators
# Current development "plan":
# Get this code to the point where it can run through a full game without
# encountering any unexpected messages, and without getting stuck somewhere.
# Functions should look like this:
def template(self):
# function returns non-zero when there is a situation that the current
# function is not equipped to deal with (ie gnome with wand of death).
exc_level = self.push_except_function(function)
try:
# do whatever this function does
# do NOT use return
pass
except NetHackException, e:
if e.level < exc_level:
raise
self.pop_except_function()
# failure is 0 for success, non-zero for failure.
return failure
import os, sys, select
import pty
import string
import re
import random
import time
import traceback
import Queue, bisect
os.environ['TERM'] = 'vt100'
os.environ['NETHACKOPTIONS'] = "number_pad,!autopickup,!sparkle,!timed_delay," \
"!tombstone,scores:0t/0a/1o"
class PriorityQueue(Queue.Queue):
def _put(self, item):
bisect.insort(self.queue, item)
def hex_string(string):
ret = ""
for c in string:
if ord(c) > ord(' ') and ord(c) <= ord('~'):
ret = ret + " %s" % c
else:
ret = ret + " %02x" % ord(c)
return ret
class NetHackException(Exception):
def __init__(self, player, level):
self.player = player
self.level = level
while len(player.except_functions) > level + 1:
player.pop_except_function()
class ErrorException(Exception):
def __init__(self, string):
self.string = string
class RoutePlanException(ErrorException):
pass
class Terminal:
ATTRIB_REVERSE = 0x100
def __init__(self, lines=25, columns=80):
self.lines = lines
self.columns = columns
# bits 0-6 contain the ASCII character
# higher bits are for attributes
self.chars = [32] * lines * columns
self.x = 0
self.y = 0
self.state = ""
self.prompt = ""
self.mode = 0
self.actions = {}
for i in range(ord(' '), ord('~')+1):
self.actions["%c" % i] = "print"
self.actions["\x00"] = "ignore" # fill character
self.actions["\x08"] = 'backspace'
self.actions["\x0a"] = 'LF'
self.actions["\x0d"] = 'CR'
self.actions["\x1b(B"] = "ignore" # character set stuff
self.actions["\x1b)0"] = "ignore"
self.actions["\x1b>"] = "ignore" # keypad in numeric mode
self.actions["\x1b[?1l"] = "ignore" # cursor key mode
self.actions["\x1b[H"] = "home"
self.actions["\x1b[J"] = "clear to end of screen"
self.actions["\x1b[K"] = "clear to end of line"
self.actions["\x1b[A"] = "up"
self.actions["\x1b[B"] = "down"
self.actions["\x1b[C"] = "right"
self.actions["\x1b[D"] = "left"
self.actions["\x1b[7m"] = "reverse"
self.actions["\x1b[0m"] = "clear mode"
self.actions["\x1by"] = "ignore" # dunno what this does
def process(self, string):
for char in string:
self.state = self.state + char
if self.state in self.actions:
action = self.actions[self.state]
if action == "print":
self.prompt = self.prompt + char
else:
self.prompt = ""
if action == "print":
self.chars[self.x + self.y * self.columns] = \
self.mode | ord(char)
self.x = self.x + 1
elif action == 'CR':
self.x = 0
elif action == 'backspace':
self.x = self.x - 1
elif action in ('LF', "down"):
self.y = self.y + 1
elif action == "up":
self.y = self.y - 1
elif action == "left":
self.x = self.x - 1
elif action == "right":
self.x = self.x + 1
elif action == 'ignore':
pass
elif action == "home":
self.x = 0
self.y = 0
elif action == "reverse":
self.mode = self.mode | self.ATTRIB_REVERSE
elif action == "clear mode":
self.mode = 0
elif action == "clear to end of screen":
for i in range(self.x + self.y * self.columns,
self.columns * self.lines):
self.chars[i] = ord(' ')
elif action == "clear to end of line":
for i in range(self.x + self.y * self.columns,
self.columns * (self.y + 1)):
self.chars[i] = ord(' ')
else:
raise Exception, "Unknown action: %s" % action
self.state = ""
if self.x >= self.columns:
self.x = 0
self.y = self.y + 1
if self.y >= self.lines:
self.y = self.lines - 1
continue
# move cursor to absolute position
match = re.match("\x1b\[(\d+);(\d+)H", self.state)
if not match is None:
self.prompt = ""
self.y = int(match.group(1)) - 1
self.x = int(match.group(2)) - 1
self.state = ""
continue
if len(self.state) > 10:
raise Exception, "Unknown control codes: %s" % \
hex_string(self.state)
def draw(self):
#sys.stdout.write("\x1b[H")
c = map(lambda x: "%c" % (x & 0x7f), self.chars)
for l in range(self.lines):
print string.join(c[self.columns * l: self.columns * (l+1)], "")
def readline(self, line):
c = map(lambda x: "%c" % (x & 0x7f),
self.chars[self.columns * line: self.columns * (line+1)])
return string.join(c, "")
def readline_raw(self, line):
return self.chars[self.columns * line: self.columns * (line+1)]
class NetHack:
def __init__(self, out_fd):
self.terminal = Terminal()
#(nethack_in, nethack_out) = os.popen2(cmd)
(self.pid, self.fd) = pty.fork()
self.out_fd = out_fd
if self.pid == 0:
os.system("/home/drz/nethack/game/nethack -u bottie -p val")
sys.exit(0)
#print "Child with pid=%d, fd=%d" % (self.pid, self.fd)
self.poll = select.poll()
self.poll.register(self.fd, select.POLLIN | select.POLLPRI)
self.prompt = ""
self.messages = []
self.running = 1
self._unknown = '%'
def unknown(self):
if self._unknown == '|':
self._unknown = '%'
else:
self._unknown = '|'
self.cmd(self._unknown, 5, 0)
while 1:
if self.messages[-1] == "Unknown command '%s'." % self._unknown:
break
self.cmd("", 5, 0)
self.messages = self.messages[:-1]
# wait until it's the user's turn to input something
def wait(self, timeout=1000):
self.terminal.prompt = ""
self.prompt = ""
while self.running:
list = self.poll.poll(timeout)
if len(list) == 0:
break
try:
data = os.read(self.fd, 64)
except OSError:
#print "all done!"
self.running = 0
self.out_fd.write(data)
self.out_fd.flush()
for c in data:
self.terminal.process(c)
if re.match("(Hit space to continue:|.*--More--|"
"\(end\)|.*\[[ynq]+]|Call .*:)", self.terminal.prompt):
break
if re.match(".*throws", self.terminal.prompt):
#raise Exception, "throwing detected!"
# no longer necessary, since we turned off timed_delay
#timeout = 1000
pass
self.prompt = self.terminal.prompt.strip()
if len(self.prompt) < 5:
self.prompt = ""
# send a raw string, and wait until it's our turn to provide more input
def send(self, str, timeout=200):
print "sending '%s'" % str
os.write(self.fd, str)
self.wait(timeout)
def parse_list(self, listx, listy):
#print "list:", listx, listy
list = []
for y in range(listy):
list_entry = self.terminal.readline(y)[listx:].strip()
list.append(list_entry)
#print "list_entry:", list_entry
return list
# send the command "str", and wait until more input is required, hitting
# space for --More-- and so on, while keeping track of all the messages
# nethack displays
def cmd(self, str, timeout=200, reset=1):
messages = []
self.send(str, timeout)
while self.running:
#print "prompt: '%s'" % self.prompt
# the first line on the screen ends in a colon
match = re.match("(\s{9}\s+)\w", self.terminal.readline(0))
if match:
#print "calling list on line:", self.terminal.readline(0)
#print "whitespace: '%s'" % match.group(1)
#print "groups:", match.groups()
messages = messages + \
self.parse_list(len(match.group(1)), self.terminal.y)
self.send(" ", timeout)
elif re.match(".*--More--", self.prompt):
# read message until the --More--
m = ""
for l in range(0, 25):
line = self.terminal.readline(l).strip()
match = re.match("(.*)--More--", line)
if len(m) > 0:
m = m + " "
if match:
m = m + match.group(1)
break
else:
m = m + line
messages.append(m)
self.send(" ", timeout)
elif self.prompt == "(end)":
#print "found (end)"
self.parse_list(self.terminal.x - 5, self.terminal.y)
self.send(" ", timeout)
elif re.match(".* \[ynq?]", self.prompt):
break
elif re.match(".*:$", self.prompt):
break
elif len(self.prompt) < 1:
# ignore blank prompts
messages.append(self.terminal.readline(0).strip())
break
else:
# unknown prompt means it's not quite done drawing yet
#raise Exception, "Unknown prompt: \"%s\"" % self.prompt
self.send("", timeout)
messages2 = []
for m in messages:
# split up the individual sentences in the message
sentence = ""
open = None
punctuation = 0
#print "message:", m
for c in m:
if c in ('"'):
if open == c:
open = None
elif open is None:
open = c
sentence = sentence + c
elif c in ('.', '!') and open is None:
sentence = sentence + c
punctuation = 1
elif c in string.whitespace:
if punctuation:
if len(sentence) > 1:
messages2.append(sentence)
sentence = ""
punctuation = 0
if len(sentence) > 0:
sentence = sentence + c
else:
sentence = sentence + c
punctuation = 0
if len(sentence):
#print "sentence:", sentence
messages2.append(sentence)
messages2 = map(string.strip, messages2)
messages2 = filter(lambda x: len(x) > 0, messages2)
if len(messages2):
print "messages2:", messages2
if len(self.prompt):
print "prompt:", self.prompt
if reset:
self.messages = messages2
else:
self.messages = self.messages + messages2
self.parse_status()
def parse_status(self):
# line 1
line = self.terminal.readline(22).strip()
match = re.match("^(.*) the (.*?)\s+St:(\S+) Dx:(\d+) Co:(\d+) "
"In:(\d+) Wi:(\d+) Ch:(\d+)\s+(Lawful|Neutral|Chaotic)", line)
if match is None:
print "Couldn't parse status line: %s" % line
else:
if len(match.group(0)) < len(line):
raise "Unparsed status: %s" % line
(self.name, self.title, self.strength, self.dexterity,
self.constitution, self.intelligence, self.wisdom,
self.charisma, self.alignment) = match.groups()
match1 = re.match("(\d+)/(\d+)", self.strength)
match2 = re.match("(\d+)/\*\*", self.strength)
if match1:
self.strength = float(match1.group(1)) + float(match1.group(2)) / 100
elif match2:
self.strength = float(match2.group(1)) + 1
else:
self.strength = int(self.strength)
self.dexterity = int(self.dexterity)
self.constitution = int(self.constitution)
self.intelligence = int(self.intelligence)
self.wisdom = int(self.wisdom)
self.charisma = int(self.charisma)
# line 2
line = self.terminal.readline(23).strip()
match = re.match("""
Dlvl:(?P<depth>\d+)
\s+\$:(?P<gold>\d)
\s+HP:(?P<hp>\d+)\((?P<max_hp>\d+)\)
\s+Pw:(?P<pw>\d+)\((?P<max_pw>\d+)\)
\s+AC:(?P<ac>\d+)
\s+
(Exp:(?P<exp>\d+) | HD:(?P<hd>\d+))
(?P<flags>(\s+\w+))*$""", line, re.VERBOSE)
if match is None:
print "Couldn't parse status line: %s" % line
else:
if len(match.group(0)) < len(line):
raise "Unparsed status: %s" % line
self.depth = int(match.group('depth'))
self.gold = int(match.group('gold'))
self.hp = int(match.group('hp'))
self.max_hp = int(match.group('max_hp'))
self.pw = int(match.group('pw'))
self.max_pw = int(match.group('max_pw'))
self.ac = int(match.group('ac'))
if match.group('exp'):
self.level = int(match.group('exp'))
self.hd = None
else:
self.level = None
self.hd = int(match.group('hd'))
self.hunger = 0
self.blind = 0
self.stunned = 0
self.burdened = 0
self.hallucinating = 0
flags = match.group('flags') or ''
for status in string.split(flags):
status = status.strip()
if status == "Hungry":
self.hunger = 1
elif status == "Weak":
self.hunger = 2
elif status in ("Fainting", 'Fainted'):
self.hunger = 3
elif status == "Starved":
self.hunger = 4
elif status == "Blind":
self.blind = 1
elif status == "Stun":
self.stunned = 1
elif status == "Hallu":
self.hallucinating = 1
elif status == "Burdened":
self.burdened = 1
else:
raise "Unknown status: '%s'" % status
def get_map(self):
map = []
for l in range(2, 21):
map = map + self.terminal.readline_raw(l)
return map
def mypos(self):
return (self.terminal.x, self.terminal.y - 2)
def mydepth(self):
return self.depth
def semicolon(self, x, y):
self.cmd(";", 5)
timeout = 10
while (len(self.messages) < 1 or
self.messages[0] != "Pick an object.") and timeout > 0:
self.cmd("", 5)
timeout = timeout - 1
if timeout <= 0:
return None
# top 2 lines are messages
y = y + 2
vx = x - self.terminal.x
vy = y - self.terminal.y
str = ""
if (vx > 0):
str = str + ("l" * (vx / 8))
str = str + ("6" * (vx % 8))
elif (vx < 0):
str = str + ("h" * (-vx / 8))
str = str + ("4" * (-vx % 8))
if (vy > 0):
str = str + ("j" * (vy / 8))
str = str + ("2" * (vy % 8))
elif (y < self.terminal.y):
str = str + ("k" * (-vy / 8))
str = str + ("8" * (-vy % 8))
str = str + "."
self.cmd(str, 5)
while 1:
if len(self.messages) > 0:
if self.messages[0] == "Pick an object.":
self.messages = self.messages[1:]
else:
break
else:
self.cmd("", 5)
description = self.messages[0]
if re.match("a ghost or a dark part of a room", description):
char = " "
else:
char = description[0]
if re.match(".*Pick", description):
raise Exception, description
match = re.match(".*\((.+)\)( \[.*])?$", description)
if match:
description = match.group(1)
return (char, description)
DIRECTION_TABLE = {
(-1,-1): "7",
( 0,-1): "8",
( 1,-1): "9",
(-1, 0): "4",
( 1, 0): "6",
(-1, 1): "1",
( 0, 1): "2",
( 1, 1): "3"
}
# direction is given as a vector, ie (1,0) or (-1,1)
def move(self, direction):
if direction not in self.DIRECTION_TABLE:
raise Exception, "bad direction: %d,%d" % (direction[0], direction[1])
cmd = self.DIRECTION_TABLE[direction]
self.cmd(cmd, 70)
#self.unknown()
def open(self, direction):
self.cmd("o", 70)
for m in nethack.messages:
if m == "You can't open anything -- you have no hands!":
return 1
elif m == 'In what direction?':
pass
else:
raise "Unexpected message: %s" % m
self.cmd(self.DIRECTION_TABLE[direction], 70)
return 0
def fight(self, direction):
cmd = "F" + self.DIRECTION_TABLE[direction]
self.cmd(cmd, 70)
def kick(self, direction):
cmd = "\x04" + self.DIRECTION_TABLE[direction]
self.cmd(cmd, 70)
def pray(self):
self.cmd("#p\n", 5)
while len(self.messages) < 1 or \
not re.match("Are you sure you want to pray?", self.messages[0]):
self.cmd("", 5)
self.cmd("y", 70)
class NetHackCreature:
def __init__(self, description):
self.description = description
if re.match("tame", description):
self.hostile = 0
self.tame = 1
self.peaceful = 0
self.me = 0
elif re.match("peaceful", description):
self.hostile = 0
self.tame = 0
self.peaceful = 1
self.me = 0
elif re.match(".* called bottie", description):
self.hostile = 0
self.tame = 0
self.peaceful = 0
self.me = 1
else:
self.hostile = 1
self.tame = 0
self.peaceful = 0
self.me = 0
def __str__(self):
return self.description
class NetHackMapSquare:
# haven't seen this square yet
UNEXPLORED = 0
FLOOR = 1
WALL = 2
OPEN_DOOR = 3
BROKEN_DOOR = 4
CLOSED_DOOR = 5
CORRIDOR = 6
DOORWAY = 7
STAIRCASE_UP = 8
STAIRCASE_DOWN = 9
# don't know what's on this square because there's something on top of it
UNKNOWN = 10
# this is a floor/corridor whatever that you can walk on, but can't tell
# what's there because there's an object on top of it
UNKNOWN_PASSABLE = 11
FOUNTAIN = 12
SINK = 13
GRAVE = 14
PIT = 15
ARROW_TRAP = 16
NEUTRAL_ALTAR = 17
CHAOTIC_ALTAR = 18
LAWFUL_ALTAR = 19
BEAR_TRAP = 20
DART_TRAP = 21
MAGIC_TRAP = 22
RUST_TRAP = 23
SQUEAKY_BOARD = 24
LOCKED_DOOR = 25
FALLING_ROCK_TRAP = 26
ANTI_MAGIC_FIELD = 27
FIRE_TRAP = 28
HOLE = 29
TELEPORT_TRAP = 30
SLEEPING_GAS_TRAP = 31
ROLLING_BOULDER_TRAP = 32
TRAP_DOOR = 33
TREE = 34
LEVEL_TELEPORTER = 35
WEB = 36
# include unknowns because they might be doors
# don't include unkowns because they might not be doors
GRID_TERRAIN = (OPEN_DOOR,)
# Include unknown here. We might later decide that this particular unknown
# isn't passable after all, if we try moving onto it but it doesn't work.
PASSABLE_TERRAIN = (OPEN_DOOR, FLOOR, CORRIDOR, DOORWAY, STAIRCASE_UP,
STAIRCASE_DOWN, UNKNOWN, UNKNOWN_PASSABLE, FOUNTAIN, SINK, GRAVE,
PIT, ARROW_TRAP, NEUTRAL_ALTAR, CHAOTIC_ALTAR, LAWFUL_ALTAR,
BEAR_TRAP, BROKEN_DOOR, DART_TRAP, MAGIC_TRAP, RUST_TRAP,
SQUEAKY_BOARD, FALLING_ROCK_TRAP, ANTI_MAGIC_FIELD, FIRE_TRAP,
HOLE, TELEPORT_TRAP, SLEEPING_GAS_TRAP, ROLLING_BOULDER_TRAP,
TRAP_DOOR, LEVEL_TELEPORTER, WEB)
BOULDER = 0
def draw_terrain(self):
lookup = {
self.UNEXPLORED: ",",
self.FLOOR: ".",
self.WALL: "W",
self.OPEN_DOOR: "d",
self.BROKEN_DOOR: "b",
self.CLOSED_DOOR: "D",
self.LOCKED_DOOR: "D",
self.CORRIDOR: "#",
self.DOORWAY: ".",
self.STAIRCASE_UP: "<",
self.STAIRCASE_DOWN: ">",
self.UNKNOWN: ";",
self.UNKNOWN_PASSABLE: ":",
self.FOUNTAIN: "{",
self.SINK: "#",
self.GRAVE: "(",
self.PIT: "^",
self.ARROW_TRAP: "^",
self.NEUTRAL_ALTAR: "_",
self.CHAOTIC_ALTAR: "_",
self.LAWFUL_ALTAR: "_",
self.BEAR_TRAP: "^",
self.DART_TRAP: "^",
self.MAGIC_TRAP: "^",
self.RUST_TRAP: "^",
self.SQUEAKY_BOARD: "^",
self.FALLING_ROCK_TRAP: "^",
self.ANTI_MAGIC_FIELD: "^",
self.FIRE_TRAP: "^",
self.HOLE: "^",
self.TRAP_DOOR: "^",
self.TELEPORT_TRAP: "^",
self.SLEEPING_GAS_TRAP: "^",
self.ROLLING_BOULDER_TRAP: "^",
self.TREE: "#",
self.LEVEL_TELEPORTER: "^",
self.WEB: "^",
}
if self.terrain in lookup:
char = lookup[self.terrain]
else:
char = '?'
if not self.passable():
return "\x1b[31m%s\x1b[0m" % char
else:
return char
def travel_cost(self):
table = {
self.UNEXPLORED: 1000,
self.FLOOR: 1,
self.WALL: 1000,
self.OPEN_DOOR: 1,
self.BROKEN_DOOR: 1,
self.CLOSED_DOOR: 5,
self.CORRIDOR: 1,
self.DOORWAY: 1,
self.STAIRCASE_UP: 1,
self.STAIRCASE_DOWN: 1,
self.UNKNOWN: 2,
self.UNKNOWN_PASSABLE: 2,
self.FOUNTAIN: 1,
self.SINK: 1,
self.GRAVE: 1,
self.PIT: 15,
self.ARROW_TRAP: 5,
self.NEUTRAL_ALTAR: 1,
self.CHAOTIC_ALTAR: 1,
self.LAWFUL_ALTAR: 1,
self.BEAR_TRAP: 15,
self.DART_TRAP: 10,
self.MAGIC_TRAP: 10,
self.RUST_TRAP: 20,
self.SQUEAKY_BOARD: 3,
self.LOCKED_DOOR: 8,
self.FALLING_ROCK_TRAP: 5,
self.ANTI_MAGIC_FIELD: 2,
self.FIRE_TRAP: 10,
self.HOLE: 100,
self.TRAP_DOOR: 100,
self.TELEPORT_TRAP: 100,
self.LEVEL_TELEPORTER: 200,
self.WEB: 6,
self.SLEEPING_GAS_TRAP: 40,
self.ROLLING_BOULDER_TRAP: 8,
}
cost = table[self.terrain]
if self.creature:
if self.creature.peaceful:
cost = cost + 10
elif self.creature.tame:
cost = cost + 1
else:
cost = cost + 5
elif self.BOULDER in self.items:
cost = cost + 100
# prefer squares that we've already visited/searched
if self.visited > 0:
cost = cost - 0.1
if self.searched > 0:
cost = cost - .01 * min(self.searched, 5)
return cost
def set_terrain(self, t):
old = self.terrain
if old != t:
self.map.changes = self.map.changes + 1
print "change terrain of", self, "to", t
self.terrain = t
if (old in self.GRID_TERRAIN) != (self.terrain in self.GRID_TERRAIN):
# update the square's neighbors
for x in range(self.x-1, self.x+2):
for y in range(self.y-1, self.y+2):
square = self.map.get_square(x, y)
if square:
square.update_neighbors()
def __init__(self, map, x, y):
self.items = None
self.creature = None
self.character = None
self.mark = 0
self.map = map
self.x = x
self.y = y
self.visited = 0
# how many times we've searched this location
self.searched = 0
self.terrain = self.UNEXPLORED
self.items = []
def update_neighbors(self):
list = []
if self.terrain in self.GRID_TERRAIN:
possible = ((-1,0), (0,-1), (1,0), (0,1))
else:
possible = ((-1,0), (0,-1), (1,0), (0,1), (-1,-1), (-1,1), (1,-1),
(1,1))
#print "update neighbors for", self, ":",
for offset in possible:
x = self.x + offset[0]
y = self.y + offset[1]
neighbor = self.map.get_square(x, y)
if neighbor is None:
continue
if neighbor.terrain in self.GRID_TERRAIN and \
offset[0] != 0 and offset[1] != 0:
continue
list.append(neighbor)
self.neighbors = list
self.adjacents = []
for offset in ((-1,0), (0,-1), (1,0), (0,1), (-1,-1), (-1,1), (1,-1),
(1,1)):
x = self.x + offset[0]
y = self.y + offset[1]
adjacent = self.map.get_square(x, y)
if adjacent:
self.adjacents.append(adjacent)
# return true iff two squares are next to each other
def is_adjacent(self, other):
if other is None:
raise "other is None";
if self is None:
raise "self is None";
dx = abs(self.x - other.x)
dy = abs(self.y - other.y)
return (dx <= 1 and dy <= 1)
def is_grid_aligned(self, other):
return self.x == other.x or self.y == other.y
def __str__(self):
str = "%d,%d(c=" % (self.x, self.y)
if self.character is None:
str = str + "None"
else:
str = str + "%c" % (self.character & 0x7f)
str = str + ",t=%d)" % self.terrain
return str
# lit:
# 0 -- This square wasn't lit when we looked.
# 1 -- This square was lit when we looked.
def add_description(self, (char, description), lit):
# for now, not including ' ' because it'll confuse things
monster_chars = "@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'&;:~]"
item_chars = "$+=?!)*%([\\"
if self.terrain == self.UNEXPLORED:
self.set_terrain(self.UNKNOWN)
self.creature = None
if self.BOULDER in self.items:
self.items.remove(self.BOULDER)
if description == "boulder":
if not self.BOULDER in self.items:
self.items.append(self.BOULDER)
elif re.match("statue of (.*)", description):
pass
elif description == "floor of a room":
self.set_terrain(self.FLOOR)
elif re.match("((.* )?amulet|Amulet of Yendor)", description):
pass
elif re.match("(.* )?wand", description):
pass
elif re.match("neutral altar", description):
self.set_terrain(self.NEUTRAL_ALTAR)
elif re.match("chaotic altar", description):
self.set_terrain(self.CHAOTIC_ALTAR)
elif re.match("lawful altar", description):
self.set_terrain(self.LAWFUL_ALTAR)
elif re.match("iron chain", description):
pass
elif description == "open door":
self.set_terrain(self.OPEN_DOOR)
elif description == "closed door":
self.set_terrain(self.CLOSED_DOOR)
elif description == "broken door":
self.set_terrain(self.BROKEN_DOOR)
elif re.match("(lit )?corridor", description):
self.set_terrain(self.CORRIDOR)
elif description == "doorway":
self.set_terrain(self.DOORWAY)
elif description == "staircase up":
self.set_terrain(self.STAIRCASE_UP)
elif description == "staircase down":
self.set_terrain(self.STAIRCASE_DOWN)
elif description == "wall":
self.set_terrain(self.WALL)
elif description == "grave":
self.set_terrain(self.GRAVE)
elif description == "tree":
self.set_terrain(self.TREE)
elif description == "dark part of a room":
# we can do this, because we never semi-colon a ' ' part of
# the room we cannot see
if lit:
self.set_terrain(self.WALL)
elif description == "hole":
self.set_terrain(self.HOLE)
elif description == "trap door":
self.set_terrain(self.TRAP_DOOR)
elif re.match("(spiked )?pit", description):
self.set_terrain(self.PIT)
elif description == "bear trap":
self.set_terrain(self.BEAR_TRAP)
elif description == "magic trap":
self.set_terrain(self.MAGIC_TRAP)
elif description == "arrow trap":
self.set_terrain(self.ARROW_TRAP)
elif description == "rust trap":
self.set_terrain(self.RUST_TRAP)
elif description == "dart trap":
self.set_terrain(self.DART_TRAP)
elif description == "teleportation trap":
self.set_terrain(self.TELEPORT_TRAP)
elif description == "level teleporter":
self.set_terrain(self.LEVEL_TELEPORTER)
elif description == "web":
self.set_terrain(self.WEB)
elif description == "sleeping gas trap":
self.set_terrain(self.SLEEPING_GAS_TRAP)
elif description == "rolling boulder trap":
self.set_terrain(self.ROLLING_BOULDER_TRAP)
elif description == "falling rock trap":
self.set_terrain(self.FALLING_ROCK_TRAP)
elif description == "anti-magic field":
self.set_terrain(self.ANTI_MAGIC_FIELD)
elif description == "squeaky board":
self.set_terrain(self.SQUEAKY_BOARD)
elif char is "{":
self.set_terrain(self.FOUNTAIN)
elif description == "sink":
self.set_terrain(self.SINK)
elif char in monster_chars or \
re.match("interior of (.*)", description) or \
re.match("(.*)'s ghost", description):
self.creature = NetHackCreature(description)
elif char in item_chars:
pass
else:
raise "Unknown description: %s -- %s" % (char, description)
def passable(self):
return (self.terrain in self.PASSABLE_TERRAIN) and \
(not self.BOULDER in self.items)
class NetHackMap:
width = 80
height = 19
# positive y is down, positive x is to the right, to origin is at the top
# left of the map
def __init__(self):
self.squares = []
# how many times every wall that might have a secret door/passage in
# it should be searched
self.search_limit = 0
self.expected = [NetHackMapSquare.STAIRCASE_DOWN,
NetHackMapSquare.STAIRCASE_UP]
self.changes = 0
for y in range(self.height):
for x in range(self.width):
self.squares.append(NetHackMapSquare(self, x, y))
for square in self.squares:
square.update_neighbors()
def get_square(self, x, y):
if x < 0 or x >= self.width or y < 0 or y >= self.height:
return None
index = x + self.width * y
return self.squares[index]
def unmark(self):
for square in self.squares:
square.mark = 0
square.src = None
def find_terrain(self, terrain):
for square in self.squares:
if square.terrain == terrain:
return square
return None
def draw(self):
x = 0