forked from ajgbarnes/level9
-
Notifications
You must be signed in to change notification settings - Fork 0
/
level9.py
1777 lines (1532 loc) · 56.4 KB
/
level9.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
###############################################################################
# Python Level 9 Interpreter for Version 1 Games
###############################################################################
#
# Written after reverse engineering the BBC Micro game.
#
# Implementation in Python of the Level 9 BBC Micro Version 1 A-Code engine
# used in the following games:
#
# - Adventure Quest (1982)
# - Colossal Adventure (1982)
# - Dungeon Adventure (1982)
# - Snowball (1983)
# - Lords of Time (1983)
#
# Will extend this at some point to v2, v3 and v4.
#
# This is actually the second iteration as the first looked quite similar to the
# assembly code when I was working out what it all did.
#
# Game files are written by Level 9 Computing (c) Copyright 1982, 1983
#
# Code and comments by Andy Barnes (c) Copyright 2022 (for now)
#
# Twitter @ajgbarnes
#
# This implementation uses the same function and list handler
# names as the [Level 9 interpeter by Glenn Summers and others](https://github.com/DavidKinder/Level9/blob/master/level9.c)
# for consistency and familiarity.
#
# This was used a reference to functions only as I struggled understanding
# the code - nearly all my understanding came from decompiling the BBC Micro's
# game code.
###############################################################################
from fileinput import filename
import sys
import signal
import re
import time
import logging
import argparse
###############################################################################
# Load the version1 file configuration information
###############################################################################
from l9config import v1Configuration
###############################################################################
# This table is used by the vm_fn_exit command handler in its second scan
# of the exit data to see if it's possible to go from another location
# to the current location using the inverse direction to the way the player wants
# to move e.g. if the player is moving E from location 1 to 2, then is it possible
# to move W from location to 2 and 1 and can do the exit flags allow it to be
# used for reverse location lookup.
#
# Note Lords of Time requires this to have 19 entries when OPEN DOOR is
# used (bug in the A-Code?). So extending with four 0xff bytes
###############################################################################
inverseDirectionTable = [0x00, 0x04, 0x06, 0x07, 0x01, 0x08, 0x02, 0x03,
0x05, 0x0a, 0x09, 0x0c, 0x0b, 0xff, 0xff, 0x0f, 0xff, 0xff, 0xff, 0xff]
vm_variables_previous = [0]*256
vm_variables = [0]*256
vm_stack = []
vm_listarea = [0]*512
vm_listarea_previous = [0]*512
vm_dictionary = {}
charsWrittenToLine = 0
###############################################################################
# Default randomseed for game events - can be set at any time with
# #randomseed <value>
# either manually or from a script
###############################################################################
randomseed=int(time.time()) & 0xff
###############################################################################
# File that contains the automated script to execute (if any).
# Holds the file handle.
###############################################################################
scriptFile = None
##############################################################################
# Not used but a reference index of the commands that the A-Code supports
# (I used it for logging at some early point). Zero based index so goto = 0.
##############################################################################
opCodes=[
"goto",
"intgosub",
"intreturn",
"printnumber",
"messagev",
"messagec",
"function",
"input",
"varcon",
"varvar",
"_add",
"_sub",
"ilins",
"ilins",
"jump",
"exit",
"ifeqvt",
"ifnevt",
"ifltvt",
"ifgtvt",
"nop",
"nop",
"nop",
"nop",
"ifeqct",
"ifnect",
"ifltct",
"ifgtct",
"printinput",
"ilins",
"ilins",
"ilins",
]
###############################################################################
# isValidHex()
#
# Validates a string is in 0xNN format
#
# Parameters:
# string - holds the string to be validate as hex
#
# Returns:
# True - string is in 0xNN format
# False - invalid format
###############################################################################
def isValidHex(string):
return re.search("^0x[0-9a-fA-F]{2}$", string) is not None
###############################################################################
# signal_handler()
#
# Signal handler for SIGINT (when someone pressses CTRL+C)
# just exits cleanly without an error / stack trace
#
# Parameters:
# signum - the signal that was invoked
# frame - the frame object
#
# Returns:
# n/a
###############################################################################
def signal_handler(signum, frame):
sys.exit(0)
###############################################################################
# _process_hash_commands()
#
# If a player enters a # command, match it and process here. These are
# not part of the original Level 9 game engine - just a few tools for
# helping to understand what is going on.
#
# Supports:
# #vars - lists all game variable values
# #var <number> - displays a single game variable value
# #seed <number> - sets the random seed to the value - useful for
# debugging when a game contains random events
# #setvar <number> <value> - Sets variable to the value. Can be decimal
# or hexadecimal values (0xNN)
# #setlist <number> <value> - Set item <number> to <value>. Can be decimal
# or hexadecimal values (0xNN)
# #list - lists all the values in the listarea
# #dict - print the dictionary for the game
#
#
#
# Parameters:
# data - the game file byte array
# pc - the virtual machine program counter
# userInput - the text string typed by the player
# signum - the signal that was invoked
# frame - the frame object
#
# Returns:
# n/a
###############################################################################
def _process_hash_commands(data, pc, userInput):
global randomseed
buffer=""
strippedInput = userInput.strip().lower()
# Give yourself all the items
#for x in range(80,159):
# vm_listarea[x]=0xff
match strippedInput.split():
# Prints the dictionary
case ['#dict' | '#dictionary']:
for word in vm_dictionary.keys():
print(word.replace("'", "") + " ", end='')
if word == '9':
break
print("")
# Sets the random seed which can be used by the A-Code
# for random game events
case ["#seed", seed]:
if(seed.isdigit()):
randomseed = int(seed)
print("Seed set to "+seed)
if(isValidHex(seed)):
randomseed = int(seed,16)
print("Seed set to "+hex(seed))
# Prints the value of just one variable
case ['#var', variable]:
if(variable.isdigit()):
intvariable = int(variable)
if(vm_variables[intvariable] == vm_variables_previous[intvariable]):
print(f"\033[0m{vm_variables[intvariable]:04x} (hex)")
else:
print(f"\033[92m{vm_variables[intvariable]:04x}\033[0m (hex)")
elif(isValidHex(variable)):
intvariable = int(variable,16)
if(vm_variables[intvariable] == vm_variables_previous[intvariable]):
print(f"\033[0m{vm_variables[intvariable]:04x} (hex)")
else:
print(f"\033[92m{vm_variables[intvariable]:04x}\033[0m (hex)")
print("")
# Prints the value of ALL variables
case ['#vars', *_]:
print(" x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf")
print(" ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----")
for idx, variable in enumerate(vm_variables):
#buffer = "" + str(idx - idx % 10)
if(idx > 0 and (idx % 16 == 0 or idx == len(vm_variables))):
startIdx = (idx - 16) - (idx % 16)
print(f"\033[0m{startIdx:03x}"+" |"+buffer)
buffer = ""
if(vm_variables[idx] == vm_variables_previous[idx]):
buffer += f" \033[0m{variable:04x}"
else:
buffer += f" \033[92m{variable:04x}"
print("")
# Set the value of a variable
case ["#setvar", variable, value]:
if(variable.isdigit() and value.isdigit()):
vm_variables_previous[int(variable)]=vm_variables[int(variable)]
vm_variables[int(variable)]=int(value)
print('Variable '+variable+' changed to '+value)
elif(isValidHex(variable) and isValidHex(value)):
vm_variables_previous[int(variable,16)]=vm_variables[int(variable,16)]
vm_variables[int(variable,16)]=int(value,16)
print('Variable '+variable+' changed to '+value)
# Set the value in the list area (all dynamic lists are stored there)
case["#setlist", item, value]:
if(item.isdigit() and value.isdigit()):
vm_listarea[int(item)]=int(value)
print(vm_listarea[int(item)])
print('List area item '+item+' changed to '+value)
elif(isValidHex(item) and isValidHex(value)):
vm_listarea[int(item,16)]=int(value,16)
print(hex(vm_listarea[int(item,16)]))
print('List area item '+item+' changed to '+value)
# Print all values in the dynamic list area
case ['#list', *_]:
print(" x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf")
print(" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --")
for idx, variable in enumerate(vm_listarea):
if(idx > 0 and (idx % 16 == 0 or idx == len(vm_listarea))):
startIdx = (idx - 16) - (idx % 16)
print(f"\033[0m{startIdx:03x}"+" |"+buffer)
buffer = ""
if(vm_listarea[idx] == vm_listarea_previous[idx]):
buffer += f" \033[0m{variable:02x}"
else:
buffer += f" \033[92m{variable:02x}"
print("")
# Print all values in the dynamic list area
case ['#message' | '#msg', number]:
if(number.isdigit()):
address = _getAddrForMessageN(data, int(number))
_printMessage(data, address)
print("")
elif(isValidHex(number)):
address = _getAddrForMessageN(data, int(number, 16))
_printMessage(data, address)
print("")
case other:
print('Invalid command')
###############################################################################
# _getSignedNumber
#
# Converts a twos complement value of a byte to a positive or negative
# integer.
#
# Parameters:
# byte - value to convert
#
# Returns:
# Integer in range of +127 to -127
###############################################################################
def _getSignedNumber(byte):
if(byte>127):
signedNumber=(256-byte) * -1
else:
signedNumber=byte
return signedNumber
###############################################################################
# _getAddrForFragment
#
# Gets the address in the game file of the nth common word fragment. Each
# common fragment is seperated by a 0x01.
#
#
# Parameters:
# data - the game file byte array
# fragmentNumber - nth fragment to find address of
#
# Returns:
# Address of the nth fragment
###############################################################################
def _getAddrForFragment(data, fragmentNumber):
address=commonFragmentsAddr
while fragmentNumber:
if(data[address]==1):
fragmentNumber = fragmentNumber - 1
address=address+1
return address
###############################################################################
# _getAddrForMessageN
#
# Gets the address in the game file of the nth message. Each
# message is seperated by a 0x01.
#
#
# Parameters:
# data - the game file byte array
# messageNumber - nth message to find address of
#
# Returns:
# Address of the nth message
###############################################################################
def _getAddrForMessageN(data, messageNumber):
messagesAddress = messagesStartAddr
# Keeping looping until the nth message is found
while messageNumber:
byte = data[messagesAddress]
if(byte == 0):
logging.error("ERROR couldn't find nth string")
sys.exit(1)
elif(byte == 1):
messageNumber = messageNumber - 1
messagesAddress = messagesAddress + 1
return messagesAddress
###############################################################################
# _getAddrForMessageN
#
# Decode the message at the passed address. Does NOT print it to the screen.
# Loop through each byte:
# - If a byte is > 0x5E then it's a common fragment (go decode)
# - If a byte is 0x01 then it's the end of the message
# - If a byte is 0x01 then it's the end of the messages area of memory
#
#
# Parameters:
# data - the game file byte array
# msgAddress - start address in the game file of the address
#
# Returns:
# Decoded plain text message
###############################################################################
def _getMessage(data, msgAddress):
message=''
byte = data[msgAddress]
while byte:
if(byte >= 0x5E):
fragmentNumber = byte - 0x5E
fragmentAddr = _getAddrForFragment(data,fragmentNumber)
newMessage = _getMessage(data, fragmentAddr)
message = message + newMessage
elif(byte == 0x02):
# Used to denote end of some fragments?
break
elif(byte == 0x01):
# End of fragment or string
break
else:
message = message + str(chr(byte+0x1D))
#_getCharacter(byte)
msgAddress = msgAddress + 1
byte = data[msgAddress]
return message
###############################################################################
# _printMessage
#
# Calls the routine to decode the message at msgAddress and then prints
# the character to the screen with the following character rules:
# '%' - replace with a carriage return but only print it if more than 2
# characters have been written to the line
# '_' - replace with a space
#
# Anything else is just printed
#
# Parameters:
# data - the game file byte array
# msgAddress - start address in the game file of the message to print
#
# Returns:
# n/a
###############################################################################
def _printMessage(data, msgAddress):
global charsWrittenToLine
message=_getMessage(data,msgAddress)
for character in message:
if(character == '%' and charsWrittenToLine>2):
print('\n',end='')
charsWrittenToLine = 0
elif(character == '_'):
print(' ',end='')
charsWrittenToLine += 1
elif(character != '%'):
print(character,end='')
charsWrittenToLine += 1
###############################################################################
# _printCharacter()
#
# Used when printing all the messages
#
#
# Parameters:
# byte - byte to print
#
# Returns:
# n/a
###############################################################################
def _printCharacter(byte):
char = chr(byte+int("0x1D",16))
if(char == "%"):
print("\n")
elif(char == "_"):
print(" ")
else:
print(chr(byte+29),end='')
###############################################################################
# _findAndPrintLetters
#
# Recursive function for finding the nth common word fragment and printing
# it - if the nth common word fragment contains another common word fragment
# it wlil call itself to decode and print that
#
# Parameters:
# iteratiions - the nth common word fragment to find
# bytearray - data to loop over
#
# Returns:
# n/a
###############################################################################
def _findAndPrintLetters(iterations, bytearray):
startAddress=commonFragmentsAddr
currentPos=startAddress
loopsLeft=iterations - 0x5E
while loopsLeft:
if(bytearray[currentPos]==1):
loopsLeft = loopsLeft-1
currentPos=currentPos+1
while(bytearray[currentPos]>2):
if(bytearray[currentPos]>=94):
_findAndPrintLetters(bytearray[currentPos], bytearray)
else:
_printCharacter(bytearray[currentPos])
currentPos=currentPos+1
###############################################################################
# _printAllMessage
#
# Prints all the messages for the game
#
# Anything else is just printed
#
# Parameters:
# data - the game file byte array
# msgAddress - start address in the game file of the message to print
#
# Returns:
# n/a
###############################################################################
def _printAllMessages(data,messagesStartAddr):
counter=0
startAddress=messagesStartAddr
address=startAddress
print(hex(counter)," / ",hex(address)," : ",end='')
byte = data[address]
while(byte):
if(byte>=0x5E):
_findAndPrintLetters(byte, data)
pass
elif(byte < 0x5E and byte > 0x02):
_printCharacter(byte)
elif(byte == 2):
break
else:
print("")
counter=counter+1
print(hex(counter)," / ",hex(address+1)," : ",end='')
address=address+1
byte = data[address]
###############################################################################
# vm_fn_load_dictionary
#
# Finds the dictionary in the code starting at dictionaryAddr
# and decodes the words. Puts each word in a python dictionary
# with the word as the key and the command/object value as the value
#
# The last byte of the word has the 8th bit set - this byte is
# followed by the command/object value.
#
# Parameters:
# data - the game file byte array
# dictionaryddr - start address in the game file of the dictionary
#
# Returns:
# n/a
###############################################################################
def vm_fn_load_dictionary(data,dictionaryAddr,printDict):
codeNext = False
word=""
address=dictionaryAddr
byte = data[address]
wordStart=address
while byte:
if codeNext:
if(printDict):
print(hex(byte), " / ",hex(wordStart),word)
vm_dictionary[word]=byte
codeNext=False
word=""
else:
if byte>=127:
codeNext=True
word = word + chr(byte & 0x7F)
address=address+1
byte = data[address]
###############################################################################
# vm_fn_listhandler()
#
# Implements the four list handlers for processing the game lists. Up to
# 5 lists can be defined (technically 6 but the 0 position is never used
# by the v1 games).
#
# The list could be a reference (in the game code) or dynamic
# (outside the game code) list. The list number to look up is
# contained in the bottom 5 bits of the opCode.
#
# 0xE0 - 0xE5
# list#x[ variable[ <operand1> ]] = variable[ <operand2>
# 0xC0 - 0xC5
# variable[ <operand2> ] = list#x[ <operand1> ]
# 0xA0 - 0xA5
# variable[ <operand2> ] = list#x[ variable[ <operand1> ]]
# 0x80 - 0x85
# list#x[ <operand1> ] = variable[ <operand2> ]
#
# Parameters:
# data - the game file byte array
# opCode - list handler code
# pc - the program counter
#
# Returns:
# Updated program counter
###############################################################################
def vm_fn_listhandler(data,opCode,pc):
listNumber = opCode & 0b00011111
if(opCode & 0b00011111 > 0x05):
print(f'Version 1 games only supported 5 lists and this is accessing list {opCode & 0b00011111}')
sys.exit()
# Get the list offset - if it is negative then it is
# a reference (static) list in the game code, otherwise
# it's a working dynamic list in vm_listarea
listOffset = v1Configuration[game]['lists'][listNumber-1]
if(opCode >= 0b11100000): # 0xE0
# list#x[ variable[ <operand1> ]] = variable[ <operand2> ]
pc=pc+1
variable1=data[pc]
pc=pc+1
variable2=data[pc]
if(listOffset < 0):
print('Error: Update to reference list attempted ', hex(opCode), hex(pc))
sys.exit()
offset = listOffset + vm_variables[variable1]
vm_listarea[offset] = vm_variables[variable2]
elif(opCode >= 0b11000000): # 0xC0
# variable[ <operand2> ] = list#x[ <operand1> ]
pc=pc+1
constant = data[pc]
pc=pc+1
variable = data[pc]
if(listOffset < 0):
print('Error: Update to reference list attempted ', hex(opCode), hex(pc))
sys.exit()
vm_variables[variable] = vm_listarea[listOffset+constant]
elif(opCode >= 0b10100000): # 0xA0
# variable[ <operand2> ] = list#x[ variable[ <operand1> ]]
pc=pc+1
variable1 = data[pc]
pc=pc+1
variable2 = data[pc]
if(listOffset >= 0):
vm_variables[variable2] = vm_listarea[listOffset+vm_variables[variable1]]
else:
listItemAddress=aCodeStartAddr+listOffset+vm_variables[variable1]
vm_variables[variable2] = data[listItemAddress]
else: # > 0b1000000 / 0x80
# list#x[ <operand1> ] = variable[ <operand2> ]
pc=pc+1
variable1 = data[pc]
pc=pc+1
variable2 = data[pc]
if(listOffset<0):
print('Error: Update to reference list attempted ', hex(opCode), hex(pc))
sys.exit()
offset = listOffset + variable1
vm_listarea[offset] = vm_variables[variable2]
return pc
###############################################################################
# vm_fn_goto()
#
# Performs a relative or absolute goto
#
# Parameters:
# data - the game file byte array
# opCode - list handler code
# pc - the program counter
#
# Returns:
# Updated program counter
###############################################################################
def vm_fn_goto(data, opCode, pc):
# Get the first operand
pc=pc+1
operand1 = data[pc]
operand2 = None
# The 6th bit indicates if the command has one
# or two operands
if (opCode & 0b00100000):
# Single (it's set)
offset=_getSignedNumber(operand1)
pc=pc+offset-1
else:
# Double (it's not set)
pc=pc+1
operand2=data[pc]
offset=(256 * operand2) + operand1
pc=aCodeStartAddr+offset-1
return pc
###############################################################################
# vm_fn_intgosub()
#
# Places the current program counter on the stack (so it can be
# returned to) and performs a relative or absolute goto
#
# Parameters:
# data - the game file byte array
# opCode - list handler code
# pc - the program counter
#
# Returns:
# Updated program counter
###############################################################################
def vm_fn_intgosub(data, opCode, pc):
# If the 6th bit is set then there's only one
# operand for the offset so the return address is pc+1
# otherwise there are two so it's pc+2
if(opCode & 0b00100000):
vm_stack.append(pc+1)
else:
vm_stack.append(pc+2)
pc=vm_fn_goto(data,opCode,pc)
return pc
###############################################################################
# vm_fn_intreturn()
#
# Returns to the A-Code location at the top of the stack
# (sets the program counter)
#
# Parameters:
# data - the game file byte array
# opCode - list handler code
# pc - the program counter
#
# Returns:
# Updated program counter
###############################################################################
def vm_fn_intreturn(data, opCode, pc):
pc=vm_stack.pop()
return pc
###############################################################################
# vm_fn_printnumber()
#
# Prints the number held in the variable1 to the screen
#
# Parameters:
# data - the game file byte array
# opCode - list handler code
# pc - the program counter
#
# Returns:
# Updated program counter
###############################################################################
def vm_fn_printnumber(data, opCode, pc):
# Get the first operand
pc=pc+1
variable1 = data[pc]
print(str(vm_variables[variable1]),end='')
return pc
###############################################################################
# vm_fn_messagev()
#
# Prints the message with the id held in variable indicated by operand1
#
# Parameters:
# data - the game file byte array
# opCode - list handler code
# pc - the program counter
#
# Returns:
# Updated program counter
###############################################################################
def vm_fn_messagev(data, opCode, pc):
# Get the first operand
pc=pc+1
operand1 = data[pc]
nthMessage = vm_variables[operand1]
address = _getAddrForMessageN(data, nthMessage)
_printMessage(data, address)
return pc
###############################################################################
# vm_fn_messagev()
#
# Prints the message with the id held in operands 1 and 2
#
# Parameters:
# data - the game file byte array
# opCode - list handler code
# pc - the program counter
#
# Returns:
# Updated program counter
###############################################################################
def vm_fn_messagec(data, opCode, pc):
# Get the first operand
pc=pc+1
operand1 = data[pc]
operand2 = None
nthMessage = 0;
# If the 7th bit is set in the opCode
# then there is only one operand, otherwise
# there are two
if (opCode & 0b01000000):
nthMessage = operand1
else:
pc=pc+1
operand2=data[pc]
nthMessage = (operand2 * 256 ) + operand1
address = _getAddrForMessageN(data, nthMessage)
_printMessage(data, address)
return pc
###############################################################################
# vm_fn_function()
#
# Performs one of the following functions based on the operand:
# 1 - exit
# 2 - generate new random seed
# 3 - save game
# 4 - load game
# 5 - Reset all the variables to zero
# 6 - Clear the stack
#
# Parameters:
# data - the game file byte array
# opCode - list handler code
# pc - the program counter
#
# Returns:
# Updated program counter
###############################################################################
def vm_fn_function(data,opCode,pc):
global randomseed
pc=pc+1
requiredFunction = data[pc]
match requiredFunction:
case 1:
sys.exit(0)
case 2:
pc=pc+1
variableToSet=data[pc]
randomseed=(((((randomseed<<8) + 0x0a - randomseed) <<2) + randomseed) + 1) & 0xffff
vm_variables[variableToSet]=randomseed & 0xff
case 3:
with open(game+".sav", "wb") as save_file:
for var in (vm_variables):
save_file.write(var.to_bytes(2,'big'))
for li in (vm_listarea):
save_file.write(li.to_bytes(1,'big'))
case 4:
with open(game+".sav", "rb") as load_file:
for i in range(0, len(vm_variables)):
bytes=load_file.read(2)
print(i)
vm_variables[i] = int.from_bytes(bytes, 'big')
for i in range(0, len(vm_listarea)-1):
bytes=load_file.read(1)
vm_listarea[i] = int.from_bytes(bytes, 'big')
case 5:
# Reset all the variables to zero
for i in range(0,len(vm_variables)):
vm_variables[i]=0
case 6:
# Clear the stack
vm_stack.clear()
case other:
print(f'Unknown function {requiredFunction:02x}')
sys.exit()
return pc
###############################################################################
# vm_fn_input()
#
# Wait for player input and parse the result by looking up each word in the
# dictionary and finding the command/object id with the match (or ignoring)
# a word if it doesn't match.
#
# The ids are placed in the variables identified by the first three operands
# and the word count in the fourth.
#
# Note that if it's prefixed with a hash then it'll be passsed to the hash
# command handler - these are extensions I put in for debugging / understanding
#
# Parameters:
# data - the game file byte array
# opCode - list handler code
# pc - the program counter
#
# Returns:
# Updated program counter
###############################################################################
def vm_fn_input(data,opCode,pc):
global vm_variables_previous
global vm_listarea_previous
# <command> <byte1> <byte2> <byte3> <byte4>
# <byte1> where to store the first cmd/obj
# <byte2> where to store the second cmd/obj
# <byte3> where to store the third cmd/obj
# <byte4> where to store the word count
pc=pc+1
firstWordVar=data[pc]
pc=pc+1
secondWordVar=data[pc]
pc=pc+1
thirdWordVar=data[pc]
pc=pc+1
wordCountVar=data[pc]
wordCount=0
while(True):
userInput = ''
if(scriptFile):
#time.sleep(1)
while(True):
userInput = scriptFile.readline()
if(userInput == ""):
userInput = input().upper()
break
userInput = userInput.replace("*","")
userInput = userInput.split('[')[0]
userInput = userInput.split(';')[0]
userInput = userInput.rstrip()
if(userInput != ''):
break
print(userInput)
#time.sleep(0.8)
userInput=userInput.upper()
else:
# Get user input
userInput = input().upper()
if(len(userInput) > 0 and userInput[0] =="#"):
_process_hash_commands(data, pc, userInput)
else:
vm_variables_previous = vm_variables.copy()
userInput = userInput.split('#')[0]
userInput = re.sub('[,]','',userInput)
userInput = re.sub('[^a-zA-Z0-9.\- ]','',userInput)
# Restrict to the first 39 characters only
if(len(userInput) > 39):
userInput=userInput[0:39]