Advertisement
HawkenJ

Untitled

Mar 28th, 2014
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.99 KB | None | 0 0
  1. # Reddit Daily Programmer #154, Hard
  2. # Wumpus (Rogue-like text game)
  3.  
  4. # Imports
  5.  
  6. import random
  7. import copy
  8.  
  9. # Constants
  10.  
  11. MESSAGES = {
  12.     "^": "You see see the entrance here. You wish to run away?",
  13.     ".": "You see nothing which is something.",
  14.     "P": "AAAAAAAAAaaaaaaaaaaaaaaaaaaaaahhhhhhhhhh noooooooooooooooooo.... Splat",
  15.     "W": "Overwhelmed in Stench a Wumpus stands before you ready to eat you.",
  16.     "$": "Before you lies the the gold of adventure seekers who feed a Wumpus recently.",
  17.     "K": "Cast before you in a rock a sword awaits to be looted and name yourself King."
  18. }
  19.  
  20. # Functions
  21.  
  22. def welcome():
  23.     print("""                   ---WUMPUS CAVE GAME---
  24.  
  25. Beware the Wumpus. For it slumbers in the cave up yonder in the hills.
  26.  
  27. Only the brave seek him.
  28.  
  29. """)
  30. def cave_generator():
  31.     """Returns:
  32.        A cave (nested list) full unknown squares ("?"), with walls ("#")
  33.        A completed cave with all rooms generated (also with walls)
  34.        An int to represent start position - number of squares down from the top
  35.        Another int representing number of squares in from the side
  36.    """
  37.     cave, cave_size = empty_cave_generator()
  38.     cave = wall_generator(cave, cave_size)
  39.     cave_copy = copy.deepcopy(cave)
  40.     complete_cave = room_generator(cave_copy)
  41.     down, across, cave, complete_cave = start_point(cave, complete_cave, cave_size)
  42.     return cave, complete_cave, down, across
  43.    
  44. def empty_cave_generator():
  45.     """Prompts user for int 10-20 and creates nested lists of "." in the appropriate size
  46.   If user is not feeling cooperative, returns a nested list of maximum size :)"""
  47.     invalid_entries = 0
  48.     try:
  49.         cave_size = int(input("Enter cave size from 10-20: "))
  50.     except ValueError:
  51.         cave_size = 0
  52.     while (not 10<= cave_size <= 20):
  53.         try:
  54.             cave_size = int(input("Invalid input. Please enter cave size from 10-20: "))
  55.         except ValueError:
  56.             cave_size = 0
  57.         invalid_entries += 1
  58.         if invalid_entries == 3:
  59.             print("\nYour lack of cooperation has angered the Gods. You trip and fall into a massive cave.")
  60.             cave_size = 20
  61.     cave = [["?"]*cave_size for i in range(cave_size)]
  62.     return cave, cave_size
  63.    
  64. def wall_generator(cave, cave_size):
  65.     """Puts a square of "#" around the grid"""
  66.     for i in range(cave_size):
  67.         cave[i].insert(0, "#")
  68.         cave[i].append("#")
  69.     cave.insert(0, ["#"] * (cave_size + 2))
  70.     cave.append(["#"] * (cave_size + 2))
  71.     return cave
  72.    
  73. def room_generator(cave):
  74.     """Distributes rooms randomly. 5% chance of pitfall, 15% chance of gold,
  75.    15% chance of weapon (marked as K), 15% chance of a wumpus"""
  76.     for line in range(len(cave)):
  77.         for item in range(len(cave)):
  78.             if cave[line][item] == "?":
  79.                 rnd = random.randint(0,20)
  80.                 if rnd < 1:
  81.                     cave[line][item] = "P"
  82.                 elif rnd < 4:
  83.                     cave[line][item] = "$"
  84.                 elif rnd < 7:
  85.                     cave[line][item] = "K"
  86.                 elif rnd < 10:
  87.                     cave[line][item] = "W"
  88.                 else:
  89.                     cave[line][item] = "."
  90.             else:
  91.                 pass
  92.     return cave
  93.  
  94. def start_point(cave, complete_cave, cave_size):
  95.     """Picks a start point in the cave, shown as a "^\""""
  96.     down = random.randint(1, cave_size)
  97.     across = random.randint(1, cave_size)
  98.     cave[down][across] = "^"
  99.     complete_cave[down][across] = "^"
  100.     return down, across, cave, complete_cave
  101.  
  102. def enter_room(down, across):
  103.     """Shows the player their location, prints a message about the room and
  104.    if necessary runs the appropriate functions (ie. pitfall, wumpus)"""
  105.     cave_map[down][across] = complete_cave[down][across]
  106.     cave_printer(down, across)
  107.     print(MESSAGES[complete_cave[down][across]])
  108.     if cave_map[down][across] == "P":
  109.         pitfall()
  110.         return
  111.     elif cave_map[down][across] == "W":
  112.         wumpus()
  113.     if not dead:
  114.         neighbour_check(down, across)
  115.         print("Points :", points, "\n")
  116.  
  117. def cave_printer(down, across):
  118.     """Prints the 3x3 square around the player. Marks the player on the map as @"""
  119.     print("\n", "".join(cave_map[down-1][across-1:across+2]), sep = "")
  120.     print(cave_map[down][across-1]+"@"+cave_map[down][across+1])
  121.     print("".join(cave_map[down+1][across-1:across+2]), end = "\n\n")
  122.    
  123.  
  124. def neighbour_check(down, across):
  125.     """Checks each adjacent square for a wumpus or a pitfall"""
  126.     if "W" in [complete_cave[down+1][across], complete_cave[down-1][across], complete_cave[down][across+1], complete_cave[down][across-1]]:
  127.         print("You detect a foul stench in the air")
  128.     if "P" in [complete_cave[down+1][across], complete_cave[down-1][across], complete_cave[down][across+1], complete_cave[down][across-1]]:
  129.         print("You hear a howling wind")
  130.  
  131. def loot(down, across, weapon, points):
  132.     """Take the gold/ weapons from a room. Sends the location to change_item to update
  133.    the square. Updates the points value."""
  134.     if cave_map[down][across] == "K":
  135.         if weapon == False:
  136.             print("You take the weapon and feel ready to take on anything!")
  137.             points += 5
  138.             change_item(".", down, across)
  139.             remove_weapons_from_map()
  140.         else:
  141.             print("You already have one of these... Perhaps you should have picked this up before.")
  142.         return(True, points)
  143.     elif cave_map[down][across] == "$":
  144.         print("Yoink!")
  145.         points += 5
  146.         change_item(".", down, across)
  147.         return weapon, points
  148.     else:
  149.         print("Nothing to loot!")
  150.         return weapon, points
  151.  
  152. def change_item(new_item, down, across, hidden = False):
  153.     """Turns item at location given into new_item. If hidden is True, this
  154.    leaves the item as "?" on the cave map, but changes the item in the complete
  155.    cave."""
  156.     global cave_map
  157.     global complete_cave
  158.     complete_cave[down][across] = new_item
  159.     if not hidden:
  160.         cave_map[down][across] = new_item
  161.  
  162. def remove_weapons_from_map():
  163.     """Checks nested lists for undiscovered weapons: sends them to change_item
  164.    to be turned into gold!"""
  165.     for i in range(len(cave_map)):
  166.         for j in range(len(cave_map)):
  167.             if cave_map[i][j] == "?" and complete_cave[i][j] == "K":
  168.                 change_item(".", i, j, hidden = True)
  169.  
  170. def move(direction, down, across, points):
  171.     """Checks that move is valid (ie. not moving into a wall), then returns
  172.    new position and adds a point if the position was previously undiscovered"""
  173.     if direction == "N":
  174.         if cave_map[down-1][across] != "#":
  175.             if cave_map[down-1][across] == "?":
  176.                 points += 1
  177.             return down-1, across, points
  178.     elif direction == "S":
  179.         if cave_map[down+1][across] != "#":
  180.             if cave_map[down+1][across] == "?":
  181.                 points += 1
  182.             return down+1, across, points
  183.     elif direction == "E":
  184.         if cave_map[down][across+1] != "#":
  185.             if cave_map[down][across+1] == "?":
  186.                 points += 1
  187.             return down, across+1, points
  188.     elif direction == "W":
  189.         if cave_map[down][across-1] != "#":
  190.             if cave_map[down][across-1] == "?":
  191.                 points += 1
  192.             return down, across-1, points
  193.     print("\nYou try and dig your way out through the wall, but to no avail.\
  194.    \nTry moving a different way...")
  195.     return down, across, points
  196.  
  197. def pitfall():
  198.     """I think you get the idea..."""
  199.     global dead
  200.     dead = "You fell to your death."
  201.  
  202. def wumpus():
  203.     """If you have a weapon, you slay the wumpus. Otherwise, you dead."""
  204.     global points
  205.     global dead
  206.     if weapon:
  207.         print("You destroy the wumpus!")
  208.         change_item(".", down, across)
  209.         points += 10
  210.     else:
  211.         dead = "A wumpus attacked you and turned you into lunch."
  212.         print("\nAAAAAARGHHH.... \n\n...chomp chomp chomp")
  213.  
  214. def run():
  215.     if cave_map[down][across] == "^":
  216.         global dead
  217.         dead = "You ran away. Through cowardice or boredom, we will never know."
  218.     else:
  219.         print("Running away only works at the cave entrance!")
  220.  
  221. def game_over():
  222.     """Text summary to end the game"""
  223.     print("***GAME OVER***", dead, "You scored ", sep = "\n", end = "")
  224.     if points == 1:
  225.         print("1 whole point!")
  226.     elif points < 10:
  227.         print(str(points) + ". A disappointing result.")
  228.     elif points < 30:
  229.         print(str(points) + "! Nice work")
  230.     else:
  231.         print(str(points) + "!! Wumpuses will be glad not to see you again.")
  232.    
  233. def help_menu():
  234.     print("""
  235. All commands must be followed by the return key.
  236.  
  237. Press N to move North
  238. Press E to move East
  239. Press S to move South
  240. Press W to move West
  241. Press L to Loot weapons or gold
  242. Press R to Run. This only works at cave entrance (where you started, marked as ^)
  243. Press X to exit at any time
  244. """)
  245.  
  246. # Main
  247.  
  248. welcome()
  249. cave_map, complete_cave, down, across = cave_generator()
  250. weapon = False
  251. dead = False
  252. points = 0
  253. user_input = ""
  254.  
  255. cave_printer(down, across)
  256. print("You stand, trembling and weaponless, about to start your adventure")
  257. neighbour_check(down, across)
  258.  
  259. while user_input != "X" and not dead:
  260.     user_input = input("Make your move: ").upper()
  261.     while user_input not in ["N", "E", "S", "W", "R", "L", "?", "X"]:
  262.         print("Input not recognised. Press ? followed by return for help.")
  263.         user_input = input("Make your move: ").upper()
  264.     if user_input == "?":
  265.         help_menu()
  266.     elif user_input in ["N", "E", "S", "W"]:
  267.         down, across, points = move(user_input, down, across, points)
  268.     elif user_input == "L":
  269.         weapon, points = loot(down, across, weapon, points)
  270.     elif user_input == "R":
  271.         run()
  272.     elif user_input == "X":
  273.         dead = "Hopelessly lost, you decided to end it all."
  274.     if not dead:
  275.         enter_room(down, across)
  276.    
  277. game_over()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement