#!/usr/bin/env python ''' I converted adventure from Fortran IV to python as directly as possible. Python has no GOTOs and adventure felt like it was made of nothing but a maze of twisty little GOTOs! When multiple GOTOs went to the same line number I created a subroutine. The resulting call tree results in unintended recursion, so you will notice that many subroutines return a small dictionary of a subroutine name and its arguments. The dictionary is created at the bottommost level in the call sequence and bubbled up to the very top so that recursion can be avoided. There is probably a better solution. The many, many globals have been collected into dictionaries. This has two advantages. One, is that is simpler to pass a global dictionary than the individual variables, but it also makes suspend/resume possible since the dictionary reflects game state. And besides, the original suspend method of having the player save the core image image is more than a small challenge today! The original code was written on a machine 36-bit words, and remnants of that are still seen in the code with five 7-bit characters. Bit operations on 5-byte integers which are also 5-char strings cannot be converted directly. I didn't convert the XORing of strings to hide them and prevent scanning the running program since the python source has it all it plaintext. I similarly bypassed the password challenge to prove a player is a wizard. It is almost certainly running on a machine controlled by the player. For old times' sake, you still must provide the password. Original comments are maintained but I've added more during the course of reverse engineering the logic in order to port the code. As time allows I hope to improve the ported code and bring it up to modern standards. But don't hold your breath. :-) Mike Markowski, mike.ab3ap@gmail.com Nov 2024 ''' from numpy.random import random, randint import datetime, time import os, sys debug = False # If True, show dwarf locs, lamp energy level. # Adventures # Current limits: # 9650 words of message text (lines, linsiz). # 750 travel options (travel, trvsiz). # 300 vocabulary words (ktab, atab, tabsiz). # 150 locations (ltext, stext, key, cond, abb, atloc, locsiz). # 100 objects (plac, place, fixd, fixed, link (twice), ptext, prop). # 35 "action" verbs (actspk, vrbsiz). # 205 random messages (rtext, rtxsiz). # 12 different player classifications (ctext, cval, clsmax). # 20 hints, less 3 (hintlc, hinted, hints, hntsiz). # 35 magic messages (mtext, magsiz). # There are also limits which cannot be exceeded due to the structure of # the database. (E.g., the vocabulary uses n/1000 to determine word type, # so there can't be more than 1000 words.) These upper limits are: # 1000 non-synonymous vocabulary words # 300 locations # 100 objects # Statement Functions # # # toting(obj) = True if the obj is being carried # here(obj) = True if the obj is at "loc" (or is being carried) # at(obj) = True if on either side of two-placed object # liq(g, dummy) = Object number of liquid in bottle # liqloc(loc) = Object number of liquid (if any) at loc # bitset(l,n) = True if cond[l] has bit n set (bit 0 is units bit) # forced(loc) = True if loc moves without asking for input (cond = 2) # dark(dummy) = True if location "loc" is dark # pct(n) = True n% of the time (n integer from 0 to 100) # # wzdark says whether the loc he's leaving was dark # lmwarn says whether he's been warned about lamp going dim # closng says whether its closing time yet # panic says whether he's found out he's trapped in the cave # closed says whether we're all the way closed # gaveup says whether he exited via "quit" # scorng indicates to the score routine whether we're doing a "score" command # demo is true if this is a prime-time demonstration game # yea is random yes/no reply toting = lambda g,obj: g['place'][obj] == -1 here = lambda g,obj: g['place'][obj] in [-1, g['loc']] at = lambda g,obj: g['loc'] in [g['place'][obj], g['fixed'][obj]] bitset = lambda g,loc,n: (g['cond'][loc] & (1<= 15: # At or beyond Hall of Mists. cave['dflag'] = 1 # Activate dwarf logic. d = location(cave, g, w) continue elif cave['dflag'] == 1: # Set to 2 when first dwarf follows. d = dwarfStartup(cave, g, w) # Start up the dwarves. continue attack,dtotal,stick = dwarfMovement(cave, g, w) # Walk dwarves, pirate. if debug: # Display dwarf & pirate locations for debugging. print(' Dwarves: ') for i in range(1,7): if g['dloc'][i] == 0: # Dead. continue print(' %d: %s' % (g['dloc'][i], locName(g, g['dloc'][i]))) # Now we know what's happening. Let's tell the poor sucker about it. if dtotal == 0: # Number of dwarves following is zero. d = location(cave, g, w) continue if dtotal == 1: speak(g, 4, 'r') # THREATENING LITTLE DWARF else: s = '\n THERE ARE %d THREATENING LITTLE DWARVES ' % dtotal s += 'IN THE ROOM WITH YOU.' print(s) if attack == 0: # No attack, next turn. d = location(cave, g, w) continue if cave['dflag'] == 2: # Dwarf following, cave['dflag'] = 3 # and a little angrier. # If saved not = -1, he bypassed the "start" call. Dwarves get # *very* mad! if cave['saved'] != -1: cave['dflag'] = 20 if attack == 1: speak(g, 5, 'r') # KNIFE IS THROWN AT YOU! k = 52 # IT MISSES!, 53==IT GETS YOU! else: print('\n %d OF THEM THROW KNIVES AT YOU!' % attack) k = 6 # NONE HIT YOU!, 7==ONE OF THEM GETS YOU! if stick <= 1: speak(g, k+stick, 'r') if stick == 0: d = location(cave, g, w) continue else: print('\n %d OF THEM GET YOU!' % stick) g['oldlc2'] = g['loc'] # Save last place before dying. d = dead(cave, g, w, pit=False) # Player is dead. def analyseObject(cave, g, w, wizcom, wd1, wd2, obj, verb=0): ''' Analyse an object word. See if the thing is here, whether we've got a verb yet, and so on. Object must be here unless verb is "find" or "invent(ory)" (and no new verb yet to be analysed). Water and oil are also funny, since they are never actually dropped at any location, but might be here inside the bottle or as a feature of the location. ''' g['obj'] = obj # For use in transitive(). maybeTransitive = g['fixed'][obj] == g['loc'] or here(g, obj) while True: if maybeTransitive: if wd2 != '': # Continue analysis of wd2. return secondWord(cave, g, w, wizcom, wd1, wd2) if g['verb'] != 0: # Obj & verb means transitive. spk = g['actspk'][g['verb']] # Default message for verb. return transitive(cave, g, w, wizcom, wd1, wd2, spk) print('\n WHAT DO YOU WANT TO DO WITH THE %s?' % wd1) return {'fn':'newTurn', 'spk':-1} maybeTransitive = True if obj == w['grate']: if g['loc'] in [1,4,7]: # End of road, valley or streambed slit. obj = w['dprssn'] if 9 < g['loc'] < 15: # In cave, haven't reached Hall of Mists. obj = w['entrnc'] if obj != w['grate']: return {'fn':'motionVerb','goto':8, 'verb':obj, 'kk':-1} if obj == w['dwarf']: upTop = False for i in range(1, 5+1): if g['dloc'][i] == g['loc'] and cave['dflag'] >= 2: upTop = True break if upTop: continue if ((liq(g, w) == obj and here(g,w['bottle'])) or obj == liqloc(g, w)): continue if (obj == w['plant'] and at(g,w['plant2']) and g['prop'][w['plant2']] != 0): g['obj'] = w['plant2'] continue if obj == w['knife'] and g['knfloc'] == g['loc']: g['knfloc'] = -1 spk = 116 # DWARVES' KNIVES VANISH AS THEY STRIKE WALLS OF THE CAVE. return {'fn':'newTurn', 'spk':spk} if obj == w['rod'] and here(g,w['rod2']): g['obj'] = w['rod2'] continue if (g['verb'] in [w['find'], w['invent']]) and wd2 == '': continue break print('\n I SEE NO %s HERE.' % wd1) return {'fn':'newTurn', 'spk':0} def analyseVerb(cave, g, w, wizcom, wd1, wd2, verb): # Analyse a verb. Remember what it was, go back for object if second word # unless verb is "say", which snarfs arbitrary second word. g['verb'] = verb if wd2 != '' and verb != w['say']: return secondWord(cave, g, w, wizcom, wd1, wd2) if verb == w['say']: if wd2 == '': g['obj'] = 0 else: g['obj'] = vocab(g,wd2,-1) spk = g['actspk'][verb] # Default message for verb. if g['obj'] == 0: return intransitive(cave, g, w, wizcom, wd1, wd2, spk) else: return transitive(cave, g, w, wizcom, wd1, wd2, spk) def attack(cave, g, w, wizcom, spk, wd1, wd2): # ATTACK. Assume target if unambiguous. "Throw" also links here. # Attackable objects fall into two categories: enemies (snake, dwarf, # etc.) and others (bird, clam). Ambiguous if two enemies, or if no # enemies but two others. # # Verb can be ATTAC,KILL,FIGHT,HIT,STRIK,SLAY. for i in range(1, 5+1): if g['dloc'][i] == g['loc'] and cave['dflag'] >= 2: break # Dwarf here and following player. else: i = 0 if g['obj'] == 0: # Intransitive, find object. if i != 0: # Which following dwarf is present. g['obj'] = w['dwarf'] if here(g,w['snake']): g['obj'] = g['obj']*100 + w['snake'] if at(g,w['dragon']) and g['prop'][w['dragon']] == 0: g['obj'] = g['obj']*100 + w['dragon'] if at(g,w['troll']): g['obj'] = g['obj']*100 + w['troll'] if here(g,w['bear']) and g['prop'][w['bear']] == 0: g['obj'] = g['obj']*100 + w['bear'] if g['obj'] > 100: # Multiple potential objects here. return what(g, wd1) # Ask, ATTACK WHAT? if g['obj'] == 0: # Still looking for object. # Can't attack bird by throwing axe. if here(g,w['bird']) and g['verb'] != w['throw']: g['obj'] = w['bird'] # Clam and oyster both treated as clam for intransitive case; no # harm done. if here(g,w['clam']) or here(g,w['oyster']): g['obj'] = 100*g['obj'] + w['clam'] if g['obj'] > 100: # Multiple potential objects here. return what(g, wd1) if g['obj'] == w['bird']: spk = 137 # OH, LEAVE THE POOR UNHAPPY BIRD ALONE. if cave['closed']: return {'fn':'newTurn', 'spk':spk} dstroy(cave, g, w['bird']) g['prop'][w['bird']] = 0 # Dead bird. if g['place'][w['snake']] == g['plac'][w['snake']]: # At initial loc. g['tally2'] += 1 # Cannot find bird again. spk = 45 # THE LITTLE BIRD IS NOW DEAD. if g['obj'] == 0: # Never found an object. spk = 44 # THERE IS NOTHING HERE TO ATTACK. if g['obj'] in [w['clam'], w['oyster']]: spk = 150 # THE SHELL IS VERY STRONG if g['obj'] == w['snake']: spk = 46 # ATTACKING THE SNAKE DOESN'T WORK. if g['obj'] == w['dwarf']: spk = 49 # WITH WHAT? YOUR BARE HANDS? if g['obj'] == w['dwarf'] and cave['closed']: dwarvesDisturbed(cave, g, w) # Game ends. if g['obj'] == w['dragon']: spk = 167 # THE POOR THING IS ALREADY DEAD! if g['obj'] == w['troll']: spk = 157 # TROLLS ARE CLOSE RELATIVES WITH THE ROCKS... if g['obj'] == w['bear']: spk = 165 + (g['prop'][w['bear']] + 1)//2 if g['obj'] != w['dragon'] or g['prop'][w['dragon']] != 0: return {'fn':'newTurn', 'spk':spk} # Fun stuff for dragon. If he insists on attacking it, win! Set prop to # dead, move dragon to central loc (still fixed), move rug there (not # fixed), and move him there, too. Then do a null motion to get new # description. speak(g, 49, 'r') # WITH WHAT? YOUR BARE HANDS? g['verb'] = 0 g['obj'] = 0 ans,_ = getin(cave, g, w) if ans not in ['Y', 'YES']: return specialCases(cave, g, w, wizcom, wd1, wd2, g['verb']) speak(g, w['dragon'], 'p', propMsg=1) # YOU HAVE JUST VANQUISHED A DRAGON g['prop'][w['dragon']] = 2 # Dead dragon. g['prop'][w['rug']] = 0 # Mark rug as no dragon sitting on it. k = (g['plac'][w['dragon']] + g['fixd'][w['dragon']])//2 move(cave, g, w['dragon']+100, -1) # Immovable dragon is gone. move(cave, g, w['rug']+100, 0) # Immovable rug is gone. move(cave, g, w['dragon'], k) # Replace with movable dead dragon. move(cave, g, w['rug'], k) # Replace with movable rug. for obj in range(1, 100+1): if g['place'][obj] in [g['plac'][w['dragon']], g['fixd'][w['dragon']]]: move(cave, g, obj, k) g['loc'] = k k = w['null'] return {'fn':'motionVerb', 'goto':8, 'verb':k, 'kk':-1} def badMotion(g, w, k): # Non-applicable motion. Various messages depending on word given. spk = 12 # I DON'T KNOW HOW TO APPLY THAT WORD HERE. if 43 <= k <= 50: spk = 9 # THERE IS NO WAY TO GO THAT DIRECTION. elif k in [29, 30]: spk = 9 elif k in [7, 36, 37]: spk = 10 # USE COMPASS POINTS OR NEARBY OBJECTS. elif k in [11, 19]: spk = 11 # USE COMPASS POINTS OR NAME SOMETHING IN GENERAL DIRECTION # if verb in [w['find'], w['invent']]: # XXX BUG??? adven.f4 has verb, not k. elif k in [w['find'], w['invent']]: spk = 59 # I CANNOT TELL YOU WHERE REMOTE THINGS ARE. elif k in [62, 65]: spk = 42 # NOTHING HAPPENS. elif k == 17: spk = 80 # WHICH WAY? speak(g, spk, 'r') return {'fn':None} def blast(cave, g, w, spk): # BLAST. No effect unless you've got dynamite, which is a neat trick! if g['prop'][w['rod2']] < 0 or not cave['closed']: return {'fn':'newTurn', 'spk':spk} cave['bonus'] = 133 # Best: LOUD EXPLOSION...BURYING THE DWARVES if g['loc'] == 115: # NE storage room, site of explosion. cave['bonus'] = 134 # 2nd best: LOUD EXPLOSION...BURYING THE SNAKES if here(g,w['rod2']): # Explosive present, oh no. cave['bonus'] = 135 # 3rd best: YOU ARE SPLASHED ACROSS THE WALLS speak(g, cave['bonus'], 'r') finish(cave, g, w) def breakObj(cave, g, w, spk): # BREAK. Only works for mirror in repository and, of course, the vase. if g['obj'] == w['mirror']: spk = 148 # TOO FAR UP FOR YOU TO REACH. if not (g['obj'] == w['vase'] and g['prop'][w['vase']] == 0): if g['obj'] != w['mirror'] or not cave['closed']: return {'fn':'newTurn', 'spk':spk} speak(g, 197, 'r') # MIRROR SHATTERS INTO A MYRIAD TINY FRAGMENTS. dwarvesDisturbed(cave, g, w) spk = 198 # VASE HURLED DELICATELY TO THE GROUND. if toting(g,w['vase']): drop(cave, g, w['vase'], g['loc']) g['prop'][w['vase']] = 2 # Shattered. g['fixed'][w['vase']] = -1 # Gone. return {'fn':'newTurn', 'spk':spk} def brief(cave): # BRIEF. Intransitive only. Suppress long descriptions after first # time. spk = 156 # I'LL ONLY DESCRIBE A PLACE IN FULL THE FIRST TIME cave['abbnum'] = 10000 cave['detail'] = 3 return {'fn':'newTurn', 'spk':spk} def bug(num): ''' The following conditions are currently considered fatal bugs. Numbers < 20 are detected while reading the database; the others occur at "run time". 0 Message line > 70 characters 1 Null line in message 2 Too many words of messages 3 Too many travel options 4 Too many vocabulary words 5 Required vocabulary word not found 6 Too many rtext or mtext messages 7 Too many hints 8 Location has cond bit being set twice 9 Invalid section number in database 20 Special travel (500>l>300) exceeds goto list 21 Ran off end of vocabulary table 22 Vocabulary type (n/1000) not between 0 and 3 23 Intransitive action verb exceeds goto list 24 Transitive action verb exceeds goto list 25 Conditional travel entry with no alternative 26 Location has no travel entries 27 Hint number exceeds goto list 28 Invalid month returned by date function ''' print(' FATAL ERROR, SEE SOURCE CODE FOR INTERPRETATION.') print(' PROBABLE CAUSE: ERRONEOUS INFO IN DATABASE.') print(' ERROR CODE =%2d\n' % num) sys.exit(0) def carry(cave, g, obj, where): ''' Start toting an object, removing it from the list of things at its former location. Incr holdng unless it was already being toted. If obj>100 (moving "fixed" second loc), don't change place or holdng. ''' if obj <= 100: # Not a fixed object. if g['place'][obj] == -1: # Object not any place, so currently toted. return g['place'][obj] = -1 # Remove from current location. cave['holdng'] += 1 # Increment inventory count. if g['atloc'][where] == obj: # Object is here. g['atloc'][where] = g['link'][obj] return temp = g['atloc'][where] # First object at location. while True: if g['link'][temp] == 0: # Added by mm during python debugging. print(' %s NOT HERE. CAVE OUT OF ORDER, QUITTING!' % objName(g, obj)) sys.exit(1) if g['link'][temp] == obj: # Found it! break temp = g['link'][temp] # Index of next object at location. g['link'][temp] = g['link'][obj] def caveMsg(g): # CAVE. Different messages depending on whether above ground. if g['loc'] < 8: speak(g, 57, 'r') # I DON'T KNOW WHERE THE CAVE IS, TRY THE STREAM. else: speak(g, 58, 'r') # I NEED MORE DETAILED INSTRUCTIONS TO DO THAT. def ciao(cave, g, w): ''' Exits, after issuing reminder to save new core image. Used when suspending and when creating new version via magic mode. On some systems, the core image is lost once the program exits. If so, set k=31 instead of 32. -- The above is of course no longer applicable, but let's print it for old times' sake. (mm, Oct 2024) ''' k = 32 speak(g, k, 'm') # BE SURE TO SAVE YOUR CORE-IMAGE... if k == 31: a,b = getin(cave, g, w) sys.exit(0) # # C a v e C l o s i n g a n d S c o r i n g # # closeClock1 & closeClock2 ''' These sections handle the closing of the cave. The cave closes "clock1" turns after the last treasure has been located (including the pirate's chest, which may of course never show up). Note that the treasures need not have been taken yet, just located. Hence clock1 must be large enough to get out of the cave (it only ticks while inside the cave). When it hits zero, we branch to 10000 to start closing the cave, and then sit back and wait for him to try to get out. If he doesn't within clock2 turns, we close the cave; if he does try, we assume he panics, and give him a few additional turns to get frantic before we close. When clock2 hits zero, we branch to 11000 to transport him into the final puzzle. Note that the puzzle depends upon all sorts of random things. For instance, there must be no water or oil, since there are beanstalks which we don't want to be able to water, since the code can't handle it. Also, we can have no keys, since there is a grate (having moved the fixed object!) there separating him from all the treasures. Most of these problems arise from the use of negative prop numbers to suppress the object descriptions until he's actually moved the objects. When the first warning comes, we lock the grate, destroy the bridge, kill all the dwarves (and the pirate), remove the troll and bear (unless dead), and set "closng" to true. Leave the dragon; too much trouble to move it. From now until clock2 runs out, he cannot unlock the grate, move to any location outside the cave (loc<9), or create the bridge. Nor can he be resurrected if he dies. Note that the snake is already gone, since he got to the treasure accessible only via the hall of the Mt. King. Also, he's been in giant room (to get eggs), so we can refer to it. Also also, he's gotten the pearl, so we know the bivalve is an oyster. *And*, the dwarves must have been activated, since we've found chest. ''' def closeClock1(cave, g, w, wizcom, wd1, wd2): # Line 10000 g['prop'][w['grate']] = 0 # Lock the grate. g['prop'][w['fissur']] = 0 # Destroy the bridge. for i in range(1, 6+1): g['dseen'][i] = False g['dloc'][i] = 0 # Kill each dwarf or pirate. move(cave, g, w['troll'], 0) # Remove troll. move(cave, g, w['troll']+100, 0) move(cave, g, w['troll2'], g['plac'][w['troll']]) move(cave, g, w['troll2']+100, g['fixd'][w['troll']]) juggle(cave, g, w['chasm']) if g['prop'][w['bear']] != 3: # ==3, already dead. dstroy(cave, g, w['bear']) # Remove bear. g['prop'][w['chain']] = 0 # Lock chain. g['fixed'][w['chain']] = 0 g['prop'][w['axe']] = 0 # Take axe. g['fixed'][w['axe']] = 0 speak(g, 129, 'r') # "ALL ADVENTURERS EXIT IMMEDIATELY THROUGH MAIN OFFICE." cave['clock1'] = -1 cave['closng'] = True return parseWords(cave, g, w, wizcom, wd1, wd2) def closeClock2(cave, g, w): ''' Once he's panicked, and clock2 has run out, we come here to set up the storage room. The room has two locs, hardwired as 115 (NE) and 116 (SW). At the NE end, we place empty bottles, a nursery of plants, a bed of oysters, a pile of lamps, rods with stars, sleeping dwarves, and him. At the SW end we place grate over treasures, snake pit, covey of caged birds, more rods, and pillows. A mirror stretches across one wall. Many of the objects come from known locations and/or states (E.g. the snake is known to have been destroyed and needn't be carried away from its old "place"), making the various objects be handled differently. We also drop all other objects he might be carrying (lest he have some which could cause trouble, such as the keys). We describe the flash of light and trundle back. ''' g['prop'][w['bottle']] = put(cave, g, w['bottle'],115,1) g['prop'][w['plant']] = put(cave, g, w['plant'],115,0) g['prop'][w['oyster']] = put(cave, g, w['oyster'],115,0) g['prop'][w['lamp']] = put(cave, g, w['lamp'],115,0) g['prop'][w['rod']] = put(cave, g, w['rod'],115,0) g['prop'][w['dwarf']] = put(cave, g, w['dwarf'],115,0) g['loc'] = 115 g['oldloc'] = 115 g['newloc'] = 115 # Leave the grate with normal (non-negative) property. foo = put(cave, g, w['grate'],116,0) g['prop'][w['snake']] = put(cave, g, w['snake'],116,1) g['prop'][w['bird']] = put(cave, g, w['bird'],116,1) g['prop'][w['cage']] = put(cave, g, w['cage'],116,0) g['prop'][w['rod2']] = put(cave, g, w['rod2'],116,0) g['prop'][w['pillow']] = put(cave, g, w['pillow'],116,0) g['prop'][w['mirror']] = put(cave, g, w['mirror'],115,0) g['fixed'][w['mirror']] = 116 for i in range(1, 100+1): if toting(g,i): dstroy(cave, g, i) # Remove anything he's carrying. speak(g, 132, 'r') # BLINDING FLASH OF LIGHT... cave['closed'] = True return {'fn':None} def closeDemo(cave, g, w): # And, of course, demo games are ended by the wizard. # Line 13000 speak(g, 1, 'm') # A LARGE CLOUD OF GREEN SMOKE APPEARS... cave['gaveup'] = True finish(cave, g, w) def dark(g, w): if g['cond'][g['loc']] & 1: # Light bit set, not dark. return False if not here(g, w['lamp']): # No lamp here, must be dark. return True return g['prop'][w['lamp']] == 0 # Light/dark when lamp on/off. def datime(): ''' Return the date and time in d and t. d is number of days since 01-jan-77, t is minutes past midnight. This is harder than it sounds, because the finagled dec functions return the values only as ascii strings! ''' t0 = datetime.date(1977,1,1) # 1 Jan 1977 is a Saturday. today = datetime.date.today() d = (today - t0).days now = time.localtime() t = 60*now.tm_hour + now.tm_min # Minutes since midnight. return d, t def dbRead(g): # Description of the database format # # # The data file contains several sections. Each begins with a line # containing a number identifying the section, and ends with a line # containing "-1". # # Section 1: Long form descriptions. Each line contains a location number, # a tab, and a line of text. The set of (necessarily adjacent) lines # whose numbers are x form the long description of location x. # Section 2: Short form descriptions. Same format as long form. Not all # places have short descriptions. # Section 3: Travel table. Each line contains a location number (x), # a second location number (y), and a list of motion numbers (see # section 4). Each motion represents a verb which will go to y if # currently at x. Y, in turn, is interpreted as follows. Let m = # y/1000, n = y mod 1000. # if n<=300 it is the location to go to. # if 300500 message n-500 from section 6 is printed, # and he stays wherever he is. # Meanwhile, m specifies the conditions on the motion. # if m = 0 it's unconditional. # if 0$<". # Section 6: Arbitrary messages. Same format as sections 1, 2, and 5, # except the numbers bear no relation to anything (except for special # verbs in section 4). # Section 7: Object locations. Each line contains an object number and its # initial location (zero (or omitted) if none). If the object is # immovable, the location is followed by a "-1". If it has two locations # (e.g. the grate) the first location is followed with the second, and # the object is assumed to be immovable. # Section 8: Action defaults. Each line contains an "action-verb" number # and the index (in section 6) of the default message for the verb. # Section 9: Liquid assets, etc. Each line contains a number (n) and up to # 20 location numbers. Bit n (where 0 is the units bit) is set in # cond[loc] for each loc given. The cond bits currently assigned # are: # 0 Light # 1 If bit 2 is on: on for oil, off for water # 2 Liquid asset, see bit 1 # 3 Pirate doesn't go here unless following player # Other bits are used to indicate areas of interest to "hint" routines: # 4 Trying to get into cave # 5 Trying to catch bird # 6 Trying to deal with snake # 7 Lost in maze # 8 Pondering dark room # 9 At Witt's End # Cond[loc] is set to 2, overriding all other bits, if loc has forced # motion. # Section 10: Class messages. Each line contains a number (n), a tab, and a # message describing a classification of player. The scoring section # selects the appropriate message, where each message is considered to # apply to players whose scores are higher than the previous n but not # higher than this n. Note that these scores probably change with every # modification (and particularly expansion) of the program. # Section 11: Hints. Each line contains a hint number (corresponding to a # cond bit, see section 9), the number of turns he must be at the right # loc(s) before triggering the hint, the points deducted for taking the # hint, the message number (section 6) of the question, and the message # number of the hint. These values are stashed in the "hints" array. # Hntmax is set to the max hint number (<= hntsiz). Numbers 1-3 are # unusable since cond bits are otherwise assigned, so 2 is used to # remember if he's read the clue in the repository, and 3 is used to # remember whether he asked for instructions (gets more turns, but loses # points). # Section 12: Magic messages. Identical to section 6 except put in a # separate section for easier reference. Magic messages are used by # the startup, maintenance mode, and related routines. # Section 0: End of database. # Read the database if we have not yet done so if g['setup'] != 0: # Only for old days of computing. cave, w, wizcom = postDbInit(g) else: # print('INITIALISING...') # Clear out the various text-pointer arrays. All text is stored in # array lines; each line is preceded by a word pointing to the next # pointer (i.e. the word following the end of the line). The # pointer is negative if this is first line of a message. The # text-pointer arrays contain indices of pointer-words in lines. # Stext(n) is short description of location n. Ltext(n) is long # description. Ptext(n) points to message for prop(n) = 0. # Successive prop messages are found by chasing pointers. Rtext # contains section 6's stuff. Ctext(n) points to a player-class # message. Mtext is for section 12. We also clear cond. See # description of section 9 for details. db = open('text', 'r') while True: # Start new data section. Sect is the section number. line = db.readline().strip() sect = int(line) match sect: case 0: return postDbInit(g) case 1: sections(db, g, 1) case 2: sections(db, g, 2) case 3: section3(db, g) case 4: section4(db, g) case 5: section5(db, g) case 6: sections(db, g, 6) case 7: section7(db, g) case 8: section8(db, g) case 9: section9(db, g) case 10: sections(db, g, 10) case 11: section11(db, g) case 12: sections(db, g, 12) case _: bug(9) # Invalid section number in database. db.close() # print('INIT DONE ') def dead(cave, g, w, pit=True): ''' "You're dead, Jim." If the current loc is zero, it means the clown got himself killed. We'll allow this maxdie times. Maxdie is automatically set based on the number of snide messages available. Each death results in a message (81, 83, etc.) which offers reincarnation; if accepted, this results in message 82, 84, etc. The last time, if he wants another chance, he gets a snide remark as we exit. When reincarnated, all objects being carried get dropped at oldlc2 (presumably the last place prior to being killed) without change of props. The loop runs backwards to assure that the bird is dropped before the cage. (This kluge could be changed once we're sure all references to bird and cage are done by keywords.) The lamp is a special case (it wouldn't do to leave it in the cave). It is turned off and left outside the building (only if he was carrying it, of course). He himself is left inside the building (and heaven help him if he tries to XYZZY back into the cave without the lamp!). Oldloc is zapped so he can't just "retreat". ''' # The easiest way to get killed is to fall into a pit in pitch darkness. if pit: speak(g, 23, 'r') # YOU BROKE EVERY BONE IN YOUR BODY! g['oldlc2'] = g['loc'] # Okay, he's dead. Let's get on with it. if cave['closng']: # He died during closing time. No resurrection. Tally up a death # and exit. speak(g, 131, 'r') # IT LOOKS AS THOUGH YOU'RE DEAD...CALL IT A DAY. cave['numdie'] += 1 finish(cave, g, w) yea = yes(cave, g, w,81+cave['numdie']*2, 82+cave['numdie']*2, 54, 'r') # REINCARNATE? cave['numdie'] += 1 if cave['numdie'] == cave['maxdie'] or not yea: finish(cave, g, w) g['place'][w['water']] = 0 g['place'][w['oil']] = 0 if toting(g,w['lamp']): g['prop'][w['lamp']] = 0 for j in range(1, 100+1): i = 101 - j if not toting(g,i): continue k = g['oldlc2'] if i == w['lamp']: k = 1 drop(cave, g, i, k) g['loc'] = 3 # Resurrected, back to the building! g['oldloc'] = g['loc'] return location(cave, g, w) # Back to top of game loop. def discard(cave, g, w, spk, goto9021=False): # Discard object. "Throw" also comes here for most objects. Special # cases for bird (might attack snake or dragon) and cage (might contain # bird) and vase. Drop coins at vending machine for extra batteries. # # Also: DROP,RELEA,FREE,DISCA,DUMP. if not goto9021: # Line 9020 if (toting(g,w['rod2']) and g['obj'] == w['rod'] and not toting(g,w['rod'])): g['obj'] = w['rod2'] # rod2 is in Storage Area, SW end. if not toting(g,g['obj']): return {'fn':'newTurn', 'spk':spk} if g['obj'] == w['bird'] and here(g,w['snake']): speak(g, 30, 'r') # LITTLE BIRD ATTACKS THE GREEN SNAKE... if cave['closed']: dwarvesDisturbed(cave, g, w) dstroy(cave, g, w['snake']) # Set prop for use by travel options g['prop'][w['snake']] = 1 # Snake run off by bird. skipTop = False else: skipTop = True while True: if not skipTop or goto9021: k = liq(g, w) # Line 9021 if k == g['obj']: g['obj'] = w['bottle'] if g['obj'] == w['bottle'] and k != 0: g['place'][k] = 0 if g['obj'] == w['cage'] and g['prop'][w['bird']] != 0: drop(cave, g, w['bird'],g['loc']) # Set bird free. if g['obj'] == w['bird']: g['prop'][w['bird']] = 0 drop(cave, g, g['obj'],g['loc']) return {'fn':'newTurn', 'spk':0} skipTop = False if g['obj'] == w['coins'] and here(g,w['vend']): dstroy(cave, g, w['coins']) # Take his money. drop(cave, g, w['batter'], g['loc']) # Fresh batteries for payment. speak(g, w['batter'], 'p', propMsg=0) # FRESH BATTERIES HERE. return {'fn':'newTurn', 'spk':0} elif (g['obj'] == w['bird'] and at(g,w['dragon']) and g['prop'][w['dragon']] == 0): # Bird and living dragon. speak(g, 154, 'r') # BIRD ATTACKS DRAGON, BURNT TO A CINDER. dstroy(cave, g, w['bird']) g['prop'][w['bird']] = 0 # Dead bird. if g['place'][w['snake']] == g['plac'][w['snake']]: g['tally2'] += 1 # Cannot find bird again. return {'fn':'newTurn', 'spk':0} elif g['obj'] == w['bear'] and at(g,w['troll']): speak(g, 163, 'r') # TROLL SCURRIES AWAY. move(cave, g, w['troll'], 0) move(cave, g, w['troll']+100, 0) move(cave, g, w['troll2'], g['plac'][w['troll']]) move(cave, g, w['troll2']+100, g['fixd'][w['troll']]) juggle(cave, g, w['chasm']) g['prop'][w['troll']] = 2 elif (g['obj'] != w['vase'] or g['loc'] == g['plac'][w['pillow']]): speak(g, 54, 'r') # OK else: g['prop'][w['vase']] = 2 # VASE DROPS WITH A DELICATE CRASH. if at(g,w['pillow']): g['prop'][w['vase']] = 0 # VASE RESTING ON VELVET PILLOW. speak(g, w['vase'], 'p', propMsg=g['prop'][w['vase']]+1) if g['prop'][w['vase']] != 0: g['fixed'][w['vase']] = -1 # Vase destroyed. return {'fn':'newTurn', 'spk':0} def drink(g, w, wd1, spk): # DRINK. If no object, assume water and look for it here. If water is # in the bottle, drink that, else must be at a water loc, so drink # stream. # # spk is default message, i.e., spk == g['actspk'][g['verb']] speak(g, spk, 'r') # Print prompt. if (g['obj'] == 0 # No object specified and liqloc(g, w) != w['water'] # and no water here and (liq(g, w) != w['water'] # and (no water in bottle or not here(g,w['bottle']))): # or no bottle here) return what(g, wd1) if g['obj'] != 0 and g['obj'] != w['water']: # obj not water. spk = 110 # DON'T BE RIDICULOUS! if spk == 110 or liq(g, w) != w['water'] or not here(g,w['bottle']): return {'fn':'newTurn', 'spk':spk} g['prop'][w['bottle']] = 1 # Bottle empty. g['place'][w['water']] = 0 # No water here. spk = 74 # THE BOTTLE OF WATER IS NOW EMPTY. return {'fn':'newTurn', 'spk':spk} def drop(cave, g, obj, where): ''' Place an object at a given loc, prefixing it onto the atloc list. Decr holdng if the object was being toted. ''' if obj <= 100: # Object numbers are < 100. if g['place'][obj] == -1: # Not in any room, must be toting it. cave['holdng'] -= 1 # Toting one less object. g['place'][obj] = where # Place object at location 'where'. else: g['fixed'][obj-100] = where # Objects fixed in place. if where <= 0: return g['link'][obj] = g['atloc'][where] # Add to object list at location. g['atloc'][where] = obj # Object is not 1st seen at location. def dstroy(cave, g, obj): ''' Permanently eliminate "object" by moving to a non-existent location. ''' move(cave, g, obj, 0) def dwarfBlock(g): ''' See if a dwarf has seen him and has come from where he wants to go. If so, the dwarf's blocking his way. If coming from place forbidden to pirate (dwarves rooted in place) let him get out (and attacked). ''' for i in range(1, 5+1): # Check all 5 dwarves. if (g['odloc'][i] == g['newloc'] # If going to dwarf i's old location and g['dseen'][i]): # and player was seen by dwarf i. speak(g, 2, 'r') # DWARF WITH BIG KNIFE BLOCKS WAY. return g['loc'] # Can't leave loc, dwarf blocks way. return g['newloc'] # Able to go to newloc. def dwarvesDisturbed(cave, g, w): # Oh dear, he's disturbed the dwarves. speak(g, 136, 'r') # RUCKUS HAS AWAKENED THE DWARVES finish(cave, g, w) def dwarfMovement(cave, g, w): ''' Things are in full swing. Move each dwarf at random, except if he's seen us he sticks with us. Dwarves never go to locs <15. If wandering at random, they don't back up unless there's no alternative. If they don't have to move, they attack. And, of course, dead dwarves don't do much of anything. ''' dtotal = 0 attack = 0 stick = 0 locs = 21*[0] # Store potential new dwarf locations. for i in range(1, 6+1): # Loop through all dwarves and pirate. if g['dloc'][i] == 0: # Dwarf i is dead. continue j = 1 kk = g['dloc'][i] # Location of living dwarf. kk = g['key'][kk] # travel[key[n]] first newloc from loc n if kk != 0: while True: # Potential new dwarf location. ndloc = abs(g['travel'][kk])//1000%1000 # Destination. if ((15 <= ndloc <= 300) # If in cave, and ndloc != g['odloc'][i] # not old place, and not (j > 1 and ndloc == locs[j-1]) # not duplicate, and j < 20 # not out of locs[], and ndloc != g['dloc'][i] # not current place, and not forced(g,ndloc) # not forced movt, and not (i == 6 and bitset(g,ndloc,3)) # pirate ok here, and abs(g['travel'][kk])//1000000 != 100): # dwarf ok here. locs[j] = ndloc # Save potential new dwarf loction. j += 1 # Count of ndloc's. kk += 1 # Next potential newloc in travel[]. if g['travel'][kk-1] < 0: # Last possible newloc. break locs[j] = g['odloc'][i] # Dwarf i's old location. if j >= 2: # Went into the if-block above. j -= 1 j = 1 + randint(j) # Pick from potential new locations. g['odloc'][i] = g['dloc'][i] # Age location. g['dloc'][i] = locs[j] # Move there! g['dseen'][i] = ( (g['dseen'][i] and g['loc'] >= 15) # Seen and >= Hall of Mists. or g['dloc'][i] == g['loc'] # Dwarf is here. or g['odloc'][i] == g['loc']) # Dwarf was just here. if not g['dseen'][i]: # Not seen by dwarf. continue g['dloc'][i] = g['loc'] if i == 6: # == pirate. pirateActions(cave, g, w) continue # This threatening little dwarf is in the room with him! dtotal += 1 if g['odloc'][i] != g['dloc'][i]: # Dwarves on the move don't attack. continue attack += 1 if g['knfloc'] >= 0: g['knfloc'] = g['loc'] # Put knife here. if 1000*random() < 95*(cave['dflag']-2): stick += 1 return attack,dtotal,stick def dwarfStartup(cave, g, w): ''' When we encounter the first dwarf, we kill 0, 1, or 2 of the 5 dwarves. If any of the survivors is at loc, replace him with the alternate. ''' if g['loc'] < 15 or pct(95): # 95% dwarf does not follow. return location(cave, g, w) cave['dflag'] = 2 # Dwarf is now following. for _ in range(1,2+1): # Kill up to 2 dwarves. j = 1 + randint(5) # Pick an unlucky dwarf. # If saved not = -1, he bypassed the "start" call. if pct(50) and cave['saved'] == -1: # Kill a dwarf? Flip a coin! g['dloc'][j] = 0 # Kill dwarf. for i in range(1, 5+1): # Check all 5 dwarves. if g['dloc'][i] == g['loc']: # If surviving dwarf is here, g['dloc'][i] = g['daltlc'] # move to Nugget Rm. g['odloc'][i] = g['dloc'][i] # Age dwarf location. speak(g, 3, 'r') # DWARF THREW AXE AT YOU AND MISSED. drop(cave, g, w['axe'], g['loc']) # Put dwarf's axe here. return location(cave, g, w) def eat(cave, g, w, wd1, spk, intransitive=True): # EAT. Intransitive: assume food if present, else ask what. # Transitive: food ok, some things lose appetite, rest are ridiculous. if intransitive: if not here(g,w['food']): return what(g, wd1) dstroy(cave, g, w['food']) spk = 72 # THANK YOU, IT WAS DELICIOUS! else: if g['obj'] == w['food']: dstroy(cave, g, w['food']) spk = 72 # THANK YOU, IT WAS DELICIOUS! elif g['obj'] in [w['bird'], w['snake'], w['clam'], w['oyster'], w['dwarf'], w['dragon'], w['troll'], w['bear']]: spk = 71 # I THINK I JUST LOST MY APPETITE. return {'fn':'newTurn', 'spk':spk} def feed(cave, g, w, spk): # FEED. If bird, no seed. Snake, dragon, troll: quip. If dwarf, make # him mad. Bear, special. if g['obj'] == w['bird']: spk = 100 # HAVE NO BIRD SEED. elif g['obj'] in [w['snake'], w['dragon'], w['troll']]: spk = 102 # NOTHING HERE IT WANTS TO EAT (EXCEPT PERHAPS YOU). if g['obj'] == w['dragon'] and g['prop'][w['dragon']] != 0: spk = 110 # DON'T BE RIDICULOUS! if g['obj'] == w['troll']: spk = 182 # GLUTTONY IS NOT ONE OF THE TROLL'S VICES. if (g['obj'] == w['snake'] and not cave['closed'] and here(g,w['bird'])): spk = 101 # SNAKE DEVOURED YOUR BIRD. dstroy(cave, g, w['bird']) # Remove bird. g['prop'][w['bird']] = 0 # Dead bird. g['tally2'] += 1 # Cannot find bird again. elif g['obj'] == w['dwarf']: if here(g,w['food']): spk = 103 # YOU FOOL, DWARVES EAT ONLY COAL! cave['dflag'] += 1 # Angrier! elif g['obj'] == w['bear']: if g['prop'][w['bear']] == 0: # Locked to chain. spk = 102 # NOTHING HERE IT WANTS TO EAT (EXCEPT PERHAPS YOU). if g['prop'][w['bear']] == 3: # Dead bear. spk = 110 # DON'T BE RIDICULOUS! if here(g,w['food']): dstroy(cave, g, w['food']) g['prop'][w['bear']] = 1 # Free and fed. g['fixed'][w['axe']] = 0 # Not attacked. g['prop'][w['axe']] = 0 spk = 168 # WOLFS DOWN FOOD, CALMS DOWN. return {'fn':'newTurn', 'spk':spk} else: spk = 14 # I'M GAME. WOULD YOU CARE TO EXPLAIN HOW? return {'fn':'newTurn', 'spk':spk} def feeFie(cave, g, w, wd1): # FEE FIE FOE FOO (and FUM). Advance to next state if given in proper # order. Look up wd1 in section 3 of vocab to determine which word we've # got. Last word zips the eggs back to the Giant Room (unless already # there). k = vocab(g, wd1, 3) # FEE -> k==3001%1000==1, etc. spk = 42 # NOTHING HAPPENS. if cave['foobar'] != 1 - k: if cave['foobar'] != 0: spk = 151 # CAN'T YOU READ? NOW YOU'D BEST START OVER. return {'fn':'newTurn', 'spk':spk} cave['foobar'] = k # Track progress (word num) saying FEE FIE FOE FOO. if k != 4: return {'fn':'newTurn', 'spk':54} # newTurn() cave['foobar'] = 0 if (g['place'][w['eggs']] == g['plac'][w['eggs']] # cur loc == orig loc. or (toting(g,w['eggs']) and g['loc'] == g['plac'][w['eggs']])): return {'fn':'newTurn', 'spk':spk} # Bring back troll if we steal the eggs back from him before crossing. if (g['place'][w['eggs']] == 0 and g['place'][w['troll']] == 0 and g['prop'][w['troll']] == 0): g['prop'][w['troll']] = 1 # Troll is back. k = 2 # DONE! Default message. if here(g,w['eggs']): # If eggs here, take them. k = 1 # NEST OF GOLDEN EGGS VANISHED! if g['loc'] == g['plac'][w['eggs']]: # In Giant Room, bring eggs back. k = 0 # LARGE NEST HERE, FULL OF GOLDEN EGGS! move(cave, g, w['eggs'], g['plac'][w['eggs']]) # Zip eggs to Giant Room. speak(g, w['eggs'], 'p', propMsg=k) return {'fn':'newTurn', 'spk':0} def fill(cave, g, w, wd1, spk): # FILL. Bottle must be empty, and some liquid available. (Vase is nasty.) if g['obj'] != w['vase']: if g['obj'] != 0 and g['obj'] != w['bottle']: return {'fn':'newTurn', 'spk':spk} if g['obj'] == 0 and not here(g,w['bottle']): return what(g, wd1) spk = 107 # YOUR BOTTLE IS NOW FULL OF WATER. if liqloc(g, w) == 0: spk = 106 # THERE IS NOTHING HERE WITH WHICH TO FILL THE BOTTLE. if liq(g, w) != 0: spk = 105 # YOUR BOTTLE IS ALREADY FULL. if spk != 107: return {'fn':'newTurn', 'spk':spk} g['prop'][w['bottle']] = g['cond'][g['loc']]%4//2*2 k = liq(g, w) if toting(g,w['bottle']): g['place'][k] = -1 if k == w['oil']: spk = 108 # YOUR BOTTLE IS NOW FULL OF OIL. return {'fn':'newTurn', 'spk':spk} spk = 29 # YOU AREN'T CARRYING IT! if liqloc(g, w) == 0: spk = 144 # THERE IS NOTHING HERE WITH WHICH TO FILL THE VASE. if liqloc(g, w) == 0 or not toting(g,w['vase']): return {'fn':'newTurn', 'spk':spk} speak(g, 145, 'r') # TEMPERATURE HAS DELICATELY SHATTERED THE VASE. g['prop'][w['vase']] = 2 g['fixed'][w['vase']] = -1 return discard(cave, g, w, spk, goto9021=True) def find(cave, g, w, spk, k): # FIND. Might be carrying it, or it might be here. Else give caveat. if (at(g,g['obj']) or (liq(g, w) == g['obj'] and at(g,w['bottle'])) or k == liqloc(g, w)): spk = 94 # I BELIEVE WHAT YOU WANT IS RIGHT HERE WITH YOU. for i in range(1, 5+1): if (g['dloc'][i] == g['loc'] and cave['dflag'] >= 2 and g['obj'] == w['dwarf']): spk = 94 # I BELIEVE WHAT YOU WANT IS RIGHT HERE WITH YOU. if cave['closed']: spk = 138 # I DARESAY WHATEVER YOU WANT IS AROUND HERE SOMEWHERE. if toting(g,g['obj']): spk = 24 # YOU ARE ALREADY CARRYING IT! return {'fn':'newTurn', 'spk':spk} def finish(cave, g, w, scorng=False): # Exit code. # The present scoring algorithm is as follows: # Objective: Points: Present Total Possible: # Getting well into cave 25 25 # Each treasure < chest 12 60 # Treasure chest itself 14 14 # Each treasure > chest 16 144 # Surviving (max-num)*10 30 # Not quitting 4 4 # Reaching "closng" 25 25 # "Closed": Quit/killed 10 # Klutzed 25 # Wrong way 30 # Success 45 45 # Came to Witt's End 1 1 # Round out the total 2 2 # Total: 350 # (Points can also be deducted for using hints.) score = 0 mxscor = 0 # First tally up the treasures. Must be in building and not broken. # Give the poor guy 2 points just for finding each treasure. for i in range(50, g['maxtrs']+1): if g['ptext'][i] == 0: continue k = 12 # Easily found treasures. if i == w['chest']: # Treasure chest. k = 14 if i > w['chest']: # Hard to find treasures. k = 16 if g['prop'][i] >= 0: # Free 2 pts. Treasure found, maybe not in bldg. score += 2 if g['place'][i] == 3 and g['prop'][i] == 0: # In bldg & not broken. score += k - 2 # In bldg, so take back free 2 points. mxscor += k # Now look at how he finished and how far he got. Maxdie and numdie tell # us how well he survived. Gaveup says whether he exited via quit. # Dflag will tell us if he ever got suitably deep into the cave. Closng # still indicates whether he reached the endgame. And if he got as far # as "cave closed" (indicated by "closed"), then bonus is zero for # mundane exits or 133, 134, 135 if he blew it (so to speak). score += (cave['maxdie'] - cave['numdie'])*10 mxscor += cave['maxdie']*10 if not (scorng or cave['gaveup']): score += 4 mxscor += 4 if cave['dflag'] != 0: score += 25 mxscor += 25 if cave['closng']: score += 25 mxscor += 25 if cave['closed']: if cave['bonus'] == 0: score += 10 if cave['bonus'] == 135: score += 25 if cave['bonus'] == 134: score += 30 if cave['bonus'] == 133: score += 45 mxscor += 45 # Did he come to Witt's End as he should? if g['place'][w['magzin']] == 108: # 108 is Witt's End. score += 1 mxscor += 1 # Round it off. score += 2 mxscor += 2 # Deduct points for hints. Hints < 4 are special; see database description. for i in range(1, g['hntmax']+1): if g['hinted'][i]: score -= g['hints'][i][2] # Return to score command if that's where we came from. if scorng: return score,mxscor # That should be good enough. Let's tell him all about it. print('\n\n\n YOU SCORED%4d OUT OF A POSSIBLE%4d USING%5d TURNS.' % (score,mxscor,cave['turns'])) for i in range(1, g['clsses']+1): if g['cval'][i] >= score: break else: print('\n YOU JUST WENT OFF MY SCALE!!\n') sys.exit(0) speak(g, g['ctext'][i]) if i == g['clsses']-1: print('\n TO ACHIEVE THE NEXT HIGHER RATING ', 'WOULD BE A NEAT TRICK!\n\n CONGRATULATIONS!!\n') else: k = g['cval'][i] + 1-score kk = 'S.' if k == 1: kk = '. ' print('\n TO ACHIEVE THE NEXT HIGHER RATING, ' 'YOU NEED%3d MORE POINT%2s\n' % (k,kk)) sys.exit(0) def gameState(): g = { 'lines' :[''], # Ensure first real line is at index 1, like Fortran. 'linuse':0, 'linbytes':0, 'travel':751*[0], 'ktab' :301*[0], # Definitions (ints) of atab words, Sec 4. 'atab' :301*[''], # 5-letter words, Sec 4. 'ltext' :151*[0], # Long form descriptions of locations, Sec 1. 'stext' :151*[0], # Short form descriptions of locations, Sec 2. 'key' :151*[0], # Index into travel[], with newloc routes, Sec 3. 'cond' :151*[0], # Liquid and other conditions at each loc, Sec 9. 'abb' :151*[0], # >0, use abbreviated description at loc. 'atloc' :151*[0], # First object at location i. 'plac' :101*[0], # plac[i] is initial loc of obj i, Sec 7. 'place' :101*[0], # place[i] is current location of object i. 'fixd' :101*[0], # if 0/-1, obj plac[i] is movable/immovable, Sec 7. 'fixed' :101*[0], 'link' :201*[0], 'ptext' :101*[0], # Property text. 'prop' :101*[0], # Print ptext[n] message for prop[n]. 'actspk': 36*[0], # Default message for an action. 'rtext' :206*[0], # Random messages. 'ctext' : 13*[0], # Player classification messages. 'cval' : 13*[0], # Class point threshold. 'hintlc': 21*[0], 'hinted': 21*[False], 'hints' : [[0 for c in range(5)] for r in range(21)], # 21x5. 'mtext' : 36*[0], # Magic text. 'dseen' : 7*[False], 'dloc' : 7*[0], # Dwarf/pirate current locations. 'odloc' : 7*[0], # Dwarf/pirate previous locations. 'linsiz':9650, 'trvsiz': 750, 'tabsiz': 300, 'locsiz': 150, 'vrbsiz': 35, 'rtxsiz': 205, 'clsmax': 12, 'hntsiz': 20, 'magsiz': 35, 'setup': 0, 'blklin':True, 'clsses':1, 'knfloc':-1, 'loc':-1, 'newloc':-1, 'oldloc':-1, 'oldlc2':-1, 'trvs':1, 'obj':0, 'verb':0 } return g def getHint(cave, g, w, hint): ''' Hints Come here if he's been long enough at required loc(s) for some unused hint. Hint number is in variable "hint". Branch to quick test for additional conditions, then come back to do neat stuff. Goto 40010 if conditions are met and we want to offer the hint. Goto 40020 to clear hintlc back to zero, 40030 to take no action yet. ''' # Now for the quick tests. See database description for one-line notes. match hint: case 4: # Cave if g['prop'][w['grate']] != 0 or here(g,w['keys']): g['hintlc'][hint] = 0 return case 5: # Bird if not (here(g,w['bird']) and toting(g,w['rod']) and g['oldobj'] == w['bird']): return case 6: # Snake if not here(g,w['snake']) or here(g,w['bird']): g['hintlc'][hint] = 0 return case 7: # Maze if (g['atloc'][g['loc']] != 0 or g['atloc'][g['oldloc']] != 0 or g['atloc'][g['oldlc2']] != 0 or cave['holdng'] <= 1): g['hintlc'][hint] = 0 return case 8: # Dark if g['prop'][w['emrald']] == -1 or g['prop'][w['pyram']] != -1: g['hintlc'][hint] = 0 return case 9: # Witt pass case _: bug(27) # Hint number exceeds goto list. g['hintlc'][hint] = 0 if not yes(cave, g, w,g['hints'][hint][3],0,54,'r'): return print('\n I AM PREPARED TO GIVE YOU A HINT, BUT IT WILL COST YOU', '%2d POINTS.' % g['hints'][hint][2]) g['hinted'][hint] = yes( cave, g, w, 175, g['hints'][hint][4], 54, 'r') # WANT THE HINT? if g['hinted'][hint] and g['limit'] > 30: g['limit'] += 30*g['hints'][hint][2] g['hintlc'][hint] = 0 def getin(cave, g, w): ''' Get a command from the adventurer. Snarf out the first word and return it in word1. Any number of blanks may follow the word. If a second word appears, it is returned in word2, else word2 is set to null string. ''' warn = '\n PLEASE STICK TO 1- AND 2-WORD COMMANDS.\n' word2 = '' while True: wd = inputCheck(cave, g, w).upper().split() n = len(wd) if n > 2: print(warn); continue if n == 2: word2 = wd[1] if n >= 1: word1 = wd[0]; break return word1, word2 def goBack(g, kk): # Handle "GO BACK". Look for verb which goes from loc to oldloc, or to # oldlc2 if oldloc has forced-motion. K2 saves entry -> forced loc -> # previous loc. # Line 20 k = g['oldloc'] if forced(g,k): k = g['oldlc2'] g['oldlc2'] = g['oldloc'] g['oldloc'] = g['loc'] k2 = 0 if k == g['loc']: speak(g, 91, 'r') # I NO LONGER REMEMBER HOW YOU GOT HERE. return {'fn':None} while True: ll = (abs(g['travel'][kk])//1000)%1000 if ll == k: k = abs(g['travel'][kk])%1000 kk = g['key'][g['loc']] return {'fn':'motionVerb', 'goto':9, 'verb':k, 'kk':kk} if ll <= 300: j = g['key'][ll] if forced(g,ll) and (abs(g['travel'][j])//1000)%1000 == k: k2 = kk if g['travel'][kk] < 0: break kk += 1 kk = k2 if kk == 0: speak(g, 140, 'r') # YOU CAN'T GET THERE FROM HERE. return {'fn':None} k = abs(g['travel'][kk])%1000 kk = g['key'][g['loc']] return {'fn':'motionVerb', 'goto':9, 'verb':k, 'kk':-1} def hours(wizcom): # Announce the current hours when the cave is open for adventuring. This info # is stored in wkday, wkend, and holid, where bit shift(1,n) is on iff the # hour from n:00 to n:59 is "prime time" (cave closed). Wkday is for # weekdays, wkend for weekends, holid for holidays. Next holiday is from # hbegin to hend. print('') hoursx(wizcom['wkday'],'MON -',' FRI:') hoursx(wizcom['wkend'],'SAT -',' SUN:') hoursx(wizcom['holid'],'HOLID','AYS: ') d,t = datime() if wizcom['hend'] < d or wizcom['hend'] < wizcom['hbegin']: return if wizcom['hbegin'] <= d: print('\n TODAY IS A HOLIDAY, NAMELY %s' % wizcom['hname']) return d = wizcom['hbegin'] - d t = 'DAYS, ' if d == 1: t = 'DAY, ' print('\n THE NEXT HOLIDAY WILL BE IN%3d %5s NAMELY %s' % (d,t,wizcom['hname'])) def hoursShow(g, wizcom): # HOURS. Report current non-prime-time hours. speak(g, 6, 'm') # COLOSSAL CAVE IS OPEN AT THE FOLLOWING HOURS: hours(wizcom) return {'fn':'newTurn', 'spk':0} def hoursx(h,day1,day2): ''' Used by hours (above) to print hours for either weekdays or weekends. ''' first = True frm = -1 if h == 0: print(' %-5s%-5s OPEN ALL DAY' % (day1,day2)) return while True: frm = frm + 1 if (h & (1<= 24: break till = frm while True: till += 1 if not ((h & (1<". t = t[:t.rfind("'")] if t=='INT': t = 'INTEGER' print(' %s NEEDED.' % t.upper()) except EOFError: break except KeyboardInterrupt: break cave['gaveup'] = True quitGame(cave, g, w, verify=False) def intransitive(cave, g, w, wizcom, wd1, wd2, spk): # Analyse an intransitive verb (ie, no object given yet). # Line 4080 verb = g['verb'] match verb: case 1: return take(cave, g, w, wd1, spk=spk) # TAKE case 2: return what(g, wd1) # DROP case 3: return what(g, wd1) # SAY case 4: return locking(cave, g, w, wd1) # OPEN case 5: return newTurn(cave, g, w, wizcom, verb) # NOTH case 6: return locking(cave, g, w, wd1) # LOCK case 7: return lampOn(cave, g, w, spk) # ON case 8: return lampOff(g, w, spk) # OFF case 9: return what(g, wd1) # WAVE case 10: return what(g, wd1) # CALM case 11: return newTurn(cave,g,w,wizcom,verb,spk) # WALK case 12: return attack(cave,g,w,wizcom,spk,wd1,wd2) # KILL case 13: return pour(g, w, wd1, spk) # POUR case 14: return eat(cave, g, w, wd1,spk) # EAT case 15: return drink(g, w, wd1,spk) # DRNK case 16: return what(g, wd1) # RUB case 17: return what(g, wd1) # TOSS case 18: return quitGame(cave, g, w) # QUIT case 19: return what(g, wd1) # FIND case 20: return inventory(g, w) # INVN case 21: return what(g, wd1) # FEED case 22: return fill(cave, g, w, wd1, spk) # FILL case 23: return blast(cave, g, w, spk) # BLST case 24: return score(cave, g, w) # SCOR case 25: return feeFie(cave, g, w, wd1) # FOO case 26: return brief(cave) # BRF case 27: return read(cave, g, w, wd1,spk) # READ case 28: return what(g, wd1) # BREK case 29: return what(g, wd1) # WAKE case 30: return suspend(cave, g, w, wizcom) # SUSP case 31: return hoursShow(g, wizcom) # HOUR case 32: return suspend(cave, g, w, wizcom, restart=True) # RESUM case _: bug(23) # Intransitive action verb exceeds goto list. def inventory(g, w): # INVENTORY. If object, treat same as find. Else report on current # burden. spk = 98 for i in range(1, 100+1): if i == w['bear'] or not toting(g,i): continue if spk == 98: speak(g, 99, 'r') # YOU ARE CURRENTLY HOLDING THE FOLLOWING: g['blklin'] = False speak(g, i, 'p', propMsg=-1) g['blklin'] = True spk = 0 if toting(g,w['bear']): spk = 141 # YOU ARE BEING FOLLOWED BY A VERY LARGE, TAME BEAR. return {'fn':'newTurn', 'spk':spk} def juggle(cave, g, obj): ''' Juggle an object by picking it up and putting it down again, the purpose being to get the object to the front of the chain of things at its loc. ''' i = g['place'][obj] j = g['fixed'][obj] move(cave, g, obj, i) move(cave, g, obj+100, j) def lampNeedBatteries(cave, g, w, wizcom, wd1, wd2): # Line 12200 if cave['lmwarn'] or not here(g,w['lamp']): return parseWords(cave, g, w, wizcom, wd1, wd2) cave['lmwarn'] = True spk = 187 # GO BACK FOR THOSE BATTERIES. if g['place'][w['batter']] == 0: spk = 183 # START WRAPPING THIS UP...OR FIND SOME FRESH BATTERIES. if g['prop'][w['batter']] == 1: spk = 189 # OUT OF SPARE BATTERIES. speak(g, spk, 'r') return parseWords(cave, g, w, wizcom, wd1, wd2) def lampOff(g, w, spk): # Lamp off if not here(g,w['lamp']): return {'fn':'newTurn', 'spk':spk} g['prop'][w['lamp']] = 0 speak(g, 40, 'r') # YOUR LAMP IS NOW OFF. if dark(g, w): speak(g, 16, 'r') # IT IS NOW PITCH DARK. return {'fn':'newTurn', 'spk':0} def lampOn(cave, g, w, spk): # Light lamp if not here(g,w['lamp']): return {'fn':'newTurn', 'spk':spk} spk = 184 if g['limit'] < 0: return {'fn':'newTurn', 'spk':spk} g['prop'][w['lamp']] = 1 speak(g, 39, 'r') # YOUR LAMP IS NOW ON. if cave['wzdark']: return location(cave, g, w) return {'fn':'newTurn', 'spk':0} def lampOut(cave, g, w, wizcom, wd1, wd2): # Line 12400 g['limit'] = -1 g['prop'][w['lamp']] = 0 if here(g,w['lamp']): speak(g, 184, 'r') # YOUR LAMP HAS RUN OUT OF POWER. return parseWords(cave, g, w, wizcom, wd1, wd2) def lampOutQuit(cave, g, w): # Line 12600 speak(g, 185, 'r') # NOT MUCH POINT IN WANDERING AROUND WITHOUT A LAMP. cave['gaveup'] = True finish(cave, g, w) def lampRecharge(cave, g, w, wizcom, wd1, wd2): ''' Another way we can force an end to things is by having the lamp give out. When it gets close, we come here to warn him. We go to 12000 if the lamp and fresh batteries are here, in which case we replace the batteries and continue. 12200 is for other cases of lamp dying. 12400 is when it goes out, and 12600 is if he's wandered outside and the lamp is used up, in which case we force him to give up. ''' # Line 12000 speak(g, 188, 'r') # YOUR LAMP IS GETTING DIM...REPLACING BATTERIES. g['prop'][w['batter']] = 1 if toting(g,w['batter']): drop(cave, g, w['batter'],g['loc']) g['limit'] += 2500 cave['lmwarn'] = False return parseWords(cave, g, w, wizcom, wd1, wd2) def liq(g, w): '''What's in the bottle.''' c = g['prop'][w['bottle']] match max(c, -1-c): case 0: return w['water'] case 1: return 0 case 2: return w['oil'] def liqloc(g, w): # Liquid at this location. c = g['cond'][g['loc']] if c & 0b100 == 0: return 0 # No liquid. elif c & 0b010 == 0: return w['water'] else: return w['oil'] def location(cave, g, w): # Describe the current location and (maybe) get next command. # Print text for current loc. if g['loc'] == 0: return dead(cave, g, w, pit=False) # He's dead. kk = g['stext'][g['loc']] # Short form text describing loc. if g['abb'][g['loc']]%cave['abbnum'] == 0 or kk == 0: kk = g['ltext'][g['loc']] # Long form text describing loc. if not forced(g,g['loc']) and dark(g, w): if cave['wzdark'] and pct(35): # It was dark, 35% chance of dying. return dead(cave, g, w) kk = g['rtext'][16] # IT IS NOW PITCH DARK if toting(g,w['bear']): speak(g, 141, 'r') # FOLLOWED BY LARGE, TAME BEAR speak(g, kk) # Describe loc or say it's dark. k = 1 if forced(g,g['loc']): return {'fn':'motionVerb', 'goto':8, 'verb':k, 'kk':-1} if g['loc'] == 33 and pct(25) and not cave['closng']: # 1/4 chance at Y2. speak(g, 8, 'r') # HOLLOW VOICE SAYS "PLUGH" # Print out descriptions of objects at this location. If not closing and # property value is negative, tally off another treasure. Rug is special # case; once seen, its prop is 1 (dragon on it) till dragon is killed. # Similarly for chain; prop is initially 1 (locked to bear). These hacks # are because prop = 0 is needed to get full score. if dark(g, w): return {'fn':'newTurn', 'spk':0} g['abb'][g['loc']] += 1 # Count visits to loc before printing long text. i = g['atloc'][g['loc']] # First ibject at loc. while True: if i == 0: # No more items here. return {'fn':'newTurn', 'spk':0} obj = i if obj > 100: # Immovable object. obj -= 100 if obj == w['steps'] and toting(g,w['nugget']): i = g['link'][i] # Skip to next item. continue # Can't carry nugget up steps. if g['prop'][obj] < 0: # Not found till now. if cave['closed']: i = g['link'][i] continue g['prop'][obj] = 0 # Tag it as found. if obj == w['rug'] or obj == w['chain']: g['prop'][obj] = 1 # Rug w/dragon or chain w/bear. g['tally'] -= 1 # One less treasure to find. # If remaining treasures too elusive, zap his lamp. if g['tally'] == g['tally2'] != 0: g['limit'] = min(35, g['limit']) kk = g['prop'][obj] if obj == w['steps'] and g['loc'] == g['fixed'][w['steps']]: kk = 1 speak(g, obj, 'p', propMsg=kk) i = g['link'][i] def locName(g, loc, msg=-1): rm = g['lines'][g['stext'][loc]] # Short text. if rm == '': pos = g['ltext'][loc] # Long text. rm = g['lines'][pos] else: rm = rm[7:] return rm def locType(cave, g, w, k): if g['newloc'] <= 300: # Location to go to. return {'fn':None} elif g['newloc'] <= 500: # Special motion. return motionsSpecial(cave, g, w, k) else: # Don't move. speak(g, g['newloc']-500, 'r') g['newloc'] = g['loc'] return {'fn':None} def locking(cave, g, w, wd1, intransitive=True): # Lock, unlock, no object given. Assume various things if present. if intransitive: if here(g,w['clam']): g['obj'] = w['clam'] if here(g,w['oyster']): g['obj'] = w['oyster'] if at(g,w['door']): g['obj'] = w['door'] if at(g,w['grate']): g['obj'] = w['grate'] if g['obj'] != 0 and here(g,w['chain']): return what(g, wd1) if here(g,w['chain']): g['obj'] = w['chain'] if g['obj'] == 0: spk = 28 # THERE IS NOTHING HERE WITH A LOCK! return {'fn':'newTurn', 'spk':spk} # Lock, unlock object. Special stuff for opening clam/oyster and for # chain. spk = 33 # I DON'T KNOW HOW TO LOCK OR UNLOCK SUCH A THING. if g['obj'] == w['clam'] or g['obj'] == w['oyster']: # Clam/oyster. k = 0 if g['obj'] == w['oyster']: k = 1 spk = 124+k if toting(g,g['obj']): spk = 120+k # PUT DOWN CLAM/OYSTER BEFORE OPENING IT. if not toting(g,w['tridnt']): spk = 122+k # NOTHING STRONG ENOUGH TO OPEN CLAM/OYSTER. if g['verb'] == w['lock']: spk = 61 # WHAT? if spk != 124: # GLISTENING PEARL FALLS OUT OF CLAM AND ROLLS AWAY. return {'fn':'newTurn', 'spk':spk} dstroy(cave, g, w['clam']) drop(cave, g, w['oyster'],g['loc']) # Give it its proper name! drop(cave, g, w['pearl'],105) # Roll pearl to cul-de-sac, 2 rooms away. return {'fn':'newTurn', 'spk':spk} if g['obj'] == w['door']: spk = 111 # DOOR IS EXTREMELY RUSTY AND REFUSES TO OPEN. if g['obj'] == w['door'] and g['prop'][w['door']] == 1: spk = 54 # OK if g['obj'] == w['cage']: spk = 32 # IT HAS NO LOCK. if g['obj'] == w['keys']: spk = 55 # YOU CAN'T UNLOCK THE KEYS. if g['obj'] == w['grate'] or g['obj'] == w['chain']: spk = 31 # YOU HAVE NO KEYS! if spk != 31 or not here(g,w['keys']): return {'fn':'newTurn', 'spk':spk} if g['obj'] == w['chain']: # Chain. if g['verb'] == w['lock']: spk = 172 # THE CHAIN IS NOW LOCKED. if g['prop'][w['chain']] != 0: spk = 34 # IT WAS ALREADY LOCKED. if g['loc'] != g['plac'][w['chain']]: spk = 173 # NOTHING HERE TO WHICH THE CHAIN CAN BE LOCKED. if spk != 172: return {'fn':'newTurn', 'spk':spk} g['prop'][w['chain']] = 2 if toting(g,w['chain']): drop(cave, g, w['chain'],g['loc']) g['fixed'][w['chain']] = -1 return {'fn':'newTurn', 'spk':spk} spk = 171 # THE CHAIN IS NOW UNLOCKED. if g['prop'][w['bear']] == 0: spk = 41 # NO WAY TO GET PAST THE BEAR if g['prop'][w['chain']] == 0: spk = 37 # IT WAS ALREADY UNLOCKED. if spk != 171: # THE CHAIN IS NOW UNLOCKED. return {'fn':'newTurn', 'spk':spk} g['prop'][w['chain']] = 0 g['fixed'][w['chain']] = 0 if g['prop'][w['bear']] != 3: # ==3, dead bear. g['prop'][w['bear']] = 2 # Free. g['fixed'][w['bear']] = 2 - g['prop'][w['bear']] return {'fn':'newTurn', 'spk':spk} if not cave['closng']: k = 34 + g['prop'][w['grate']] # GRATE NOW LOCKED/WAS LOCKED. g['prop'][w['grate']] = 1 # Unlocked. if g['verb'] == w['lock']: g['prop'][w['grate']] = 0 # Locked. k += 2*g['prop'][w['grate']] return {'fn':'newTurn', 'spk':k} if not cave['panic']: cave['clock2'] = 15 cave['panic'] = True k = 130 # THIS EXIT IS CLOSED. return {'fn':'newTurn', 'spk':k} def lookAround(cave, g): # LOOK. Can't give more detail. Pretend it wasn't dark (though it may # "now" be dark) so he won't fall into a pit while staring into the # gloom. if cave['detail'] < 3: speak(g, 15, 'r') # I AM NOT ALLOWED TO GIVE MORE DETAIL. cave['detail'] += 1 # Bump counter, give detail every 5th visit. cave['wzdark'] = False # Pretend it isn't dark. g['abb'][g['loc']] = 0 # Turn off abbreviated description. def maint(cave, g, w, wizcom): ''' Someone said the magic word to invoke maintenance mode. Make sure he's a wizard. If so, let him tweak all sorts of random things, then exit so can save tweaked version. Since magic word must be first command given, only thing which needs to be fixed up is abb(1). ''' if not wizard(cave, g, w, wizcom): return g['blklin'] = False if yes(cave, g, w,10,0,0,'m'): # DO YOU WISH TO SEE THE HOURS? hours(wizcom) if yes(cave, g, w,11,0,0,'m'): # DO YOU WISH TO CHANGE THE HOURS? newhrs(cave, g, w, wizcom) if yes(cave, g, w,26,0,0,'m'): # WISH TO (RE)SCHEDULE THE NEXT HOLIDAY? speak(g, 27, 'm') # TO BEGIN HOW MANY DAYS FROM TODAY? wizcom['hbegin'] = inputCheck(cave, g, w, dtype=int) speak(g, 28, 'm') # TO LAST HOW MANY DAYS (ZERO IF NO HOLIDAY)? wizcom['hend'] = inputCheck(cave, g, w, dtype=int) d,t = datime() wizcom['hbegin'] += d wizcom['hend'] += wizcom['hbegin'] - 1 speak(g, 29, 'm') # TO BE CALLED WHAT (UP TO 20 CHARACTERS)? wizcom['hname'] = inputCheck(cave, g, w).upper() s = ' LENGTH OF SHORT GAME (NULL TO LEAVE AT%3d): ' % wizcom['short'] x = inputCheck(cave, g, w, s, dtype=int, emptyOk=True) if x > 0: wizcom['short'] = x speak(g, 12, 'm', nl=False) # NEW MAGIC WORD (NULL TO LEAVE UNCHANGED): x = inputCheck(cave, g, w, emptyOk=True) if x != '': wizcom['magic'] = x speak(g, 13, 'm', nl=False) # NEW MAGIC NUMBER (NULL TO LEAVE UNCHANGED): x = inputCheck(cave, g, w, dtype=int, emptyOk=True) if x > 0: wizcom['magnm'] = x s = ' LATENCY FOR RESTART (NULL TO LEAVE AT%3d): ' % wizcom['latncy'] x = inputCheck(cave, g, w, s, dtype=int, emptyOk=True) if 0 < x < 45: speak(g, 30, 'm') # TOO SMALL! ASSUMING MINIMUM VALUE (45 MINUTES). if x > 0: wizcom['latncy'] = max(45, x) if yes(cave, g, w,14,0,0,'m'): # CHANGE THE MESSAGE OF THE DAY? motd(cave, g, w, wizcom, True) cave['saved'] = 0 g['setup'] = 2 g['abb'][1] = 0 speak(g, 15, 'm') # OKAY. YOU CAN SAVE THIS VERSION NOW. g['blklin'] = True f = open('hours', 'w') for k in wizcom.keys(): print('%s %s' % (k, str(wizcom[k])), file=f) f.close() ciao(cave, g, w) def motd(cave, g, w, wizcom, alter): ''' Handles message of the day. If alter is true, read a new message from the wizard. Else print the current one. Message is initially null. ''' msg = '' if not alter: if wizcom['motd'] != '': print(' %s' % wizcom['motd']) return speak(g, 23, 'm') # LIMIT LINES TO 70 CHARS. END WITH NULL LINE. while True: try: line = inputCheck(cave, g, w, emptyOk=True).upper() except KeyboardInterrupt: cave['gaveup'] = True quitGame(cave, g, w, verify=False) if len(line) > 70: speak(g, 24, 'm') # LINE TOO LONG, RETYPE: continue if line == '': wizcom['motd'] = msg return if len(msg)+len(line) >= 100: # Limit motd to 100 chars. speak(g, 25, 'm') # NOT ENOUGH ROOM FOR ANOTHER LINE... wizcom['motd'] = msg return msg += line def motionsSpecial(cave, g, w, k): # Special motions come here. Labelling convention: statement # numbers nnnxx (xx = 00-99) are used for special case number # nnn (nnn = 301-500). match g['newloc']-300: # goto (30100,30200,30300)newloc case 1: # loc is either 99/alcove or 100/plover. # Travel 301. Plover-alcove passage. Can carry only emerald. # Note: travel table must include "useless" entries going through # passage, which can never be used for actual motion, but can be # spotted by "go back". # g['newloc'] = 99 + 100 - g['loc'] g['newloc'] = 99 if g['loc']==100 else 100 # Go to other end. if (cave['holdng'] == 0 or (cave['holdng'] == 1 and toting(g,w['emrald']))): return {'fn':None} # Holding nothing or only emerald. g['newloc'] = g['loc'] # Don't move. speak(g, 117, 'r') # WON'T FIT THROUGH THE TUNNEL WITH YOU. return {'fn':None} case 2: # Travel 302. Plover transport. Drop the emerald (only use # special travel if toting it), so he's forced to use the # plover-passage to get it out. Having dropped it, go back and # pretend he wasn't carrying it after all. drop(cave, g, w['emrald'],g['loc']) return {'fn':'motionVerb', 'goto':12, 'verb':k, 'kk':-1} case 3: # Travel 303. Troll bridge. Must be done only as special motion # so that dwarves won't wander across and encounter the bear. # (They won't follow the player there because that region is # forbidden to the pirate.) If prop(troll) = 1, he's crossed # since paying, so step out and block him. (Standard travel # entries check for prop(troll) = 0.) Special stuff for bear. if g['prop'][w['troll']] != 1: g['newloc'] = (g['plac'][w['troll']] + g['fixd'][w['troll']] - g['loc']) if g['prop'][w['troll']] == 0: g['prop'][w['troll']] = 1 if not toting(g,w['bear']): return {'fn':None} speak(g, 162, 'r') # YOU STUMBLE BACK AND FALL INTO THE CHASM. g['prop'][w['chasm']] = 1 g['prop'][w['troll']] = 2 drop(cave, g, w['bear'], g['newloc']) g['fixed'][w['bear']] = -1 # Destroy bear. g['prop'][w['bear']] = 3 # Dead bear. if g['prop'][w['spices']] < 0: g['tally2'] += 1 # Cannot find spices again. g['oldlc2'] = g['newloc'] return dead(cave, g, w) speak(g, w['troll'], 'p', propMsg=1) # No msg, chased away. g['prop'][w['troll']] = 0 move(cave, g, w['troll2'], 0) move(cave, g, w['troll2']+100, 0) move(cave, g, w['troll'], g['plac'][w['troll']]) move(cave, g, w['troll']+100, g['fixd'][w['troll']]) juggle(cave, g, w['chasm']) g['newloc'] = g['loc'] return {'fn':None} case _: bug(20) # Special travel (500>l>300) exceeds goto list. def motionVerb(cave, g, w, goto, k, kk=-1): ''' Figure out the new location Given the current location in "loc", and a motion verb number in "k", put the new location in "newloc". The current loc is saved in "oldloc" in case he wants to retreat. The current oldloc is saved in oldlc2, in case he dies. (If he does, newloc will be limbo, and oldloc will be what killed him, so we need oldlc2, which is the last place he was safe.) Variable kk is used with the BACK command where goto==9. ''' if goto == 8: # Line 8, newloc=loc, plus special cases. kk = g['key'][g['loc']] # loc travel[] info begins here. g['newloc'] = g['loc'] if kk == 0: bug(26) # Location has no travel entries. # Special cases to return now. if k == w['null']: return {'fn':None} elif k == w['back']: return goBack(g, kk) # Return to previous location. elif k == w['look']: lookAround(cave, g) # Describe location. return {'fn':None} elif k == w['cave']: caveMsg(g) # Looking for find cave. return {'fn':None} # Age locations. g['oldlc2'] = g['oldloc'] # Last place he was safe. g['oldloc'] = g['loc'] if goto <= 9: # Line 9, jump straight here for BACK. while True: # Loop through possible newloc's from loc. ll = abs(g['travel'][kk]) # travel[kk] is possible newloc. if ll%1000 in [1, k]: # Verb k got him from oldloc to loc. break # Use verb ll below. if g['travel'][kk] < 0: # Last potential newloc from loc. return badMotion(g, w, k) # Print error before next turn. kk += 1 # Next possible newloc. # ll = 1000*newlocinfo + verb # newlocinfo = 1000*cond + newloc while True: # Line 10 if goto < 12: ll //= 1000 # Newloc portion of ll. while True: if goto < 12: # Line 11, conditional travel. g['newloc'] = ll//1000 # 0 if unconditional travel. k = g['newloc']%100 # Motion condition on property k. if g['newloc'] <= 300: # Non-property condition. break if g['prop'][k] != g['newloc']//100 - 3: # Met prop condition. g['newloc'] = ll%1000 # Go to conditional newloc. return locType(cave, g, w, k) # Handle movement. while True: # Line 12, jump straight here for Plover transport. if g['travel'][kk] < 0: bug(25) # Conditional travel entry with no alternative. kk += 1 # Index to next potential newloc. g['newloc'] = abs(g['travel'][kk])//1000 if g['newloc'] == ll: # Don't go to same place. continue # Consider next potential newloc. ll = g['newloc'] break goto = 11 if g['newloc'] <= 100: # Line 13, newloc is probability of travel. if g['newloc'] != 0 and not pct(g['newloc']): # Line 14 goto = 12 # Not taking this route, look at next. continue # Look at next possible route. elif toting(g,k) or (g['newloc'] > 200 and at(g,k)): goto = 16 else: goto = 12 continue g['newloc'] = ll%1000 # Line 16, the actual newloc. return locType(cave, g, w, k) def move(cave, g, obj,where): ''' Place any object anywhere by picking it up and dropping it. May already be toting, in which case the carry is a no-op. Mustn't pick up objects which are not at any loc, since carry wants to remove objects from atloc chains. ''' if obj <= 100: frm = g['place'][obj] # Location of movable object. else: frm = g['fixed'][obj-100] # Location of immovable object. if 0 < frm <= 300: # If object is at some location (not toted), carry(cave, g, obj, frm) # then tote it. drop(cave, g, obj, where) # Move it to new loc. def newhrs(cave, g, w, wizcom): ''' Set up new hours for the cave. Specified as inverse--i.e., when is it closed due to prime time? See hours (above) for desc of variables. ''' speak(g, 21, 'm') wizcom['wkday'] = newhrx(cave, g, w, 'WEEKDAYS:') wizcom['wkend'] = newhrx(cave, g, w, 'WEEKENDS:') wizcom['holid'] = newhrx(cave, g, w, 'HOLIDAYS:') speak(g, 22, 'm') hours(wizcom) def newhrx(cave, g, w, day): ''' Input prime time specs and set up a word of internal format. ''' newhrx = 0 print(' PRIME TIME ON %s' % day) while True: frm = inputCheck(cave, g, w, ' FROM: ', dtype=int) if not (0 <= frm < 24): return newhrx till = inputCheck(cave, g, w, ' TILL: ', dtype=int) till -= 1 if not (frm <= till < 24): return newhrx for i in range(frm, till+1): newhrx |= 1< 0: speak(g, spk, 'r') # Print prompt. if spk > -1: # New turn, so age object/verb info. verb = 0 g['oldobj'] = g['obj'] g['obj'] = 0 # Check if this loc is eligible for any hints. If been here long enough, # branch to help section (on later page). Hints all come back here # eventually to finish the loop. Ignore "hints" < 4 (special stuff, see # database notes). for hint in range(4, g['hntmax']+1): if g['hinted'][hint]: continue if not bitset(g,g['loc'],hint): g['hintlc'][hint] = -1 g['hintlc'][hint] += 1 if g['hintlc'][hint] >= g['hints'][hint][1]: getHint(cave, g, w, hint) # Kick the random number generator just to add variety to the chase. Also, # if closing time, check for any objects being toted with prop < 0 and set # the prop to -1-prop. This way objects won't be described until they've # been picked up and put down separate from their respective piles. Don't # tick clock1 unless well into cave (and not at Y2). if cave['closed']: if g['prop'][w['oyster']] < 0 and toting(g,w['oyster']): speak(g, w['oyster'], 'p', propMsg=1) # WRITTEN UNDERSIDE OF OYSTER. for i in range(1, 100+1): if toting(g,i) and g['prop'][i] < 0: g['prop'][i] = -1 - g['prop'][i] cave['wzdark'] = dark(g, w) if g['knfloc'] > 0 and g['knfloc'] != g['loc']: g['knfloc'] = 0 random() wd1, wd2 = getin(cave, g, w) return specialCases(cave, g, w, wizcom, wd1, wd2, verb) def objName(g, obj): for i in range(1, g['tabsiz']+1): if g['ktab'][i] == -1: return -1 if (1000 <= g['ktab'][i] < 2000) and g['ktab'][i]%1000 == obj: return g['atab'][i] return 'Not found' def parseWords(cave, g, w, wizcom, wd1, wd2): ''' Section 4: Vocabulary. Each line contains a number (n), a tab, and a five-letter word. Call m = n/1000. If m = 0, then the word is a motion verb for use in travelling (see section 3). Else, if m = 1, the word is an object. Else, if m = 2, the word is an action verb (such as "carry" or "attack"). Else, if m = 3, the word is a special case verb (such as "dig") and n mod 1000 is an index into section 6. Objects from 50 to (currently, anyway) 79 are considered treasures (for pirate, closeout). ''' i = vocab(g, wd1, -1) if i == -1: # Gee, i don't understand. print('\n SORRY, I DON\'T KNOW THE WORD "%s".' % wd1) return {'fn':'newTurn', 'spk':-1} vType,vNum = divmod(i, 1000) match vType: case 0: # Motion verb. return motionVerb(cave, g, w, 8, vNum) case 1: # Object. return analyseObject(cave, g, w, wizcom, wd1, wd2, vNum) case 2: # Action verb. return analyseVerb(cave, g, w, wizcom, wd1, wd2, vNum) case 3: # Special verb like "DIG". return {'fn':'newTurn', 'spk':vNum} case _: bug(22) # Vocabulary type (n/1000) not between 0 and 3. def pirateActions(cave, g, w): # The pirate's spotted him. He leaves him alone once we've # found chest. K counts if a treasure is here. If not, and # tally = tally2 plus one for an unseen chest, let the pirate # be spotted. Use place[messag] to determine if pirate's # been seen, since place[chest] = 0 could mean he threw it to # troll. if g['loc'] == g['chloc'] or g['prop'][w['chest']] >= 0: return # Chest discovered. k = 0 plac = g['plac'] # Rooms where objects were originally placed. for j in range(50, g['maxtrs']+1): # Treasures are >= 50. # Pirate won't take pyramid from Plover Room or Dark Room # (too easy!). if not (j == w['pyram'] and g['loc'] in [plac[w['pyram']], plac[w['emrald']]]): if toting(g,j): # Non-pyramid, non-emerald here. break if here(g,j): k = 1 # Treasure to steal! else: if (g['tally'] == g['tally2']+1 # Unseen chest and k == 0 # and no treasure here and g['place'][w['messag']] == 0 # and pirate not seen and here(g,w['lamp']) # and lamp is here and g['prop'][w['lamp']] == 1): # and is on. speak(g, 186, 'r') # FAINT RUSTLING NOISES...PIRATE. move(cave, g, w['chest'], g['chloc']) # Place chest in Alike maze. move(cave, g, w['messag'], g['chloc2']) # Place message in Diff maze. g['dloc'][6] = g['chloc'] # Pirate is with chest. g['odloc'][6] = g['chloc'] g['dseen'][6] = False # Still not seen. return if g['odloc'][6] != g['dloc'][6] and pct(20): speak(g, 127, 'r') # FAINT RUSTLING NOISES... return speak(g, 128, 'r') # A BEARDED PIRATE! if g['place'][w['messag']] == 0: move(cave, g, w['chest'],g['chloc']) move(cave, g, w['messag'],g['chloc2']) for j in range(50, g['maxtrs']): if (j == w['pyram'] and (g['loc'] in [plac[w['pyram']], plac[w['emrald']]])): continue # Don't steal pyramid from Dark or Plover Rooms. if at(g,j) and g['fixed'][j] == 0: carry(cave, g, j,g['loc']) if toting(g,j): # Take treasure j, drop(cave, g, j,g['chloc']) # and put at the Chest location. g['dloc'][6] = g['chloc'] # Put the pirate with the chest. g['odloc'][6] = g['chloc'] g['dseen'][6] = False # Pirate is unseen. return def postDbInit(g): # Finish constructing internal data format # If setup = 2 we don't need to do this. It's only necessary if we # haven't done it at all or if the program has been run since then. if g['setup'] == 2: return # if g['setup'] == -1: # XXX Never called. # suspend(cave, g, w, wizcom, restart=True) cave = { # 'c' for cave state. 'abbnum':5, 'bonus':0, 'clock1':30, 'clock2':50, 'closed':False, 'closng':False, 'demo':False, 'detail':0, 'dflag':0, 'dkill':0, 'foobar':0, 'gaveup':False, 'holdng':0, 'iwest':0, 'knfloc':0, 'lmwarn':False, 'numdie':0, 'panic':False, 'saved':0, 'savet':0, 'scorng':False, 'turns':0, 'wzdark':False, } for i in range(4+1): if g['rtext'][2*i+81] != 0: cave['maxdie'] = i + 1 # Having read in the database, certain things are now constructed. Props # are set to zero. We finish setting up cond by checking for # forced-motion travel entries. The plac and fixd arrays are used to set # up atloc[n] as the first object at location n, and link[obj] as the # next object at the same location as obj. (Obj>100 indicates that # fixed(obj-100) = loc; link[obj] is still the correct link to use.) Abb # is zeroed; it controls whether the abbreviated description is printed. # Counts mod 5 unless "look" is used. for i in range(1, 100+1): g['place'][i] = 0 g['prop'][i] = 0 g['link'][i] = 0 g['link'][i+100] = 0 for i in range(1, g['locsiz']+1): g['abb'][i] = 0 if g['ltext'][i] != 0 and g['key'][i] != 0: k = g['key'][i] if abs(g['travel'][k])%1000 == 1: g['cond'][i] = 2 # Forced movement at this location. g['atloc'][i] = 0 # Set up the atloc and link arrays as described above. We'll use the # drop subroutine, which prefaces new objects on the lists. Since we # want things in the other order, we'll run the loop backwards. If the # object is in two locs, we drop it twice. This also sets up "place" # and "fixed" as copies of "plac" and "fixd". Also, since two-placed # objects are typically best described last, we'll drop them first. for i in range(1, 100+1): k = 101 - i if g['fixd'][k] <= 0: continue drop(cave, g, k+100, g['fixd'][k]) drop(cave, g, k, g['plac'][k]) for i in range(1, 100+1): k = 101 - i g['fixed'][k] = g['fixd'][k] if g['plac'][k] != 0 and g['fixd'][k] <= 0: drop(cave, g, k, g['plac'][k]) # Treasures, as noted earlier, are objects 50 through maxtrs (currently # 79). Their props are initially -1, and are set to 0 the first time # they are described. Tally keeps track of how many are not yet found, # so we know when to close the cave. Tally2 counts how many can never be # found (e.g. if lost bird or bridge). g['maxtrs'] = 79 g['tally'] = 0 g['tally2'] = 0 for i in range(50, g['maxtrs']+1): # Go through treasures, which are >50. if g['ptext'][i] != 0: # ==0 means no object info here. g['prop'][i] = -1 # Treasure not yet found. g['tally'] -= g['prop'][i] # Clear the hint stuff. hintlc[i] is how long he's been at loc with # cond bit i. hinted[i] is true iff hint i has been used. for i in range(1, g['hntmax']+1): g['hinted'][i] = False g['hintlc'][i] = 0 # Define some handy mnemonics. These correspond to object numbers. w = { # 'w' for words. 'keys':vocab(g, 'KEYS',1), 'lamp':vocab(g, 'LAMP',1), 'grate':vocab(g, 'GRATE',1), 'cage':vocab(g, 'CAGE',1), 'rod':vocab(g, 'ROD',1), 'rod2':vocab(g, 'ROD',1) + 1, 'steps':vocab(g, 'STEPS',1), 'bird':vocab(g, 'BIRD',1), 'door':vocab(g, 'DOOR',1), 'pillow':vocab(g, 'PILLO',1), 'snake':vocab(g, 'SNAKE',1), 'fissur':vocab(g, 'FISSU',1), 'tablet':vocab(g, 'TABLE',1), 'clam':vocab(g, 'CLAM',1), 'oyster':vocab(g, 'OYSTE',1), 'magzin':vocab(g, 'MAGAZ',1), 'dwarf':vocab(g, 'DWARF',1), 'knife':vocab(g, 'KNIFE',1), 'food':vocab(g, 'FOOD',1), 'bottle':vocab(g, 'BOTTL',1), 'water':vocab(g, 'WATER',1), 'oil':vocab(g, 'OIL',1), 'plant':vocab(g, 'PLANT',1), 'plant2':vocab(g, 'PLANT',1) + 1, 'axe':vocab(g, 'AXE',1), 'mirror':vocab(g, 'MIRRO',1), 'dragon':vocab(g, 'DRAGO',1), 'chasm':vocab(g, 'CHASM',1), 'troll':vocab(g, 'TROLL',1), 'troll2':vocab(g, 'TROLL',1) + 1, 'bear':vocab(g, 'BEAR',1), 'messag':vocab(g, 'MESSA',1), 'vend':vocab(g, 'VENDI',1), 'batter':vocab(g, 'BATTE',1), # Objects from 50 through whatever are treasures. Here are a few., 'nugget':vocab(g, 'GOLD',1), 'coins':vocab(g, 'COINS',1), 'chest':vocab(g, 'CHEST',1), 'eggs':vocab(g, 'EGGS',1), 'tridnt':vocab(g, 'TRIDE',1), 'vase':vocab(g, 'VASE',1), 'emrald':vocab(g, 'EMERA',1), 'pyram':vocab(g, 'PYRAM',1), 'pearl':vocab(g, 'PEARL',1), 'rug':vocab(g, 'RUG',1), 'chain':vocab(g, 'CHAIN',1), 'spices':vocab(g, 'SPICE',1), # These are motion-verb numbers., 'back':vocab(g, 'BACK',0), 'look':vocab(g, 'LOOK',0), 'cave':vocab(g, 'CAVE',0), 'null':vocab(g, 'NULL',0), 'entrnc':vocab(g, 'ENTRA',0), 'dprssn':vocab(g, 'DEPRE',0), # And some action verbs., 'say':vocab(g, 'SAY',2), 'lock':vocab(g, 'LOCK',2), 'throw':vocab(g, 'THROW',2), 'find':vocab(g, 'FIND',2), 'invent':vocab(g, 'INVEN',2) } ''' Initialise the dwarves. Dloc is loc of dwarves, hard-wired in. Odloc is prior loc of each dwarf, initially garbage. Daltlc is alternate initial loc for dwarf, in case one of them starts out on top of the adventurer. (No 2 of the 5 initial locs are adjacent.) Dseen is true if dwarf has seen him. Dflag controls the level of activation of all this: 0 No dwarf stuff yet (wait until reaches hall of mists) 1 Reached hall of mists, but hasn't met first dwarf 2 Met first dwarf, others start moving, no knives thrown yet 3 A knife has been thrown (first set always misses) 3+ Dwarves are mad (increases their accuracy) Sixth dwarf is special (the pirate). He always starts at his chest's eventual location inside the maze. This loc is saved in chloc for ref. The dead end in the other maze has its loc stored in chloc2. ''' g['chloc'] = 114 # DEAD END g['chloc2'] = 140 # DEAD END g['dseen'][1:6+1] = 6*[False] g['dflag'] = 0 g['dloc'][1] = 19 # HALL OF THE MOUNTAIN KING g['dloc'][2] = 27 # WEST SIDE OF FISSURE IN HALL OF MISTS g['dloc'][3] = 33 # LARGE ROOM "Y2" ON A ROCK g['dloc'][4] = 44 # TWISTY LITTLE PASSAGES, ALL ALIKE g['dloc'][5] = 64 # COMPLEX JUNCTION LARGE ROOM ABOVE g['dloc'][6] = g['chloc'] g['daltlc'] = 18 # NUGGET OF GOLD ROOM ''' Other random flags and counters, as follows: turns Tallies how many commands he's given (ignores yes/no) limit Lifetime of lamp (not set here) iwest How many times he's said "WEST" instead of "W" knfloc 0 if no knife here, loc if knife here, -1 after caveat detail How often we've said "not allowed to give more detail" abbnum How often we should print non-abbreviated descriptions maxdie Number of reincarnation messages available (up to 5) numdie Number of times killed so far holdng Number of objects being carried dkill Number of dwarves killed (unused in scoring, needed for msg) foobar Current progress in saying "FEE FIE FOE FOO". bonus Used to determine amount of bonus if he reaches closing clock1 Number of turns from finding last treasure till closing clock2 Number of turns from first warning till blinding flash Logicals were explained earlier ''' # If setup = 1, report on amount of arrays actually used, to permit # reductions. # if g['setup'] != 1: # return g['setup'] = 2 for kk in range(g['locsiz'], 0, -1): # Section 1. if g['ltext'][kk] != 0: break g['obj'] = 0 for k in range(1, 100+1): # Section 5. if g['ptext'][k] != 0: g['obj'] += 1 for k in range(1, g['tabndx']+1): # Section 4. if g['ktab'][k]//1000 == 2: verb = g['ktab'][k] - 2000 for j in range(g['rtxsiz'], 0, -1): # Section 6. if g['rtext'][j] != 0: break for i in range(g['magsiz'], 0, -1): # Section 12. if g['mtext'][i] != 0: break if False: k = 100 print(' TABLE SPACE USED:') print(' %6d OF %6d WORDS OF MESSAGES' % (g['linbytes']//5, g['linsiz'])) print(' %6d OF %6d TRAVEL OPTIONS' % (g['trvs'], g['trvsiz'])) print(' %6d OF %6d VOCABULARY WORDS' % (g['tabndx'], g['tabsiz'])) print(' %6d OF %6d LOCATIONS' % (kk, g['locsiz'])) print(' %6d OF %6d OBJECTS' % (g['obj'], k)) print(' %6d OF %6d ACTION VERBS' % (verb, g['vrbsiz'])) print(' %6d OF %6d RTEXT MESSAGES' % (j, g['rtxsiz'])) print(' %6d OF %6d CLASS MESSAGES' % (g['clsses'], g['clsmax'])) print(' %6d OF %6d HINTS' % (g['hntmax'], g['hntsiz'])) print(' %6d OF %6d MAGIC MESSAGES' % (i, g['magsiz'])) # Finally, since we're clearly setting things up for the first time... wizcom = poof() return cave, w, wizcom def poof(fname='hours'): ''' As part of database initialisation, we call poof to set up some dummy prime-time specs, magic words, etc. ''' d = { 'hbegin':0, 'hend':-1, 'hname':'', 'holid':0, 'latncy':90, 'magic':'DWARF', 'magnm':11111, # Not used with passwd challenge removed. - mm 'motd':'', 'short':30, 'wkday':0x3ff00, # 0o00777400 'wkend':0, } try: with open(fname) as file: for line in file: line = line.strip() if line == '': continue sp = line.find(' ') firstWord = line[:sp] if firstWord in ['hname','motd']: d[firstWord] = line[1+sp:] # Might contain spaces. else: line = line.split() if len(line) != 2: continue var,val = line if var == 'magic': d[var] = val else: d[var] = int(val) except FileNotFoundError: pass return d def pour(g, w, wd1, spk): # POUR. If no object, or object is bottle, assume contents of bottle. # Special tests for pouring water or oil on plant or rusty door. if g['obj'] == w['bottle'] or g['obj'] == 0: g['obj'] = liq(g, w) if g['obj'] == 0: return what(g, wd1) if not toting(g,g['obj']): return {'fn':'newTurn', 'spk':spk} spk = 78 # YOU CAN'T POUR THAT. if g['obj'] != w['oil'] and g['obj'] != w['water']: return {'fn':'newTurn', 'spk':spk} g['prop'][w['bottle']] = 1 g['place'][g['obj']] = 0 spk = 77 # YOUR BOTTLE IS EMPTY AND THE GROUND IS WET. if not (at(g,w['plant']) or at(g,w['door'])): return {'fn':'newTurn', 'spk':spk} if not at(g,w['door']): spk = 112 # THE PLANT INDIGNANTLY SHAKES THE OIL OFF ITS LEAVES... if g['obj'] != w['water']: return {'fn':'newTurn', 'spk':spk} speak(g, w['plant'], 'p', propMsg=g['prop'][w['plant']]+1) g['prop'][w['plant']] = (g['prop'][w['plant']] + 2)%6 g['prop'][w['plant2']] = g['prop'][w['plant']]//2 k = w['null'] return {'fn':'motionVerb','goto':8, 'verb':k, 'kk':-1} g['prop'][w['door']] = 0 if g['obj'] == w['oil']: g['prop'][w['door']] = 1 spk = 113 + g['prop'][w['door']] return {'fn':'newTurn', 'spk':spk} def put(cave, g, obj,where,pval): ''' Put is the same as move, except it returns a value used to set up the negated prop values for the repository objects. ''' move(cave, g, obj, where) return -1 - pval def quitGame(cave, g, w, verify=True): # QUIT. Intransitive only. Verify intent and exit if that's what he # wants. if verify: cave['gaveup'] = yes(cave, g, w,22,54,54,'r') # REALLY WANT TO QUIT? if cave['gaveup']: finish(cave, g, w) return {'fn':'newTurn', 'spk':0} def ran(rnge): # Unused. ''' Since the ran function in lib40 seems to be a real lose, we'll use one of our own. It's been run through many of the tests in Knuth Vol. 2 and seems to be quite reliable. Ran returns a value uniformly selected between 0 and rnge-1. Note resemblance to alg used in wizard. ''' r = 0 # r/0/ d = 1 if r == 0: d,t = datime() r = 18*t + 5 d = 1000 + d%1000 for t in rnge(d): r = r*1021%0x100000 return (rnge*r)//0x100000 def read(cave, g, w, wd1, spk, intransitive=True): # READ. Magazines in dwarvish, message we've seen, and . . . oyster? if intransitive: # Find object. if here(g,w['magzin']): g['obj'] = w['magzin'] if here(g,w['tablet']): g['obj'] = g['obj']*100 + w['tablet'] if here(g,w['messag']): g['obj'] = g['obj']*100 + w['messag'] if cave['closed'] and toting(g,w['oyster']): g['obj'] = w['oyster'] if g['obj'] > 100 or g['obj'] == 0 or dark(g, w): return what(g, wd1) obj = g['obj'] if dark(g, w): s = wd1 print(' I SEE NO %s HERE.' % s) if obj == w['magzin']: spk = 190 # MAGAZINE IS WRITTEN IN DWARVISH. if obj == w['tablet']: spk = 196 # "CONGRATULATIONS ON BRINGING LIGHT INTO THE DARK-ROOM!" if obj == w['messag']: spk = 191 # "NOT MAZE WHERE PIRATE LEAVES TREASURE CHEST." if obj == w['oyster'] and g['hinted'][2] and toting(g,w['oyster']): spk = 194 # IT SAYS THE SAME THING IT DID BEFORE. if (obj != w['oyster'] or g['hinted'][2] or not toting(g,w['oyster']) or not cave['closed']): return {'fn':'newTurn', 'spk':spk} g['hinted'][2] = yes(cave, g, w,192,193,54,'r') # READ IT. READ IT ANYWAY? return {'fn':'newTurn', 'spk':0} def rub(g, w): # RUB. Yields various snide remarks. spk = g['actspk'][g['verb']] # Default message for verb. if g['obj'] != w['lamp']: spk = 76 # PECULIAR. NOTHING UNEXPECTED HAPPENS. return {'fn':'newTurn', 'spk':spk} def say(cave, g, w, wizcom, wd1, wd2): # SAY. Echo wd2 (or wd1 if no wd2 (SAY WHAT?, etc.).) Magic words # override. if wd2 != '': wd1 = wd2 i = vocab(g, wd1, -1) # XYZZY, PLUGH, PLOVE, FEE, FIE, FOE, FOO, FUM if not (i in [62, 65, 71, 2025]): # Magic words. print('\n OKAY, "%s".' % wd1) return {'fn':'newTurn', 'spk':0} wd2 = '' g['obj'] = 0 return parseWords(cave, g, w, wizcom, wd1, wd2) def score(cave, g, w): # SCORE. Go to scoring section, which will return to 8241 if scorng is # true. score,mxscor = finish(cave, g, w, scorng=True) print('\n IF YOU WERE TO QUIT NOW, YOU WOULD SCORE%4d OUT OF A POSSIBLE%4d.' % (score,mxscor)) cave['gaveup'] = yes(cave, g, w,143,54,54,'r') # DO YOU INDEED WISH TO QUIT NOW? # quitGame(cave, g, w, ask=False) # Might or might not quit. if cave['gaveup']: finish(cave, g, w) return {'fn':'newTurn', 'spk':0} def secondWord(cave, g, w, wizcom, wd1, wd2): # Get second word for analysis. wd1, wd2 = wd2, '' westOrW(cave, g, wd1) return parseWords(cave, g, w, wizcom, wd1, wd2) def sections(db, g, sect): # Sections 1, 2, 6, 10, 12. Read messages and set up pointers. oldloc = -1 while True: line = db.readline().strip() if line[:2] == '-1': # End of section. return tab = line.find('\t') loc,msg = line[:tab],line[tab+1:] # Can't use split(), multiple tabs. loc = int(loc) g['linbytes'] += len(msg) if loc != oldloc: # New location. g['lines'].append(msg) g['linuse'] += 1 else: g['lines'][g['linuse']] += '\n' + msg # Update pointers into lines[]. match sect: case 1: # Long form descriptions. g['ltext'][loc] = g['linuse'] case 2: # Short form descriptions. g['stext'][loc] = g['linuse'] case 6: # Arbitrary messages. if loc > g['rtxsiz']: bug(6) # Too many rtext or mtext messages. g['rtext'][loc] = g['linuse'] case 10: # Class messages. g['ctext'][g['clsses']] = g['linuse'] # Class level text. g['cval'][g['clsses']] = loc # Class point threshold. g['clsses'] += 1 # Number of classes. case 12: # Magic messages. if loc > g['magsiz']: bug(6) # Too many rtext or mtext messages. g['mtext'][loc] = g['linuse'] oldloc = loc if len(msg)+14 > g['linsiz']: bug(2) # Too many words of messages. def section3(db, g): ''' The stuff for section 3 is encoded here. Each "from-location" gets a contiguous section of the "travel" array. Each entry in travel is newloc*1000 + keyword (from section 4, motion verbs), and is negated if this is the last entry for this location. Key(n) is the index in travel of the first option at location n. Section 3: Travel Table. Each line contains a location number (x), a second location number (y), and a list of motion numbers (see section 4). Each motion represents a verb which will go to y if currently at x. Y, in turn, is interpreted as follows. Let m = y/1000, n = y mod 1000. If n<=300 It is the location to go to. If 300500 Message n-500 from section 6 is printed, and he stays wherever he is. Meanwhile, m specifies the conditions on the motion. If m=0 It's unconditional. If 0$<". Data file lines: 2 BRASS LANTERN 000 THERE IS A SHINY BRASS LAMP NEARBY. 100 THERE IS A LAMP SHINING NEARBY. are stored in lines[] as a single list: lines[i] = ['BRASS LANTERN', 'THERE IS A SHINY BRASS LAMP NEARBY.', 'THERE IS A LAMP SHINING NEARBY.'] where indices 1 and onward are assumed to be 000, 100, 200, ... ''' oldloc = '' while True: line = db.readline().strip() if line[:2] == '-1': # End of section 5. break isInventory = (line[1:3] != '00') loc,msg = line.split('\t') loc = int(loc) g['linbytes'] += len(msg) if isInventory: i = g['linuse'] - 1 g['lines'].append([msg]) # Inventory entry. g['linuse'] += 1 g['ptext'][loc] = g['linuse'] elif loc == oldloc: i = g['linuse'] g['lines'][i][-1] += '\n' + msg # Inventory entry. else: g['lines'][g['linuse']].append(msg) # Entries 000, 100, 200, etc. if len(msg)+14 > g['linsiz']: bug(2) # Too many words of messages. oldloc = loc def section7(db, g): ''' Read in the initial locations for each object. Also the immovability info. Plac contains initial locations of objects. Fixd is -1 for immovable objects (including the snake), or = second loc for two-placed objects. Section 7: Object locations. Each line contains an object number and its initial location (zero (or omitted) if none). If the object is immovable, the location is followed by a "-1". If it has two locations (e.g. the grate) the first location is followed with the second, and the object is assumed to be immovable. ''' while True: v = list(map(int, db.readline().strip().split())) if v[0] == -1: return obj = v[0] if len(v) >= 2: g['plac'][obj] = v[1] if len(v) == 3: g['fixd'][obj] = v[2] def section8(db, g): ''' Read default message numbers for action verbs, store in actspk. Section 8: action defaults. Each line contains an "action-verb" number and the index (in section 6) of the default message for the verb. ''' while True: vals = list(map(int, db.readline().strip().split())) verb = vals[0] if verb == -1: return g['actspk'][verb] = vals[1] def section9(db, g): ''' Read info about available liquids and other conditions, store in cond. Section 9: Liquid assets, etc. Each line contains a number (n) and up to 20 location numbers. Bit n (where 0 is the units bit) is set in cond[loc] for each loc given. The cond bits currently assigned are: 0 Light 1 If bit 2 is on: on for oil, off for water 2 Liquid asset, see bit 1 3 Pirate doesn't go here unless following player Other bits are used to indicate areas of interest to "hint" routines: 4 Trying to get into cave 5 Trying to catch bird 6 Trying to deal with snake 7 Lost in maze 8 Pondering dark room 9 At Witt's End cond[loc] is set to 2, overriding all other bits, if loc has forced motion. ''' while True: line = db.readline().strip() tk = list(map(int, line.split())) # Variable number of ints. k = tk[0] if k == -1: break for i in range(1, len(tk)): loc = tk[i] if bitset(g,loc,k): bug(8) # Location has cond bit being set twice. g['cond'][loc] |= 1<> -dist elif dist == 0: return val else: return val << dist def speak(g, i, mType='', propMsg=-1, nl=True): ''' Print the message which starts at lines(n). Precede it with a blank line unless blklin is false. ''' if mType == 'm': # Magic. # Print the i-th "magic" message (Section 12 of database). if i == 0: return n = g['mtext'][i] elif mType == 'p': # Property. # Find the propMsg+1st message from i and print it. 'i' should be # the index of the inventory message for object. (inven+i+1 # message is prop=i message). n = g['ptext'][i] propMsg += 1 elif mType == 'r': # Random. # Print the i-th "random" message (Section 6 of database). if i == 0: return n = g['rtext'][i] else: n = i if n == 0: return msg = g['lines'][n] if propMsg != -1: msg = msg[propMsg] # Section 5 only. if msg[:3] == '>$<': # Don't print anything. return if g['blklin']: print('') msg = msg.replace('\n', '\n ') # All output indented 1 space. if nl: print(' %s' % msg) else: print(' %s' % msg, end='') def specialCases(cave, g, w, wizcom, wd1, wd2, verb): # Every input, check "foobar" flag. If zero, nothing's going on. If pos, # make neg. If neg, he skipped a word, so make it zero. cave['foobar'] = min(0, -cave['foobar']) if cave['turns'] == 0 and wd1 == 'MAGIC' and wd2 == 'MODE': maint(cave, g, w, wizcom) # Game exits if he's a wizard. return {'fn':'newTurn', 'spk':0} # He's not a wizard. cave['turns'] += 1 if cave['demo'] and cave['turns'] >= wizcom['short']: closeDemo(cave, g, w) # Demo time expired, game exits. if verb == w['say'] and wd2 != '': verb = 0 if verb == w['say']: return say(cave, g, w, wizcom, wd1, wd2) if g['tally'] == 0 and g['loc'] >= 15 and g['loc'] != 33: # In cave and found all treasures, prepare to close the cave! cave['clock1'] -= 1 if cave['clock1'] == 0: # Close the cave. return closeClock1(cave, g, w, wizcom, wd1, wd2) if cave['clock1'] < 0: cave['clock2'] -= 1 if cave['clock2'] == 0: # Off to Master's Area. return closeClock2(cave, g, w) if g['prop'][w['lamp']] == 1: # Lamp on, age battery. g['limit'] -= 1 if debug: print('Lamp %d turns left.' % g['limit']) if (g['limit'] <= 30 and here(g,w['batter']) and g['prop'][w['batter']] == 0 and here(g,w['lamp'])): return lampRecharge(cave, g, w, wizcom, wd1, wd2) # Batteries here, recharge lamp. if g['limit'] == 0: # Lamp out of energy. return lampOut(cave, g, w, wizcom, wd1, wd2) if g['limit'] < 0 and g['loc'] <= 8: # Lamp out and out of cave. lampOutQuit(cave, g, w) # Game exits. if g['limit'] <= 30: # Warn adventurer lamp energy is low. return lampNeedBatteries(cave, g, w, wizcom, wd1, wd2) k = 43 # WHERE? if liqloc(g, w) == w['water']: k = 70 # YOUR FEET ARE NOW WET. if wd1 == 'ENTER' and (wd2 in ['STREA', 'WATER']): return {'fn':'newTurn', 'spk':k} if wd1 == 'ENTER' and wd2 != '': return secondWord(cave, g, w, wizcom, wd1, wd2) # Move wd2 to wd1. if (wd1 in ['WATER', 'OIL'] and wd2 in ['PLANT', 'DOOR'] and at(g,vocab(g, wd2,1))): # Use liquid name as verb POUR. wd2 = 'POUR' westOrW(cave, g, wd1) # When no special cases, fall through to this call. return parseWords(cave, g, w, wizcom, wd1, wd2) def start(cave, g, w, wizcom): ''' Check to see if this is "prime time". If so, only wizards may play, though others may be allowed a short game for demonstration purposes. If setup<0, we're continuing from a saved game, so check for suitable latency. Return true if this is a demo game (value is ignored for restarts). ''' # First find out whether it is prime time (save in ptime) and, if # restarting, whether it's too soon (save in soon). Prime-time specs # are in wkday, wkend, and holid; see maint routine for details. Latncy # is required delay before restarting. Wizards may cut this to a # third. d,t = datime() primtm = wizcom['wkday'] if d%7 <= 1: # 0,1 are Sat,Sun. primtm = wizcom['wkend'] if wizcom['hbegin'] <= d <= wizcom['hend']: # During a holiday. primtm = wizcom['holid'] ptime = (primtm & (1<<(t//60))) != 0 soon = False if g['setup'] < 0: delay = (d-cave['saved'])*1440 + (t-cave['savet']) if delay < wizcom['latncy']: print(' THIS ADVENTURE WAS SUSPENDED A MERE %3d MINUTES AGO.' % delay) soon = True if delay < wizcom['latncy']//3: speak(g, 2, 'm') # EVEN WIZARDS HAVE TO WAIT LONGER THAN THAT! sys.exit(0) # If neither too soon nor prime time, no problem. Else specify what's # wrong. start = False if not soon: if not ptime: cave['saved'] = -1 return start # Come here if not restarting too soon (maybe not restarting at all), # but it's prime time. Give our hours and see if he's a wizard. If # not, then can't restart, but if just beginning then we can offer a # short game. speak(g, 3, 'm') # COLOSSAL CAVE IS CLOSED. hours(wizcom) speak(g, 4, 'm') # ONLY WIZARDS NOW if wizard(cave, g, w, wizcom): cave['saved'] = -1 return start if g['setup'] < 0: speak(g, 9, 'm') # RESUME YOUR ADVENTURE LATER sys.exit(0) start = yes(cave, g, w,5,7,7,'m') # ALLOW VISITORS SHORT EXPLORATIONS if start: cave['saved'] = -1 return start sys.exit(0) # Come here if restarting too soon. If he's a wizard, let him go # (and note that it then doesn't matter whether it's prime time). # else, tough beans. speak(g, 8, 'm') # ONLY A WIZARD THIS SOON if wizard(cave, g, w, wizcom): cave['saved'] = -1 return start speak(g, 9, 'm') # RESUME YOUR ADVENTURE LATER sys.exit(0) def stateRead(cave, g, w, fname='GAME.CAV'): '''Doing this brute force rather than pickle or similar so that it can be ported with ease to micropython for calculators, in particular. ''' # F i n d g a m e t o l o a d files = os.listdir() files.sort() afiles = [] for f in files: if f[-4:] == '.CAV': afiles.append(f) if len(afiles) == 0: print(' I SEE NO SAVED GAME HERE.') return elif len(afiles) == 1: fname = afiles[0] # One saved game, no need to ask user. elif len(afiles) > 1: print(' I SEE THESE SAVED GAMES:') for i,s in enumerate(afiles): print(' %d. %s' % (i+1,s)) n = (inputCheck(cave,g,w,' ENTER NUMBER OF GAME TO RESUME: ',dtype=int)) n -= 1 fname = afiles[n] # L o a d g a m e f = open(fname, 'r') while True: line = f.readline().strip() if line == '': #EOF break line = line.strip() if line == 'cave': d = cave continue elif line == 'game': d = g continue var,val,tStr = line.split() val = val.split(',') if len(val) == 0: continue elif len(val) == 1: v = val[0] if tStr == 'str': d[var] = v elif tStr == 'int': d[var] = int(v) elif tStr == 'bool': d[var] = (v == 'True') else: # List. res = [] for v in val: if tStr == 'str': res.append(v) elif tStr == 'int': res.append(int(v)) elif tStr == 'bool': res.append(v == 'True') d[var] = res f.close() return def stateWrite(cave, g, fname='GAME.CAV'): # Write dictionaries. f = open(fname, 'w') print('cave', file=f) for k in cave.keys(): # Cave state. t = str(type(cave[k])) t = t[:t.rfind("'")] t = t[t.find("'")+1:] print('%s %s %s' % (k, str(cave[k]), t), file=f) print('game', file=f) for k in g.keys(): # Game state. if k in [ 'actspk', 'atab', 'clsmax', 'clsses', 'cond', 'ctext', 'cval', 'fixd', 'hints', 'hntsiz', 'key', 'ktab', 'linbytes', 'lines', 'linsiz', 'linuse', 'locsiz', 'ltext', 'magsiz', 'mtext', 'plac', 'ptext', 'rtext']: continue # Won't change so reread at restart. if k[:2] == 'wd': continue t = str(type(g[k])) t = t[:t.rfind("'")] t = t[t.find("'")+1:] if t == 'list': t = str(type(g[k][0])) t = t[:t.rfind("'")] t = t[t.find("'")+1:] l = str(g[k]) l = l.replace('[','') l = l.replace(']','') l = l.replace(' ','') print('%s %s %s' % (k, l, t), file=f) else: print('%s %s %s' % (k, str(g[k]), t), file=f) f.close() print(' GAME SAVED.') return def suspend(cave, g, w, wizcom, restart=False): # SUSPEND. Offer to exit leaving things restartable, but requiring a # delay before restarting (so can't save the world before trying # something risky). Upon restarting, setup = -1 causes return to 8305 to # pick up again. if restart: stateRead(cave, g, w) # Read game state from saved game. start(cave, g, w, wizcom) g['setup'] = 3 k = w['null'] return {'fn':'motionVerb','goto':8, 'verb':k, 'kk':-1} else: if cave['demo']: spk = 201 # NO POINT IN SUSPENDING A DEMONSTRATION GAME. return {'fn':'newTurn', 'spk':spk} s = '\n I CAN SUSPEND YOUR ADVENTURE FOR YOU SO THAT YOU CAN' s += (' RESUME LATER, BUT\n YOU WILL HAVE TO WAIT AT LEAST%3d' % wizcom['latncy']) s += ' MINUTES BEFORE CONTINUING.' print(s) if not yes(cave, g, w,200,54,54,'r'): # IS THIS ACCEPTABLE? return {'fn':'newTurn', 'spk':0} fname = input(' FILE NAME? (NULL TO USE "GAME.CAV") ').strip().upper() if fname == '': fname = 'GAME.CAV' else: if fname.find('.CAV') == -1: fname += '.CAV' cave['saved'],cave['savet'] = datime() g['setup'] = -1 stateWrite(cave, g, fname) ciao(cave, g, w) def take(cave, g, w, wd1, intransitive=True, spk=0): # Carry an object. Special cases for bird and cage (if bird in cage, can't # take one without the other). Liquids also special, since they depend on # status of bottle. Also various side effects, etc. # # Synonyms: CARRY,TAKE,KEEP,CATCH,STEAL,CAPTU,GET,TOTE. if intransitive: # Carry, no object given yet. Ok if only one object present. if g['atloc'][g['loc']] == 0 or g['link'][g['atloc'][g['loc']]] != 0: return what(g, wd1) for i in range(1, 5+1): if g['dloc'][i] == g['loc'] and cave['dflag'] >= 2: # Dwarf here & have met a dwarf. return what(g, wd1) g['obj'] = g['atloc'][g['loc']] if toting(g,g['obj']): return {'fn':'newTurn', 'spk':spk} spk = 25 # YOU CAN'T BE SERIOUS! if g['obj'] == w['plant'] and g['prop'][w['plant']] <= 0: spk = 115 # PLANT CANNOT BE PULLED FREE. if g['obj'] == w['bear'] and g['prop'][w['bear']] == 1: spk = 169 # BEAR IS STILL CHAINED TO THE WALL. if g['obj'] == w['chain'] and g['prop'][w['bear']] != 0: spk = 170 # THE CHAIN IS STILL LOCKED. if g['fixed'][g['obj']] != 0: return {'fn':'newTurn', 'spk':spk} if g['obj'] in [w['water'], w['oil']]: if not (here(g,w['bottle']) and liq(g, w) == g['obj']): g['obj'] = w['bottle'] if toting(g,w['bottle']) and g['prop'][w['bottle']] == 1: # Empty. fill(cave, g, w, wd1, spk) if g['prop'][w['bottle']] != 1: spk = 105 # YOUR BOTTLE IS ALREADY FULL. if not toting(g,w['bottle']): spk = 104 # YOU HAVE NOTHING IN WHICH TO CARRY IT. return {'fn':'newTurn', 'spk':spk} g['obj'] = w['bottle'] if cave['holdng'] >= 7: speak(g, 92, 'r') # YOU CAN'T CARRY ANYTHING MORE return {'fn':'newTurn', 'spk':0} if g['obj'] == w['bird'] and g['prop'][w['bird']] == 0: if toting(g,w['rod']): speak(g, 26, 'r') # THE BIRD WAS UNAFRAID... return {'fn':'newTurn', 'spk':0} if not toting(g,w['cage']): speak(g, 27, 'r') # YOU CAN CATCH THE BIRD, BUT YOU CANNOT CARRY IT. return {'fn':'newTurn', 'spk':0} g['prop'][w['bird']] = 1 if ((g['obj'] == w['bird'] or g['obj'] == w['cage']) and g['prop'][w['bird']] != 0): carry(cave, g, w['bird']+w['cage']-g['obj'], g['loc']) carry(cave, g, g['obj'], g['loc']) # The typical case! k = liq(g, w) if g['obj'] == w['bottle'] and k != 0: # k==0 no liquid here. g['place'][k] = -1 return {'fn':'newTurn', 'spk':54} def throw(cave, g, w, wizcom, spk, wd1, wd2): # THROW. Same as discard unless axe. Then same as attack except ignore # bird, and if dwarf is present then one might be killed. (Only way to # do so!) Axe also special for dragon, bear, and troll. Treasures # special for troll. # # Synonyms: THROW, TOSS. if toting(g,w['rod2']) and g['obj'] == w['rod'] and not toting(g,w['rod']): g['obj'] = w['rod2'] if not toting(g,g['obj']): return {'fn':'newTurn', 'spk':spk} # Next line asks, if not throwing treasure at troll... if not (g['obj'] >= 50 and g['obj'] <= g['maxtrs'] and at(g,w['troll'])): if g['obj'] == w['food'] and here(g,w['bear']): # But throwing food is another story. g['obj'] = w['bear'] return feed(cave, g, w, spk) if g['obj'] != w['axe']: return discard(cave, g, w, spk) for i in range(1, 5+1): # Needn't check dflag if axe is here. if g['dloc'][i] == g['loc']: break else: spk = 152 # AXE BOUNCES OFF DRAGON'S THICK SCALES if at(g,w['dragon']) and g['prop'][w['dragon']] == 0: speak(g, spk, 'r') drop(cave, g, w['axe'],g['loc']) k = w['null'] return {'fn':'motionVerb', 'goto':8, 'verb':k, 'kk':-1} spk = 158 # TROLL DEFTLY CATCHES THE AXE... if at(g,w['troll']): speak(g, spk, 'r') drop(cave, g, w['axe'],g['loc']) k = w['null'] return {'fn':'motionVerb', 'goto':8, 'verb':k, 'kk':-1} if here(g,w['bear']) and g['prop'][w['bear']] == 0: # This'll teach him to throw the axe at the bear! spk = 164 # AXE MISSES... drop(cave, g, w['axe'],g['loc']) g['fixed'][w['axe']] = -1 g['prop'][w['axe']] = 1 juggle(cave, g, w['bear']) return {'fn':'newTurn', 'spk':spk} g['obj'] = 0 return attack(cave, g, w, wizcom, spk, wd1, wd2) spk = 48 # DWARF DODGES OUT OF THE WAY. # If saved not = -1, he bypassed the "start" call. if not (randint(3) == 0 or cave['saved'] != -1): # 2/3 kill rate. g['dseen'][i] = False g['dloc'][i] = 0 # Kill dwarf. spk = 47 # YOU KILLED A LITTLE DWARF. cave['dkill'] += 1 if cave['dkill'] == 1: spk = 149 # YOU KILLED A LITTLE DWARF...BLACK SMOKE. speak(g, spk, 'r') drop(cave, g, w['axe'],g['loc']) k = w['null'] return {'fn':'motionVerb', 'goto':8, 'verb':k, 'kk':-1} spk = 159 # TROLL CATCHES TREASURE, SCURRIES OUT OF SIGHT # Snarf a treasure for the troll. drop(cave, g, g['obj'], 0) move(cave, g, w['troll'], 0) move(cave, g, w['troll']+100, 0) drop(cave, g, w['troll2'], g['plac'][w['troll']]) drop(cave, g, w['troll2']+100, g['fixd'][w['troll']]) juggle(cave, g, w['chasm']) return {'fn':'newTurn', 'spk':spk} def transitive(cave, g, w, wizcom, wd1, wd2, spk=54): # Analyse a transitive verb. # Line 4090 verb = g['verb'] match verb: case 1: return take(cave, g, w, wd1, False, spk) # TAKE case 2: return discard(cave, g, w, spk) # DROP case 3: return say(cave, g, w, wizcom, wd1, wd2) # SAY case 4: return locking(cave, g, w, wd1, False) # OPEN case 5: return newTurn(cave, g, w, wizcom, verb) # NOTH case 6: return locking(cave, g, w, wd1, False) # LOCK case 7: return lampOn(cave, g, w, spk) # ON case 8: return lampOff(g, w, spk) # OFF case 9: return wave(cave, g, w, spk) # WAVE case 10: return newTurn(cave, g, w, wizcom, verb, spk) # CALM case 11: return newTurn(cave, g, w, wizcom, verb, spk) # WALK case 12: return attack(cave, g, w, wizcom, spk,wd1,wd2) # KILL case 13: return pour(g, w, wd1, spk) # POUR case 14: return eat(cave, g, w, wd1,spk, False) # EAT case 15: return drink(g, w, wd1,spk) # DRNK case 16: return rub(g, w) # RUB case 17: return throw(cave, g, w, wizcom, spk,wd1,wd2) # TOSS case 18: return newTurn(cave, g, w, wizcom, verb, spk) # QUIT case 19: return find(cave, g, w, spk, verb) # FIND case 20: return find(cave, g, w, spk, verb) # INVN case 21: return feed(cave, g, w, spk) # FEED case 22: return fill(cave, g, w, wd1, spk) # FILL case 23: return blast(cave, g, w, spk) # BLST case 24: return newTurn(cave, g, w, wizcom, verb, spk) # SCOR case 25: return newTurn(cave, g, w, wizcom, verb, spk) # FOO case 26: return newTurn(cave, g, w, wizcom, verb, spk) # BRF case 27: return read(cave, g, w, wd1,spk, False) # READ case 28: return breakObj(cave, g, w, spk) # BREK case 29: return wakeDwarves(cave, g, w, spk) # WAKE case 30: return newTurn(cave, g, w, wizcom, verb, spk) # SUSP case 31: return newTurn(cave, g, w, wizcom, verb, spk) # HOUR case _: bug(24) # Transitive action verb exceeds goto list. def vocab(g, word, init): ''' Look up id in the vocabulary (atab) and return its "definition" (ktab), or -1 if not found. If init is positive, this is an initialisation call setting up a keyword variable, and not finding it constitutes a bug. It also means that only ktab values which taken over 1000 equal init may be considered. (Thus "STEPS", which is a motion verb as well as an object, may be located as an object.) And it also means the ktab value is taken mod 1000. ''' atab = g['atab'] ktab = g['ktab'] n = g['tabsiz'] # Number of words stored. for i in range(1, n+1): if ktab[i] == -1: # Got to end of word list. if init < 0: # Negative means searching for word. return -1 # Word not found. bug(5) # Required vocabulary word not found. if init >= 0 and ktab[i]//1000 != init: continue # Didn't match correct ktab section. if atab[i] == word[:5]: # Found the word! v = ktab[i] # Get alpha word's int definition. if init >= 0: # Initialisation call. v %= 1000 # Chop off section number. return v # Integer definition. bug(21) def wizard(cave, g, w, wizcom): ''' Ask if he's a wizard. If he says yes, make him prove it. Return true if he really is a wizard. ''' wizard = yes(cave, g, w,16,0,7,'m') # if not 'WIZARD?' then 'VERY WELL.' if not wizard: return False # He says he is. First step: does he know anything magical? speak(g, 17, 'm') # PROVE IT! SAY THE MAGIC WORD! word,_ = getin(cave, g, w) if word != wizcom['magic']: # Is it 'DWARF'? # Aha! An impostor! speak(g, 20, 'm') # FOO, YOU ARE NOTHING BUT A CHARLATAN! return False if yes(cave, g, w,18,0,0,'m'): # KNOW WHAT I THOUGHT IT WAS? # Aha! An impostor! speak(g, 20, 'm') # FOO, YOU ARE NOTHING BUT A CHARLATAN! return False # Let's skip the challenge-reply. :-) print(' AH, EM, IT HAS SLIPPED MY MIND.') # By George, he really *is* a wizard! speak(g, 19, 'm') # OH DEAR, YOU REALLY *ARE* A WIZARD! return True def wakeDwarves(cave, g, w, spk): # WAKE. Only use is to disturb the dwarves. if g['obj'] != w['dwarf'] or not cave['closed']: return {'fn':'newTurn', 'spk':spk} speak(g, 199, 'r') # NEAREST DWARF WAKES UP GRUMPILY... dwarvesDisturbed(cave, g, w) # Game ends. def wave(cave, g, w, spk): # WAVE. No effect unless waving rod at fissure. if not toting(g,g['obj']) or (g['obj'] == w['rod'] and toting(g,w['rod2'])): spk = 29 # YOU AREN'T CARRYING IT! if (g['obj'] != w['rod'] or not at(g,w['fissur']) or not toting(g,g['obj']) or cave['closng']): return {'fn':'newTurn', 'spk':spk} g['prop'][w['fissur']] = 1 - g['prop'][w['fissur']] speak(g, w['fissur'], 'p', propMsg=2-g['prop'][w['fissur']]) return {'fn':'newTurn', 'spk':0} def westOrW(cave, g, wd): if wd == 'WEST': cave['iwest'] += 1 if cave['iwest'] == 10: speak(g, 17, 'r') # IF YOU PREFER, SIMPLY TYPE W RATHER THAN WEST. def what(g, wd1): # Random intransitive verbs come here. Clear obj just in case (see # "attack"). print(' %s WHAT?' % wd1) g['obj'] = 0 return {'fn':'newTurn', 'spk':-1} def yes(cave,g,w,x,y,z,spkType): ''' Print message x, wait for yes/no answer. If yes, print y and leave yea true; if no, print z and leave yea false. Spk is either rspeak or mspeak. spkType == 'm' - Call yes (below) with messages from Section 12. spkType == 'r' - Call yes (below) with messages from Section 6. ''' while True: if x != 0: speak(g, x, spkType) reply,_ = getin(cave, g, w) if reply in ['YES', 'Y', 'NO', 'N']: break print('\n PLEASE ANSWER THE QUESTION.') yes = (reply in ['YES', 'Y']) if yes: if y != 0: speak(g, y, spkType) else: if z != 0: speak(g, z, spkType) return yes if __name__ == '__main__': main()