Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Can someone help me with the code for the dd_game.py for the logging portion of the course?

I am having problems getting the code for the dd_game.py to run without errors. I fix something and then something else goes south. Is it possible to download the code from somewhere or print it off to avoid the headaches?

Thank you

Bob

Here is the code:

import logging
import random

logging.info("You won't see this")
logging.warn("OH NO")

player = {'location': None, 'path': []}
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:
        monster, door, start = get_locations()

    return monster, door, start


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

def move_player(player, move):
    x, y = player['location']
    player['path'].append((x, y))
    if move == 'LEFT':
        player['location'] = x, y - 1
    elif move == 'UP':
        player['location'] = x -1 , y
    elif move == 'RIGHT':
        player['location'] = x, y = 1
    elif move == 'DOWN':
        player['location'] = x + 1, y

def draw_map(player):
    print(' _ _ _')
    tile = '|{}'
    for idx, cell in enumerate(cells):
        if idx in [0, 1, 3, 4, 6, 7]:
            if cell == player['location']:
                print(tile.format('X'), end='')
            elif cell in player['path']:
                print(tile.format('.'), end='')
            else:
                print(tile.format('_'), end='')
        else:
            if cell == player:
                print(tile.format('X|'))
            elif cell in player['path']:
                print(tile.format('.|'))
        else:
            print(tile.format('_|'))

monster, door, player = get_locations()

print("Welcome to the dungeon!")

while True:
  moves = get_moves(player)

  print("You're in room {}".format(player)) # fill in with player position

  draw_map(player)

  print("You can move {}".format(moves)) # fill in with available 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've escaped!")
    break
  elif player == monster:
    print("You were eaten by the grue!")
    break

    # If it is a good move change the player's position
    # If it is a bad move, don't change anything
    # If the new player postion is the door, they win!
    # If a new player postion is the monster they lose!
    # Otherwise, continue

The errors are coming from this particular section of the dd_game.py script, with the first error showing up as a formatting error for: print(tile.format('X'), end='') and the last else: the error is a tab error. I thought I had it all entered as in the video.

Thank you for your help! B0b

def draw_map():
    print(' _ _ _')
    tile = '|{}'
    for idx, cell in enumerate(cells):
        if idx in [0, 1, 3, 4, 6, 7]:
            if cell == player['location']:
                print(tile.format('X'), end='')
            elif cell in player['path']:
                print(tile.format('.'), end='')
            else:
                print(tile.format('_'), end='')
        else:
            if cell == player:
                print(tile.format('X|'))
            elif cell in player['path']:
                print(tile.format('.|'))
        else:
                print(tile.format('_|'))

Hi Robert Skoubo, just letting you know I've just added the syntax highlighting and proper code formatting to your question and comment.

I'm confused though, are you still needing a response or did you figure this one out?

Iain, this script is still giving me challenges. I copied it onto my Linux system and I am getting a lot of tab errors. That may be part of the problem. It has not been an issue before this though. It seems that fixing one error results in another.

I am not sure what is going with the code. I haven't run into this one yet.

Thank you for your help.

Bob

1 Answer

So, a few things I've noticed after going through your code:

You're using the player variable as a dictionary but you haven't updated the code everywhere to reflect that.

Specifically, your get_moves function is trying to look for the entire player dictionary in the lists (which should be referencing the existing cells list, remember DRY: Don't Repeat Yourself!), rather than the value of player['location'].

The same goes for when you use the get_locations function to assign the initial values to monster, door and player. You should change the last variable to player['location'].

Also within the while loop, the first format and the last if/else should reference player['location'].

And finally, for the draw_map function, you should have one outer if and else, each with an if, elif and else within them (the last else should have the same indentation as the elif before it). Also, the if cell == player: in the outer else group should be if cell == player['location']: to function correctly.

I've tried to avoid writing out all the correct code for you, so see how you go fixing things yourself. I think you'll have a better understanding of what is going on if you fix it yourself.

Good luck!

Thank you very much, Iain! I will check it out as soon as possible. I have also noticed that I seem to have cascading indent errors after the code I pointed out in the second post. I would fix one and another would appear just below it. It is all fun and I will let you know as soon as I have time to get back to it.

Thanks again! Bob

Iain, Thank you again for your help. I found out that one of my problems that kept showing up in Workspaces was the use of tabs and spaces. That caused me a lot of grief. I had worked on the script in both my editor and Wokspaces and if I remember correctly, I copied and pasted from Genie into Wokspaces - the wrong thing to do. That is where the spaces verses tabs issue came into play. Once I got that to work I missed an additional tab or extra spaces in front of one of the returns and I worked on that one for almost two hours before I found it.

I apologize for not getting back with you sooner and not getting the "Best Answer'" checked for you. I had too many irons in the fire and too much OFD - Old Fart's Disease.

Take care! Thanks again, tool

Bob