Guest User

Wumpus Hunt!

a guest
Mar 30th, 2014
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.62 KB | None | 0 0
  1. #!python3
  2. #Python implementation of a Wumpus Hunt game as specified on
  3. #http://www.reddit.com/r/dailyprogrammer/comments/21kqjq/4282014_challenge_154_hard_wumpus_cave_game/
  4. import random
  5. points = {
  6.     'empty_room':1,
  7.     'find_weapon':5,
  8.     'find_gold':5,
  9.     'kill_wumpus':10
  10.     }
  11.  
  12. def main():
  13.     cavesize =int(input("How large is the wumpus cave? (in square units): "))
  14.     while(newGame(cavesize)):
  15.         cavesize = int(input("How large is the wumpus cave? (in square units): "))
  16.  
  17. def newGame(cavesize):
  18.     """Initialize a new game"""
  19.     board, hero = createBoard(cavesize)
  20.     while(True):
  21.         printView(board, hero.coord)
  22.         #printBoard(board)
  23.         hx,hy = hero.coord
  24.         room=board[hx][hy]
  25.         printRoom(room)
  26.         printClues(board, hero.coord)
  27.         printHero(hero)
  28.         command = input("Enter Move (? for help) >").lower()
  29.         if command == 'x':
  30.             return False
  31.         elif command == '?':
  32.             printHelp()
  33.         elif command == 'n':
  34.             moveHero(board, hero,(hx-1, hy))
  35.         elif command == 's':
  36.             moveHero(board, hero, (hx+1, hy))
  37.         elif command == 'e':
  38.             moveHero(board, hero, (hx, hy+1))
  39.         elif command == 'w':
  40.             moveHero(board, hero, (hx, hy-1))
  41.         elif command == 'l':
  42.             lootRoom(board, hero)
  43.         elif command == 'r':
  44.             if leaveGame(board, hero):
  45.                 print("You exit the cave and return to town.")
  46.                 if hero.score <= 10:
  47.                     print("The men at the bar call you a pansy as you slink home")
  48.                 elif hero.score <= 25:
  49.                     print("The others at the local bar are excited to hear your story!")
  50.                 elif hero.score <=50 :
  51.                     print("Everyone is riveted by your tale!")
  52.                 elif hero.score < 100:
  53.                     print("The bar fills with the sounds of cheer as you recall your bravery")
  54.                 else:
  55.                     print("The barkeep offers you free drinks for life for your bravery")
  56.                 hero.isAlive = False
  57.             else:
  58.                 print("You can only leave through the cave entrance")
  59.         else:
  60.             print("Invalid Command.  Type ? for help")
  61.         if not hero.isAlive:
  62.             print("**** GAME OVER ****")
  63.             print("You scored {0} points!  Try again!".format(hero.score))
  64.             return True
  65.         print()
  66.  
  67. def leaveGame(board, hero):
  68.     """Attempts to leave the Wumpus Cave"""
  69.     rc = wRoom.roomContents
  70.     x,y = hero.coord
  71.     room = board[x][y]
  72.     if room.roomContents == rc['entrance']:
  73.         return True
  74.     else:
  75.         return False
  76.  
  77. def lootRoom(board, hero):
  78.     """Makes hero try to take the contents of room"""
  79.     rc = wRoom.roomContents
  80.     x,y = hero.coord
  81.     room = board[x][y]
  82.     if room.roomContents == rc['empty']:
  83.         print("There's nothing here")
  84.     elif room.roomContents == rc['treasure']:
  85.         room.roomContents = rc['empty']
  86.         hero.score += points['find_gold']
  87.     elif room.roomContents == rc['weapon']:
  88.         room.roomContents = rc['empty']
  89.         hero.hasWeapon = True
  90.         hero.score += points['find_weapon']
  91.         found_weapon(board)
  92.  
  93. def found_weapon(board):
  94.     """turns all weapon rooms to gold"""
  95.     sizex = len(board)
  96.     sizey = len(board[0])
  97.     rc = wRoom.roomContents
  98.     for x in range(1, sizex):
  99.         for y in range(1, sizey):
  100.             if board[x][y].roomContents == rc['weapon']:
  101.                 board[x][y].roomContents = rc['treasure']
  102.  
  103. def moveHero(board, hero, dest):
  104.     dx, dy = dest
  105.     hx, hy = hero.coord
  106.     destRoom = board[dx][dy]
  107.     currRoom = board[hx][hy]
  108.     rc = wRoom.roomContents
  109.     if destRoom.roomContents == rc['wall']:
  110.         print("You walked straight into a wall.  Were your eyes closed?")
  111.     elif destRoom.roomContents == rc['pit']:
  112.         print("You have fallen in a pit! Better luck next time.")
  113.         hero.isAlive = False
  114.     elif destRoom.roomContents == rc['wumpus']:
  115.         if hero.hasWeapon:
  116.             print("You have killed a Wumpus!")
  117.             hero.score += points['kill_wumpus']
  118.             destRoom.roomContents = rc['empty']
  119.         else:
  120.             print("You have been eaten alive!", end="")
  121.             hero.isAlive = False
  122.     else:
  123.         if destRoom.roomContents == rc['empty']:
  124.             hero.score += points['empty_room']
  125.     currRoom.heroVisiting = False
  126.     destRoom.heroVisiting = True
  127.     destRoom.explored = True
  128.     hero.coord = (dx, dy)
  129.  
  130. def printHelp():
  131.     print(""" Enter a direction (N/S/E/W) to travel that direction
  132. Enter L to pickup treasure/weapons
  133. Enter R to leave the cave if you're at the entrance
  134. Enter ? to display this message
  135. Enter X to hard-quit the game (no score given)
  136.    """)
  137.  
  138. def createBoard(size):
  139.     """Creates a new, random game board that is (size+1)^2 in area (including walls)"""
  140.     boardSize = size+1
  141.     totalRooms = boardSize**2
  142.     #Calculate Room distribution
  143.     roomDist = {
  144.         'entrance':1,
  145.         'wumpus':(size**2)*0.15,
  146.         'treasure':(size**2)*0.15,
  147.         'weapon':(size**2)*0.15,
  148.         'pit':(size**2)*0.05
  149.     }
  150.     #initialize empty board
  151.     gameBoard = [[[] for i in range(boardSize)] for i in range(boardSize)]
  152.     #Create rooms
  153.     for x in range(boardSize):
  154.         for y in range(boardSize):
  155.             if x == 0 or y == 0 or x == size or y == size:
  156.                 gameBoard[x][y] = wRoom(roomContents='wall')
  157.             else:
  158.                 gameBoard[x][y] = wRoom(xcrd=x, ycrd=y)
  159.     #Fill rooms
  160.     rng = random.Random()
  161.     hero = None
  162.     while len(roomDist) > 0:
  163.         x = rng.randint(1,size)
  164.         y = rng.randint(1,size)
  165.         room = gameBoard[x][y]
  166.         if room.roomContents == wRoom.roomContents['empty']:
  167.             keyList = list(roomDist.keys())
  168.             rng.shuffle(keyList)
  169.             key = keyList[0]
  170.             room.roomContents=wRoom.roomContents[key]
  171.             if(key == 'entrance'):
  172.                 hero = wHero(room.coord)
  173.                 room.heroVisiting = True
  174.                 room.explored=True
  175.             roomDist[key] -= 1
  176.             if roomDist[key] <= 0:
  177.                 del roomDist[key]
  178.     #printBoard(gameBoard)
  179.     return (gameBoard, hero)
  180.  
  181. def printRoom(room):
  182.     """Prints information about the room"""
  183.     contents = room.roomContents
  184.     rc = wRoom.roomContents
  185.     if contents == rc['empty']:
  186.         print("This room is empty.  Move along")
  187.     elif contents == rc['treasure']:
  188.         print("Yar!  There be treasure here!")
  189.     elif contents == rc['weapon']:
  190.         print("There's an old weapon in this room")
  191.     elif contents == rc['entrance']:
  192.         print("You're at the entrance.  You can leave if you want.")
  193.  
  194. def printClues(board, coord):
  195.     """Prints environmental clues for board around coord"""
  196.     x,y = coord
  197.     wNear = False
  198.     pNear = False
  199.     rc = wRoom.roomContents
  200.     for i in range(-1,2):
  201.         for k in range(-1,2):
  202.             if board[x+i][y+k].roomContents == rc['wumpus']:
  203.                 wNear = True
  204.             elif board[x+i][y+k].roomContents == rc['pit']:
  205.                 pNear = True
  206.             if wNear and pNear:
  207.                 break
  208.     if wNear:
  209.         print("A foul stench fills the air.  ", end="")
  210.     if pNear:
  211.         print("You hear the wind whistling.", end="")
  212.     if wNear or pNear:
  213.         print()
  214.     pass
  215.  
  216. def printHero(hero):
  217.     """Prints current status of hero"""
  218.     print("[{0} points earned] ".format(hero.score), end="")
  219.     if hero.hasWeapon:
  220.         print("You are armed and dangerous")
  221.     else:
  222.         print("You need to find a weapon!")
  223.  
  224. def printBoard(board):
  225.     """prints entire contents of board"""
  226.     sizex = len(board)
  227.     sizey = len(board[0])
  228.     for x in range(sizex):
  229.         for y in range(sizey):
  230.             board[x][y].write()
  231.         print()
  232.  
  233. def printView(board, coord):
  234.     """prints the 3x3 grid from board around coord"""
  235.     x,y = coord
  236.     view = []
  237.     for i in range(-1,2):
  238.         tmp = board[x+i]
  239.         tmp = tmp[y-1:y+2]
  240.         view.append(tmp)
  241.     printBoard(view)
  242.  
  243. class wRoom:
  244.     """Room Object"""
  245.     roomContents = {
  246.         'empty':0,
  247.         'treasure':1,
  248.         'weapon':2,
  249.         'wumpus':3,
  250.         'pit':4,
  251.         'entrance':5,
  252.         'wall':6
  253.     }
  254.     def __init__(self, roomContents='empty', explored=False, xcrd=0, ycrd=0):
  255.         self.explored = explored
  256.         self.heroVisiting = False
  257.         self.roomContents = wRoom.roomContents[roomContents]
  258.         self.coord=(xcrd, ycrd)
  259.     def write(self):
  260.         """Makes room print itself"""
  261.         roomChar = ""
  262.         if self.roomContents == wRoom.roomContents['wall']:
  263.             roomChar = "#"
  264.         elif not self.explored:
  265.             roomChar = "?"
  266.         elif self.heroVisiting:
  267.             roomChar = "@"
  268.         elif self.roomContents == wRoom.roomContents['entrance']:
  269.             roomChar = "^"
  270.         elif self.roomContents == wRoom.roomContents['weapon']:
  271.             roomChar = "W"
  272.         elif self.roomContents == wRoom.roomContents['treasure']:
  273.             roomChar = "$"
  274.         elif self.roomContents == wRoom.roomContents['wumpus']:
  275.             roomChar = "&"
  276.         elif self.roomContents == wRoom.roomContents['pit']:
  277.             roomChar = "="
  278.         elif self.explored:
  279.             roomChar = "."
  280.         print(roomChar, end='')
  281.  
  282. class wHero:
  283.     """Hero Object"""
  284.     def __init__(self, coord):
  285.         self.hasWeapon=False
  286.         self.coord = coord
  287.         self.score = 0
  288.         self.isAlive=True
  289.  
  290. if __name__ == "__main__":
  291.     main()
Add Comment
Please, Sign In to add comment