-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathzmachine_opcodes.py
More file actions
1721 lines (1513 loc) · 65.5 KB
/
zmachine_opcodes.py
File metadata and controls
1721 lines (1513 loc) · 65.5 KB
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
"""
Z-Machine Opcode Processor for CircuitPython
Handles Z-machine instruction execution and text processing
This module implements the core Z-machine opcodes needed for
interactive fiction games like Zork.
"""
import sys
import random
import re
import os
SAVE_DIR = "/saves/cpz_machine"
# Z-machine instruction types
LONG_FORM = 0
SHORT_FORM = 1
VARIABLE_FORM = 2
EXTENDED_FORM = 3
# Operand types
LARGE_CONSTANT = 0
SMALL_CONSTANT = 1
VARIABLE = 2
OMITTED = 3
# call types
FUNCTION = 0x0000
PROCEDURE = 0x1000
ASYNC = 0x2000
PAGE_SIZE = 0x200
PAGE_MASK = 0x1FF
SYNONYMS_OFFSET = 0x24
v3_lookup_table = [
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
" \n0123456789.,!?_#'\"/\\-:()"
]
h_words_offset = 8
h_type = 3
config_time = 0x02
h_config = 1
if h_type < 4:
address_scaler = 2;
story_shift = 1;
#property_mask = P3_MAX_PROPERTIES - 1;
property_offset = 7
max_properties = 0x20
property_mask = max_properties - 1
object_size = 9
object_attributes = 0
object_parent = 4
object_next = 5
object_child = 6
object_prop_offset = 7
property_size_mask = 0xe0;
elif h_type < V8:
address_scaler = 4;
story_shift = 2;
#property_mask = P4_MAX_PROPERTIES - 1;
property_offset = 12
max_properties = 0x40
property_mask = max_properties - 1
object_size = 14
object_attributes = 0
object_parent = 6
object_next = 8
object_child = 10
object_prop_offset = 12
property_size_mask = 0x3f;
else:
address_scaler = 8;
story_shift = 3;
#property_mask = P4_MAX_PROPERTIES - 1;
property_offset = 12
max_properties = 0x40
object_size = 14
property_size_mask = 0x3f;
class Frame:
def __init__(self):
self.return_pointer = 0 # Program counter
self.ctype = FUNCTION
self.local_vars = [0]*15
self.data_stack = []
def unserialize(self, data, debug = 0):
if debug >= 3:
for i in range(len(data)):
if i%16 == 0:
print()
print(f"0x{data[i]:02x}",end=" ")
print()
self.return_pointer = int.from_bytes(data[0:4],"big")
#print(f"return pointer: 0x{self.return_pointer:04x}")
self.ctype = int.from_bytes(data[4:6],"big")
for i in range(15):
self.local_vars[i] = int.from_bytes(data[6+i*2:6+i*2+2],"big")
stacklen = int.from_bytes(data[36:38],"big")
if stacklen > 200:
print(f"bad stack length ({stacklen})")
sys.exit()
#print("data size:",len(data))
for i in range(stacklen):
self.data_stack.append(int.from_bytes(data[38+i*2:38+i*2+2],"big"))
def serialize(self, debug = 3):
size = (4 # return_pointer
+ 1 # ctype
+ 15*2 # local_vars
+ 2 # data_stack len
+ len(self.data_stack)*2 # data_stack
)
data = bytearray()
data[0:4] = self.return_pointer.to_bytes(4, 'big')
data[4:6] = self.ctype.to_bytes(2, 'big')
for i in range(15):
data[6+i*2:6+i*2+2] = int(self.local_vars[i]).to_bytes(2, 'big')
data[37:39] = len(self.data_stack).to_bytes(2, 'big')
#print(f"len: {len(self.data_stack)}, {self.data_stack}")
for i in range(len(self.data_stack)):
data[39+i*2:39+i*2+2] = self.data_stack[i].to_bytes(2, 'big')
if debug >= 3:
i = 0
for byte_value in data:
print(f"0x{byte_value:02x}", end=" ")
i += 1
if i % 16 == 0:
print()
print()
return data
def print(self, debug = 0):
if debug >= 3:
print(f"## frame ##")
print(f"# return_pointer: 0x{self.return_pointer:02x}")
print(f"# local_vars: {self.local_vars}")
if len(self.data_stack) > 0:
print(f"# data stack: {self.data_stack}")
print("## end ##")
class ZProcessor:
def __init__(self, zmachine):
self.zm = zmachine
self.instruction_count = 0
self.line_buff = ""
# Opcode dispatch table (simplified set for basic functionality)
self.opcodes = {
# 0OP opcodes
0x30: [self.op_rtrue,"op_rtrue"], # rtrue
0x31: [self.op_rfalse,"op_rfalse"], # rfalse
0x32: [self.op_print,"op_print"], # print
0x33: [self.op_print_ret,"op_print_ret"], # print_ret
0x35: [self.op_save,"op_save"], # save
0x36: [self.op_restore,"op_restore"], # restore
0x37: [self.op_restart,"op_restart"], # restart
0x38: [self.op_ret_popped,"op_ret_popped"], # ret_popped
0x39: [self.op_catch,"op_catch"], # catch
0x3A: [self.op_quit,"op_quit"], # quit
0x3B: [self.op_new_line,"op_new_line"], # new_line
# 1OP opcodes
0x80: [self.op_jz,"op_jz"], # jz
0x81: [self.op_get_sibling,"op_get_sibling"], # get_sibling
0x82: [self.op_get_child,"op_get_child"], # get_child
0x83: [self.op_get_parent,"op_get_parent"], # get_parent
0x84: [self.op_get_prop_len,"op_get_prop_len"], # get_prop_len
0x85: [self.op_inc,"op_inc"], # inc
0x86: [self.op_dec,"op_dec"], # dec
0x87: [self.op_print_addr,"op_print_addr"], # print_addr
0x89: [self.op_remove_obj,"op_remove_obj"], # remove object
0x8A: [self.op_print_obj,"op_print_obj"], # print_obj
0x8B: [self.op_ret,"op_ret"], # ret
0x8C: [self.op_jump,"op_jump"], # jump
0x8D: [self.op_print_paddr,"op_print_paddr"], # print_paddr
0x8E: [self.op_load,"op_load"], # load
0x8F: [self.op_not,"op_not"], # not (or call_1n in v4+)
# 2OP opcodes
0x01: [self.op_je,"op_je"], # je
0x02: [self.op_jl,"op_jl"], # jl
0x03: [self.op_jg,"op_jg"], # jg
0x04: [self.op_dec_chk,"op_dec_chk"], # dec_chk
0x05: [self.op_inc_chk,"op_inc_chk"], # inc_chk
0x06: [self.op_jin,"op_jin"], # jin
0x07: [self.op_test,"op_test"], # test
0x08: [self.op_or,"op_or"], # or
0x09: [self.op_and,"op_and"], # and
0x0A: [self.op_test_attr,"op_test_attr"], # test_attr
0x0B: [self.op_set_attr,"op_set_attr"], # set_attr
0x0C: [self.op_clear_attr,"op_clear_attr"], # clear_attr
0x0D: [self.op_store,"op_store"], # store
0x0E: [self.op_insert_obj,"op_insert_obj"], # insert_obj
0x0F: [self.op_loadw,"op_loadw"], # loadw
0x10: [self.op_loadb,"op_loadb"], # loadb
0x11: [self.op_get_prop,"op_get_prop"], # get_prop
0x12: [self.op_get_prop_addr,"op_get_prop_addr"], # get_prop_addr
0x13: [self.op_get_next_prop,"op_get_next_prop"], # get_next_prop
0x14: [self.op_add,"op_add"], # add
0x15: [self.op_sub,"op_sub"], # sub
0x16: [self.op_mul,"op_mul"], # mul
0x17: [self.op_div,"op_div"], # div
0x18: [self.op_mod,"op_mod"], # mod
0x19: [self.op_call_2s,"op_call_2s"],# call 2s
# VAR opcodes
0x20: [self.op_call,"op_call"], # call (call_vs in v4+)
0x21: [self.op_storew,"op_storew"], # storew
0x22: [self.op_storeb,"op_storeb"], # storeb
0x23: [self.op_put_prop,"op_put_prop"], # put_prop
0x24: [self.op_sread,"op_sread"], # sread (aread in v4+)
0x25: [self.op_print_char,"op_print_char"], # print_char
0x26: [self.op_print_num,"op_print_num"], # print_num
0x27: [self.op_random,"op_random"], # random
0x28: [self.op_push,"op_push"], # push
0x29: [self.op_pull,"op_pull"], # pull
}
def fetch_instruction(self):
"""Fetch and decode the next instruction"""
debug_count = 999999
#debug_count = 0 # use this to enable debugging at start
if self.instruction_count >= debug_count:
self.zm.debug = 2 # turn on debugging output
pccount = self.zm.pc
if self.zm.pc >= len(self.zm.memory):
raise RuntimeError("PC out of bounds")
opcode_byte = self.zm.read_byte(self.zm.pc)
self.zm.pc += 1
#self.zm.print_debug(3,f"opcode_byte: 0x{opcode_byte:02x}")
# Determine instruction form
if opcode_byte >= 0xC0:
# Variable form: VAR
form = VARIABLE_FORM
opcode = opcode_byte & 0x1F
#self.zm.print_debug(3,f"opcode_byte/opcode = 0x{opcode_byte:02x}/0x{opcode:02x}")
operand_types = self.decode_operand_types()
operand_count = len([t for t in operand_types if t != OMITTED])
#self.zm.print_debug(3,f"operand count:{operand_count}, types:{operand_types}")
elif opcode_byte >= 0xB0:
# short form: 0OP
form = SHORT_FORM
opcode = opcode_byte & 0x3F
operand_count = 0
operand_types = []
elif opcode_byte >= 0x80:
# Short form: 1OP
form = SHORT_FORM
opcode = opcode_byte & 0x0F
operand_type = (opcode_byte & 0x30) >> 4
#self.zm.print_debug(3,f"1opcode = {opcode}")
operand_count = 1
operand_types = [operand_type]
else:
# Long form: 2OP
form = LONG_FORM
opcode = opcode_byte & 0x1F
#self.zm.print_debug(3,f"2opcode byte = {opcode}")
operand_count = 2
operand_types = [
SMALL_CONSTANT if (opcode_byte & 0x40) == 0 else VARIABLE,
SMALL_CONSTANT if (opcode_byte & 0x20) == 0 else VARIABLE
]
# Fetch operands
operands = []
for op_type in operand_types:
if op_type == OMITTED:
break
elif op_type == LARGE_CONSTANT:
value = self.zm.read_word(self.zm.pc)
#self.zm.print_debug(3,f"fetch instruction: read large constant: pc=0x{self.zm.pc:02X}, value={value}")
self.zm.pc += 2
operands.append(value)
elif op_type == SMALL_CONSTANT:
value = self.zm.read_byte(self.zm.pc)
#self.zm.print_debug(3,f"fetch instruction: read small constant: pc=0x{self.zm.pc:02X}, value={value}")
self.zm.pc += 1
operands.append(value)
elif op_type == VARIABLE:
var_num = self.zm.read_byte(self.zm.pc)
#self.zm.print_debug(3,f"fetch instruction: read variable: pc=0x{self.zm.pc:02X}, var_num={var_num}")
self.zm.pc += 1
#if var_num <= 15:
# self.print_frame(self.zm.call_stack[-1],"fetch_instruction")
operands.append(self.read_variable(var_num))
pccount = self.zm.pc - pccount
return opcode, operands, form, pccount, opcode_byte
def decode_operand_types(self):
"""Decode operand types for variable form instructions"""
types_byte = self.zm.read_byte(self.zm.pc)
self.zm.pc += 1
types = []
for i in range(4):
op_type = (types_byte >> (6 - 2*i)) & 3
types.append(op_type)
if op_type == OMITTED:
break
return types
def write_to_line(self, text, flush = False):
self.line_buff += text
#print(f"{ord(self.line_buff[-1])}")
if ord(self.line_buff[-1]) == 10 or flush:
self.zm.print_text(self.line_buff)
self.line_buff = ""
def print_frame(self, frame, i = "0"):
#self.zm.print_debug(3,f"## frame {i} ##")
#self.zm.print_debug(3,f"# return_pointer: 0x{frame.return_pointer:02X}")
#self.zm.print_debug(3,f"# local_vars: {frame.local_vars}")
if len(frame.data_stack) > 0:
pass
#self.zm.print_debug(3,f"# data stack: {frame.data_stack}")
#self.zm.print_debug(3,"## end ##")
def print_frame_stack(self):
#self.zm.print_debug(3,"### frame stack top ###")
#for i in range(len(self.zm.call_stack)):
for i in range(len(self.zm.call_stack), 0, -1):
self.print_frame(self.zm.call_stack[i-1],i)
#self.zm.print_debug(3,"### frame stack bottom ###")
def read_variable(self, var_num):
"""Read value from variable"""
if var_num == 0:
# Stack variable
if(len(self.zm.call_stack[-1].data_stack) > 0):
value = self.zm.call_stack[-1].data_stack.pop()
#self.zm.print_debug(3,f"read data stack value {value}")
#self.zm.print_debug(3,f"data stack({len(self.zm.call_stack[-1].data_stack)}): {self.zm.call_stack[-1].data_stack}")
return value
else:
#self.zm.print_debug(3,"warning: data stack is empty")
self.zm.print_error("data stack is empty in read_variable()")
self.zm.game_running = False
return 0
elif var_num <= 15:
# Local variable
f = self.zm.call_stack[-1]
#if hasattr(f,"local_vars"):
#self.zm.print_debug(3,f"read local var {var_num - 1}: {f.local_vars[var_num - 1]} {f.local_vars}")
return f.local_vars[var_num - 1]
return 0
else:
# Global variable
global_index = var_num - 16
addr = self.zm.variables_addr+global_index*2
#print(f"debug: index:{global_index}, var mem start: 0x{self.zm.variables_addr:04X}, address: 0x{addr:04X}")
#value = self.zm.memory[addr] << 8 | self.zm.memory[addr+1]
value = self.zm.read_word(addr)
#self.zm.print_debug(3,f"read global var {global_index} from 0x{addr:04x}: {value}")
return value
def write_variable(self, var_num, value):
"""Write value to variable"""
#self.zm.print_debug(3,f"write_variable() {var_num} {value}")
value = value & 0xFFFF # Ensure 16-bit value
if var_num == 0:
# Stack variable
self.zm.call_stack[-1].data_stack.append(value)
#self.zm.print_debug(3,f"write data stack value {value}")
#self.zm.print_debug(3,f"data stack({len(self.zm.call_stack[-1].data_stack)}): {self.zm.call_stack[-1].data_stack}")
elif var_num <= 15:
# Local variable
f = self.zm.call_stack[-1]
if hasattr(f,"local_vars"):
f.local_vars[var_num -1 ] = value
#self.zm.print_debug(3,f"write local var {var_num - 1}: {value} {f.local_vars}")
else:
# Global variable
global_index = var_num - 16
addr = self.zm.variables_addr + global_index*2
#self.zm.print_debug(3,f"variables_address:0x{addr:04x}")
#self.zm.print_debug(3,f"index:{global_index}, var mem start: 0x{self.zm.variables_addr:04X}, address: 0x{addr:04X}")
self.zm.write_word(addr, value)
#self.zm.print_debug(3,f"write global var {global_index} to 0x{addr:04x}: {value}")
def init_frame(self):
f = Frame()
f.return_pointer = self.zm.read_word(0x06) # Initial PC
#print("debug: ptr: ", f.return_pointer)
#print(f"debug 2: 0x{self.zm.memory[0x06]:02x}")
self.zm.call_stack.append(f)
#print(f"debug: initial frame {len(self.zm.call_stack)}:")
#self.print_frame(f,0)
def execute_instruction(self):
"""Execute one Z-machine instruction"""
try:
opcode, operands, form, pccount, opcode_byte = self.fetch_instruction()
self.instruction_count += 1
maxcount = 6000
if self.instruction_count > maxcount:
self.zm.print_error(f"{maxcount} instruction limit reached")
sys.exit()
# Map opcode based on form
if form == LONG_FORM:
full_opcode = opcode # 2OP opcodes
elif form == SHORT_FORM:
if len(operands) == 0:
full_opcode = opcode # 0OP opcodes
else:
full_opcode = 0x80 | opcode # 1OP opcodes
else: # VARIABLE_FORM
if opcode_byte & 0x20 == 0:
full_opcode = opcode # 2OP opcodes
else:
full_opcode = 0x20 | opcode # VAR opcodes
#print(f"opcode_byte:0x{opcode_byte:02x} opcode:0x{opcode:02x} full_opcode:0x{full_opcode:02x}")
self.zm.opcode = full_opcode
# Execute opcode
if full_opcode in self.opcodes:
#self.zm.print_debug(1,f"**start {self.instruction_count}:{self.opcodes[full_opcode][1]} {operands} pc:0x{(self.zm.pc-pccount):04x}/0x{self.zm.pc:04x} opcode:0x{opcode_byte:02x}/0x{opcode:02x}/0x{full_opcode:02x}")
self.opcodes[full_opcode][0](operands)
#self.zm.print_debug(2,f"local vars: {self.zm.call_stack[-1].local_vars}")
#self.zm.print_debug(2,f"data stack: {self.zm.call_stack[-1].data_stack}")
#self.zm.print_debug(3,f"**end {self.opcodes[full_opcode][1]} pc:0x{(self.zm.pc):04X}")
else:
self.zm.print_error(f"Unimplemented opcode:0x{opcode:02X}/0x{full_opcode:02X} pc:0x{(self.zm.pc-pccount):04X}")
self.zm.game_running = False
return
except Exception as e:
self.zm.print_error(f"Execution error at PC 0x{self.zm.pc:04X}: {e}")
self.zm.game_running = False
"""
Notes from c source code:
Take a jump after an instruction based on the flag, either true or false. The
jump can be modified by the change logic flag. Normally jumps are taken
when the flag is true. When the change logic flag is set then the jump is
taken when flag is false. A PC relative jump can also be taken. This jump can
either be a positive or negative byte or word range jump. An additional
feature is the return option. If the jump offset is zero or one then that
literal value is passed to the return instruction, instead of a jump being
taken. Complicated or what!
"""
def branch(self, condition):
"""Handle conditional branch"""
#self.zm.print_debug(3,f"branch() {condition}")
#self.zm.print_debug(3,f"pc = 0x{self.zm.pc:02X}")
branch_byte = self.zm.read_byte(self.zm.pc)
self.zm.pc = self.zm.pc + 1
#self.zm.print_debug(3,f"branch_byte 1:0x{branch_byte:02X}")
branch_on_true = condition
if (branch_byte & 0x80) == 0:
branch_on_true = not branch_on_true
branch_offset = branch_byte & 0x3F
#self.zm.print_debug(3,f"branch_on_true: {branch_on_true}")
#self.zm.print_debug(3,f"pc = 0x{self.zm.pc:02X}")
if (branch_byte & 0x40) == 0:
# Two-byte offset
second_byte = self.zm.read_byte(self.zm.pc)
self.zm.pc += 1
#self.zm.print_debug(3,f"branch_byte 2:0x{second_byte:02X}")
branch_offset = ((branch_offset << 8) | second_byte)
if branch_offset & 0x2000:
branch_offset |= 0xC000 # Sign extend
if branch_offset > 0 and branch_offset & 0x8000 :
branch_offset -= 0x10000 # make negative
#self.zm.print_debug(3,f"branch_offset: 0x{branch_offset:04x}")
if branch_on_true == True:
if branch_offset == 0:
self.op_rfalse([])
elif branch_offset == 1:
self.op_rtrue([])
else:
self.zm.pc += branch_offset - 2
#self.zm.print_debug(3,f"return branch(), branch_offset = 0x{branch_offset:04X}, pc = 0x{self.zm.pc:04X}")
def print_object(self, obj):
objp = self.get_object_address(obj)
name = self.get_object_name(obj)
parent = self.zm.read_byte(objp + object_parent)
next = self.zm.read_byte(objp + object_next)
child = self.zm.read_byte(objp + object_child)
#self.zm.print_debug(3,f"~~Object {obj}(0x{objp:04x}):")
#self.zm.print_debug(3,f"~name: {name}")
#self.zm.print_debug(3,f"~parent: {parent} ({self.get_object_name(parent)})")
#self.zm.print_debug(3,f"~next: {next} ({self.get_object_name(next)})")
#self.zm.print_debug(3,f"~child: {child} ({self.get_object_name(child)})")
def read_object(self, objp, field):
#self.zm.print_debug(3,f"read_object() {objp} {field}")
if field == object_parent:
result = self.zm.read_byte(objp + object_parent)
elif field == object_next:
result = self.zm.read_byte(objp + object_next)
else:
result = self.zm.read_byte(objp + object_child)
#self.zm.print_debug(3,f"read_object() returns {result}")
return result
def write_object(self, objp, field, value):
#self.zm.print_debug(3,f"write_obj() {objp} {field} {value}")
if field == object_parent:
self.zm.write_byte(objp + object_parent, value)
elif field == object_next:
self.zm.write_byte(objp + object_next, value)
else:
self.zm.write_byte(objp + object_child, value)
#self.zm.print_debug(3,"write_obj() done")
"""
Remove an object by unlinking from its parent object and from its
siblings.
"""
def remove_object(self, obj):
#self.zm.print_debug(3,f"remove_object() {obj}")
objp = self.get_object_address(obj)
# Get parent of object, and return if no parent
parent = self.read_object( objp, object_parent)
#self.zm.print_debug(3,f"parent: {parent}")
if parent == 0:
return
# Get address of parent object
parentp = self.get_object_address( parent)
# Find first child of parent
child = self.read_object( parentp, object_child)
# If object is first child then just make the parent child pointer
# equal to the next child
if child == obj:
self.write_object( parentp, object_child, self.read_object( objp, object_next ) )
else:
# Walk down the child chain looking for this object
while True:
childp = self.get_object_address(child)
child = self.read_object(childp, object_next)
if child == obj:
break
# Set the next pointer the previous child to the next pointer
# of the current object child pointer */
self.write_object( childp, object_next, self.read_object( objp, object_next ) )
# Set the parent and next child pointers to NULL
self.write_object( objp, object_parent, 0 )
self.write_object( objp, object_next, 0 )
#self.zm.print_debug(3,"remove_object() done")
def get_property_addr(self, obj):
"""Calculate the address of the start of the property list associated with an object."""
#self.zm.print_debug(3,f"get_property_addr() {obj}")
object_addr = self.get_object_address(obj)+ property_offset
prop_addr = self.zm.read_word( object_addr)
size = self.zm.read_byte( prop_addr )
#self.zm.print_debug(3,f"object: {obj} object_addr: {object_addr} prop_addr: {prop_addr} size: {size}")
value = prop_addr + ( size * 2 ) + 1
#self.zm.print_debug(3,f"get_property_addr() returns {value}")
return value
def get_next_prop(self, prop_addr):
"""Calculate the address of the next property in a property list."""
#self.zm.print_debug(3,f"get_next_prop() {prop_addr}")
value = self.zm.read_byte( prop_addr )
prop_addr+=1
"""Calculate the length of this property"""
if h_type <= 3:
value >>= 5;
elif not( value & 0x80 ):
value >>= 6;
else:
value = self.get_byte( prop_addr )
value &= property_size_mask;
if value == 0:
value = 64 #spec 1.0
"""Address property length to current property pointer"""
return prop_addr + value + 1;
def op_rtrue(self, operands):
"""Return true from current routine"""
self.return_from_routine(1)
def op_rfalse(self, operands):
"""Return false from current routine"""
self.return_from_routine(0)
def op_print(self,operands):
"""Print literal string"""
text = self.decode_string(self.zm.pc)
self.write_to_line(text)
#self.zm.print_debug(3,f"op_string: '{text}'")
# Skip over the string
self.zm.pc = self.skip_string(self.zm.pc)
def op_print_ret(self, operands):
"""Print literal string and return true"""
self.op_print(operands)
self.write_to_line("\n")
self.op_rtrue(operands)
def op_ret_popped(self, operands):
"""Return popped value from stack"""
if len(self.zm.call_stack[-1].data_stack) > 0:
value = self.zm.call_stack[-1].data_stack.pop()
else:
value = 0
self.return_from_routine(value)
def op_quit(self, operands):
"""Quit the game"""
self.zm.game_running = False
def op_new_line(self, operands):
"""Print newline"""
self.write_to_line("\n")
def op_jz(self, operands):
#self.print_frame(self.zm.call_stack[-1],"op_jz")
"""Jump if zero"""
if operands:
self.branch(not operands[0] )
def op_je(self, operands):
"""Jump if equal"""
if len(operands) >= 2:
condition = operands[0] == operands[1]
# Check additional operands
for i in range(2, len(operands)):
if operands[0] == operands[i]:
condition = True
break
self.branch(condition)
def op_jl(self, operands):
"""Jump if less than"""
if len(operands) >= 2:
# Convert to signed 16-bit
a = operands[0] if operands[0] < 32768 else operands[0] - 65536
b = operands[1] if operands[1] < 32768 else operands[1] - 65536
self.branch(a < b)
def op_jg(self, operands):
"""Jump if greater than"""
if len(operands) >= 2:
# Convert to signed 16-bit
a = operands[0] if operands[0] < 32768 else operands[0] - 65536
b = operands[1] if operands[1] < 32768 else operands[1] - 65536
self.branch(a > b)
def op_load(self, operands):
"""Load variable"""
if operands:
value = self.read_variable(operands[0])
# Store result (this is a simplification)
self.store_result(value)
def op_store(self, operands):
"""Store value in variable"""
if len(operands) >= 2:
self.write_variable(operands[0], operands[1])
def op_add(self, operands):
"""Add two values"""
if len(operands) >= 2:
result = (operands[0] + operands[1]) % 0x10000
self.store_result(result)
def op_sub(self, operands):
"""Subtract two values"""
if len(operands) >= 2:
result = (operands[0] - operands[1]) % 0x10000
self.store_result(result)
def op_print_char(self, operands):
"""Print character"""
if operands:
char = chr(operands[0]) if 32 <= operands[0] <= 126 else '?'
self.write_to_line(char)
def op_print_num(self, operands):
"""Print number"""
if operands:
# Convert to signed
num = operands[0] if operands[0] < 32768 else operands[0] - 65536
self.write_to_line(str(num))
# Format and output the status line for type 3 games only.
def show_status(self):
location = self.get_object_name(self.read_variable( 16 ))
score = self.read_variable( 17 )
moves = self.read_variable( 18 )
self.zm.update_status_line(location, score, moves)
"""
Search the dictionary for a word. Just encode the word and binary chop the
dictionary looking for it.
"""
def find_word(self,token, chop, entry_size ):
#self.zm.print_debug(3,f"find_word() {token}")
buff = []*3
mask = [0]*3
word_index = 0
offset = 0
status = 0
# Don't look up the word if there are no dictionary entries
if self.zm.dictionary_size == 0:
return 0
# Encode target word */
buff = self.encode_string( len(token), token);
# create mask for first 6 letters for comparison
for j in range(3):
mask[j] = 0x8000 # presever end string bit
for i in [10, 5, 0]:
test = (buff[j]>>i) &0x1f
if test != 0x1010:
mask[j] |= 0x1f << i
else:
break # exit inner loop
"""
Do a binary chop search on the main dictionary, otherwise do
a linear search
"""
word_index = chop - 1
if self.zm.dictionary_size > 0:
# binary chop until word is found
while chop > 0:
chop = chop // 2
#self.zm.print_debug(4,f"word index at {word_index}, chop at {chop}")
# Calculate dictionary offset
if word_index > (self.zm.dictionary_size -1):
word_index = self.zm.dictionary_size -1
offset = self.zm.dictionary_offset + ( word_index * entry_size )
#self.zm.print_debug(4,f"index: {word_index}/{chop} compare: 0x{buff[0]:04x} with 0x{self.zm.read_word(offset + 0):04x}, offset: 0x{offset:04x}")
status1 = (buff[0] & mask[0]) - (self.zm.read_word(offset+0) & mask[0])
status2 = (buff[1] & mask[1]) - (self.zm.read_word(offset+2) & mask[1])
#status1 = buff[0] - self.zm.read_word(offset + 0)
#status2 = buff[1] - self.zm.read_word(offset + 2)
#status3 = buff[2] - self.zm.read_word(offset + 4)
#status = status1
#status = (status2 == 0)
#if h_type < 4:
# status = True
#else:
# status = (status3 == 0)
# if word matches then return dictionary offset
if status1 == 0 and status2 == 0: # and (h_type < 4 or status3 == 0):
#self.zm.print_debug(3,f"'{token}' found at offset 0x{offset:04x} (binary search)")
#self.zm.print_debug(3,f"token at offset 0x{offset:04x}: '{self.decode_string(offset)}'")
return offset
if status1 > 0 or (status1 == 0 and status2 > 0):
word_index += chop
# deal with end of dictionary case
if word_index >= self.zm.dictionary_size:
word_index = self.zm.dictionary_size - 1
else:
word_index -= chop
# Deal with start of dictionary case
if word_index < 0:
word_index = 0
else:
for word_index in range(0, -self.zm.dictionary_size, 1):
# calculate dictionary offset
offset = self.zm.dictionary_offset + (word_index * entry_size)
# if word matches then return dictionary offset
status1 = buff[0] - self.zm.read_word(offset + 0)
status2 = buff[1] - self.zm.read_word(offset + 2)
status3 = buff[2] - self.zm.read_word(offset + 4)
if status1 == 0 and status2 == 0 and (h_type < 4 or status3 == 0):
#self.zm.print_debug(3,f"'{token}' found at offset 0x{offset:04x} (linear search)")
return offset
#self.zm.print_debug(3,f"'{token}' not found")
return 0
"""
Convert a typed input line into tokens. The token buffer needs some
additional explanation. The first byte is the maximum number of tokens
allowed. The second byte is set to the actual number of token read. Each
token is composed of 3 fields. The first (word) field contains the word
offset in the dictionary, the second (byte) field contains the token length,
and the third (byte) field contains the start offset of the token in the
character buffer.
"""
def tokenize_line(self, char_buf, token_buf, dictionary, flag):
#self.zm.print_debug(3,f"tokenize line() char_buf:{char_buf} token_buf:{token_buf} dictionary:0x{dictionary:04x} flag:0x{flag:02x}")
if h_type > 4:
slen = self.zm.read_byte(char_buf)
str_end = char_buf + 2 + slen
else:
#slen = self.zm.read_byte(char_buf)
pos = 1
while self.zm.read_byte(char_buf + pos) != 0:
pos += 1
str_end = char_buf + 1 + pos;
slen = pos
#print(f"slen:{slen}")
# Initialise word count and pointers
words = 0
if h_type > 4:
cp = char_buf + 2
else:
cp = char_buf + 1
tp = token_buf + 2;
buff = ""
for i in range(1,slen):
buff += chr(self.zm.read_byte(char_buf + i))
# remove extra spaces within tokens
buff = " ".join(buff.split())
# Initialise dictionary
dictp = self.zm.read_word(dictionary)
count = self.zm.read_byte(dictp)
dictp += 1
#self.zm.print_debug(3,f"dictp:0x{dictp:04x} count:{count}")
delims = ""
punctuation = [0] * 16
for i in range(count):
#punctuation[i] = self.zm.read_byte(dictp)
delims += chr(self.zm.read_byte(dictp))
dictp += 1
entry_size = self.zm.read_byte(dictp)
dictp += 1
self.zm.dictionary_size = self.zm.read_word(dictp)
self.zm.dictionary_offset = dictp + 2
#self.zm.print_debug(3,f"dict size: {self.zm.dictionary_size} offset: {self.zm.dictionary_offset}")
delims = "[" + delims + " \t\n\r\f.,?" + "]"
# Calculate the binary chop start position
if self.zm.dictionary_size > 0:
word_index = self.zm.dictionary_size / 2
chop = 1
while True:
chop *= 2
word_index = word_index // 2
if word_index == 0:
break
max_tokens = self.zm.read_byte(token_buf)
regex = re.compile(delims)
tokens = regex.split(buff.rstrip('\x00'))
words = 0
#self.zm.print_debug(3,f"buff: '{buff}' to tokens: {tokens}")
for token in tokens:
# Get the word offset from the dictionary
word = self.find_word(token, chop, entry_size)
if words <= max_tokens: # and word != 0:
self.zm.write_byte(2+token_buf + words*4 + 0, word >> 8)
self.zm.write_byte(2+token_buf + words*4 + 1, word & 0xff)
self.zm.write_byte(2+token_buf + words*4 + 2, len(token))
self.zm.write_byte(2+token_buf + words*4 + 3, buff.find(token)+1)
words += 1
self.zm.write_byte(token_buf,59)
self.zm.write_byte(token_buf+1,words)
def op_sread(self, operands):
"""Read string from user"""
#self.zm.print_debug(3,f"op_sread() {operands}")
if len(operands) >= 2:
# Refresh status line
if h_type < 4:
self.show_status()
# Reset line count
self.zm.lines_written = 0
self.write_to_line("", True) # show prompt
# Initialise character pointer and initial read size
#cbuf = ( char * ) &datap[argv[0]]
#in_size = ( h_type > 4 ) ? cbuf[1] : 0;
cbuf = operands[0]
if h_type > 4:
in_size = self.zm.read_byte(cbuf + 1)
else:
in_size = 0
# Get user input
user_input = self.zm.get_input()
self.instruction_count = 1 # reset for each input
# turn on debug mode if input start with "~"
self.zm.debug = 0
while len(user_input) > 0 and user_input[0] == "~":
user_input = user_input[1:]
self.zm.debug += 1 if self.zm.debug <= 10 else 0
# fix, max_len always returns 0 after first blank line, hard coding max_len for now
max_len = 100
# convert string to lowercase
user_input = user_input.lower().strip()
for i in range(max_len):
if i < len(user_input):
self.zm.write_byte(cbuf+1+i, ord(user_input[i]))
else:
self.zm.write_byte(cbuf+1+i,0)
self.zm.write_byte(cbuf, len(user_input))
# Tokenize the line, if a token buffer is present */
if operands[1]:
self.tokenize_line( cbuf, operands[1], h_words_offset, 0 )
def store_result(self, value):
"""Store result of instruction"""
result_var = self.zm.read_byte(self.zm.pc)
self.zm.pc += 1
#self.zm.print_debug(3,f"store_result(): write_variable({result_var}, {value})")
self.write_variable(result_var, value)
def return_from_routine(self, value):
"""Return from current routine"""
if self.zm.call_stack:
#self.zm.pc = self.zm.call_stack[-1].get('stack', []).pop() if self.zm.call_stack[-1].get('stack') else 0
# get operand count
#self.zm.print_debug(3,f"pop frame {len(self.zm.call_stack)}:")
#self.print_frame_stack()
#self.zm.call_stack.pop()
f = self.zm.call_stack.pop()
self.print_frame_stack()
#self.print_frame(f,len(self.zm.call_stack))
if len(self.zm.call_stack) == 0:
self.zm.print_error("call stack is empty")
self.zm.game_running = False
return
# restore pc
newpc = f.return_pointer
#self.zm.print_debug(3,f"pointer from 0x{self.zm.pc:04X} to 0x{newpc:04X}")
self.zm.pc = newpc
else:
self.zm.game_running = False
# save return value
# future: check if returning from function call in later ZM versions
self.store_result(value)
def write_zchar(self, c):
c = c & 0xff
if ord(" ") <= c and c <= ord("~"):
self.write_to_line(chr(c))
elif c == 13:
self.write_to_line("\r")
# don't care about other characters at this time
def encode_string(self, len, s):
# Encode Z-machine string
#self.zm.print_debug(3,f"encode_string() '{s}', len:{len}")
codes = [0]*9
buffer = [0]*3
# Initialise codes count and prev_table number
codes_count = 0
prev_table = 0
pos = 0
while len > 0:
len -= 1
"""
Set the table and code to be the ASCII character inducer, then
look for the character in the three lookup tables. If the
character isn't found then it will be an ASCII character.
"""
table = 2
code = 0
for i in range(3):
for j in range(26):
if v3_lookup_table[i][j] == s[pos]:
table = i
code = j
"""
Type 1 and 2 games differ on how the shift keys are used. Switch