Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Dungeon Game Building the Game: Part 1

Chris Nelson
Chris Nelson
4,603 Points

dungeon_game.py player error

Can't figure out why this won't run.

import random

CELLS = [(0, 0), (0, 1), (0, 2),
         (1, 0), (1, 1), (1, 2),
         (2, 0), (2, 1), (2, 2)]

def get_locations():
  monster = random.choice(CELLS)
  door = random.choice(CELLS)
  start = random.choice(CELLS)

  if monster == door or monster == start or door == start:
    return get_locations()
  return monster, door, start


def move_player(player, move):
  x, y = player
  if move == 'LEFT':
    y -= 1
  elif move == 'RIGHT':
    y += 1
  elif move == 'UP':
    x -= 1
  elif move == 'DOWN':
    x += 1
  return x, y


def get_moves(player):
  moves = ['LEFT', 'RIGHT', 'UP', 'DOWN']
  if player[1] == 0:
    moves.remove('LEFT')
  if player[1] == 2:
    moves.remove('RIGHT')
  if player[0] == 0:
    moves.remove('UP')
  if player[0] == 2:
    moves.remove('DOWN')
  return moves

monster, door, start = get_locations()

while True:
  moves = get_moves(player)

  print("Welcome to the dungeon!")
  print("You're currently in room {}".format(player))
  print("You can move {}".format(moves))
  print("Enter QUIT to quit")

  move = input("> ")
  move = move.upper()

  if move == 'QUIT':
    break

  if move in moves:
    player = move_player(player, move)
  else:
    print("** Walls are hard. Stop walking into them! **")
    continue

  if player == door:
    print("You escaped!")
    break
  elif player == monster:
    print("You got eaten, dumbass!")
    break

I get the error: Traceback (most recent call last):
File "dungeon_game.py", line 45, in <module>
moves = get_moves(player)
NameError: name 'player' is not defined

2 Answers

Abhishek Gangadhar
Abhishek Gangadhar
9,467 Points

hey, I thinks there is simple solution

monster, door, start = get_locations()

replace start by player in the above code

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,064 Points

It appears your player's initial position is not defined. One solution would be to add near the top of the code:

player = random.choice(CELLS)