Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!python3
- #Python implementation of a Wumpus Hunt game as specified on
- #http://www.reddit.com/r/dailyprogrammer/comments/21kqjq/4282014_challenge_154_hard_wumpus_cave_game/
- import random
- points = {
- 'empty_room':1,
- 'find_weapon':5,
- 'find_gold':5,
- 'kill_wumpus':10
- }
- def main():
- cavesize =int(input("How large is the wumpus cave? (in square units): "))
- while(newGame(cavesize)):
- cavesize = int(input("How large is the wumpus cave? (in square units): "))
- def newGame(cavesize):
- """Initialize a new game"""
- board, hero = createBoard(cavesize)
- while(True):
- printView(board, hero.coord)
- #printBoard(board)
- hx,hy = hero.coord
- room=board[hx][hy]
- printRoom(room)
- printClues(board, hero.coord)
- printHero(hero)
- command = input("Enter Move (? for help) >").lower()
- if command == 'x':
- return False
- elif command == '?':
- printHelp()
- elif command == 'n':
- moveHero(board, hero,(hx-1, hy))
- elif command == 's':
- moveHero(board, hero, (hx+1, hy))
- elif command == 'e':
- moveHero(board, hero, (hx, hy+1))
- elif command == 'w':
- moveHero(board, hero, (hx, hy-1))
- elif command == 'l':
- lootRoom(board, hero)
- elif command == 'r':
- if leaveGame(board, hero):
- print("You exit the cave and return to town.")
- if hero.score <= 10:
- print("The men at the bar call you a pansy as you slink home")
- elif hero.score <= 25:
- print("The others at the local bar are excited to hear your story!")
- elif hero.score <=50 :
- print("Everyone is riveted by your tale!")
- elif hero.score < 100:
- print("The bar fills with the sounds of cheer as you recall your bravery")
- else:
- print("The barkeep offers you free drinks for life for your bravery")
- hero.isAlive = False
- else:
- print("You can only leave through the cave entrance")
- else:
- print("Invalid Command. Type ? for help")
- if not hero.isAlive:
- print("**** GAME OVER ****")
- print("You scored {0} points! Try again!".format(hero.score))
- return True
- print()
- def leaveGame(board, hero):
- """Attempts to leave the Wumpus Cave"""
- rc = wRoom.roomContents
- x,y = hero.coord
- room = board[x][y]
- if room.roomContents == rc['entrance']:
- return True
- else:
- return False
- def lootRoom(board, hero):
- """Makes hero try to take the contents of room"""
- rc = wRoom.roomContents
- x,y = hero.coord
- room = board[x][y]
- if room.roomContents == rc['empty']:
- print("There's nothing here")
- elif room.roomContents == rc['treasure']:
- room.roomContents = rc['empty']
- hero.score += points['find_gold']
- elif room.roomContents == rc['weapon']:
- room.roomContents = rc['empty']
- hero.hasWeapon = True
- hero.score += points['find_weapon']
- found_weapon(board)
- def found_weapon(board):
- """turns all weapon rooms to gold"""
- sizex = len(board)
- sizey = len(board[0])
- rc = wRoom.roomContents
- for x in range(1, sizex):
- for y in range(1, sizey):
- if board[x][y].roomContents == rc['weapon']:
- board[x][y].roomContents = rc['treasure']
- def moveHero(board, hero, dest):
- dx, dy = dest
- hx, hy = hero.coord
- destRoom = board[dx][dy]
- currRoom = board[hx][hy]
- rc = wRoom.roomContents
- if destRoom.roomContents == rc['wall']:
- print("You walked straight into a wall. Were your eyes closed?")
- elif destRoom.roomContents == rc['pit']:
- print("You have fallen in a pit! Better luck next time.")
- hero.isAlive = False
- elif destRoom.roomContents == rc['wumpus']:
- if hero.hasWeapon:
- print("You have killed a Wumpus!")
- hero.score += points['kill_wumpus']
- destRoom.roomContents = rc['empty']
- else:
- print("You have been eaten alive!", end="")
- hero.isAlive = False
- else:
- if destRoom.roomContents == rc['empty']:
- hero.score += points['empty_room']
- currRoom.heroVisiting = False
- destRoom.heroVisiting = True
- destRoom.explored = True
- hero.coord = (dx, dy)
- def printHelp():
- print(""" Enter a direction (N/S/E/W) to travel that direction
- Enter L to pickup treasure/weapons
- Enter R to leave the cave if you're at the entrance
- Enter ? to display this message
- Enter X to hard-quit the game (no score given)
- """)
- def createBoard(size):
- """Creates a new, random game board that is (size+1)^2 in area (including walls)"""
- boardSize = size+1
- totalRooms = boardSize**2
- #Calculate Room distribution
- roomDist = {
- 'entrance':1,
- 'wumpus':(size**2)*0.15,
- 'treasure':(size**2)*0.15,
- 'weapon':(size**2)*0.15,
- 'pit':(size**2)*0.05
- }
- #initialize empty board
- gameBoard = [[[] for i in range(boardSize)] for i in range(boardSize)]
- #Create rooms
- for x in range(boardSize):
- for y in range(boardSize):
- if x == 0 or y == 0 or x == size or y == size:
- gameBoard[x][y] = wRoom(roomContents='wall')
- else:
- gameBoard[x][y] = wRoom(xcrd=x, ycrd=y)
- #Fill rooms
- rng = random.Random()
- hero = None
- while len(roomDist) > 0:
- x = rng.randint(1,size)
- y = rng.randint(1,size)
- room = gameBoard[x][y]
- if room.roomContents == wRoom.roomContents['empty']:
- keyList = list(roomDist.keys())
- rng.shuffle(keyList)
- key = keyList[0]
- room.roomContents=wRoom.roomContents[key]
- if(key == 'entrance'):
- hero = wHero(room.coord)
- room.heroVisiting = True
- room.explored=True
- roomDist[key] -= 1
- if roomDist[key] <= 0:
- del roomDist[key]
- #printBoard(gameBoard)
- return (gameBoard, hero)
- def printRoom(room):
- """Prints information about the room"""
- contents = room.roomContents
- rc = wRoom.roomContents
- if contents == rc['empty']:
- print("This room is empty. Move along")
- elif contents == rc['treasure']:
- print("Yar! There be treasure here!")
- elif contents == rc['weapon']:
- print("There's an old weapon in this room")
- elif contents == rc['entrance']:
- print("You're at the entrance. You can leave if you want.")
- def printClues(board, coord):
- """Prints environmental clues for board around coord"""
- x,y = coord
- wNear = False
- pNear = False
- rc = wRoom.roomContents
- for i in range(-1,2):
- for k in range(-1,2):
- if board[x+i][y+k].roomContents == rc['wumpus']:
- wNear = True
- elif board[x+i][y+k].roomContents == rc['pit']:
- pNear = True
- if wNear and pNear:
- break
- if wNear:
- print("A foul stench fills the air. ", end="")
- if pNear:
- print("You hear the wind whistling.", end="")
- if wNear or pNear:
- print()
- pass
- def printHero(hero):
- """Prints current status of hero"""
- print("[{0} points earned] ".format(hero.score), end="")
- if hero.hasWeapon:
- print("You are armed and dangerous")
- else:
- print("You need to find a weapon!")
- def printBoard(board):
- """prints entire contents of board"""
- sizex = len(board)
- sizey = len(board[0])
- for x in range(sizex):
- for y in range(sizey):
- board[x][y].write()
- print()
- def printView(board, coord):
- """prints the 3x3 grid from board around coord"""
- x,y = coord
- view = []
- for i in range(-1,2):
- tmp = board[x+i]
- tmp = tmp[y-1:y+2]
- view.append(tmp)
- printBoard(view)
- class wRoom:
- """Room Object"""
- roomContents = {
- 'empty':0,
- 'treasure':1,
- 'weapon':2,
- 'wumpus':3,
- 'pit':4,
- 'entrance':5,
- 'wall':6
- }
- def __init__(self, roomContents='empty', explored=False, xcrd=0, ycrd=0):
- self.explored = explored
- self.heroVisiting = False
- self.roomContents = wRoom.roomContents[roomContents]
- self.coord=(xcrd, ycrd)
- def write(self):
- """Makes room print itself"""
- roomChar = ""
- if self.roomContents == wRoom.roomContents['wall']:
- roomChar = "#"
- elif not self.explored:
- roomChar = "?"
- elif self.heroVisiting:
- roomChar = "@"
- elif self.roomContents == wRoom.roomContents['entrance']:
- roomChar = "^"
- elif self.roomContents == wRoom.roomContents['weapon']:
- roomChar = "W"
- elif self.roomContents == wRoom.roomContents['treasure']:
- roomChar = "$"
- elif self.roomContents == wRoom.roomContents['wumpus']:
- roomChar = "&"
- elif self.roomContents == wRoom.roomContents['pit']:
- roomChar = "="
- elif self.explored:
- roomChar = "."
- print(roomChar, end='')
- class wHero:
- """Hero Object"""
- def __init__(self, coord):
- self.hasWeapon=False
- self.coord = coord
- self.score = 0
- self.isAlive=True
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment