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 Python Collections (2016, retired 2019) Dungeon Game Hit points

MONTRIAL HARRELL
seal-mask
.a{fill-rule:evenodd;}techdegree
MONTRIAL HARRELL
Python Web Development Techdegree Student 2,150 Points

Why is my movement.py code failing?

My movement.py code is failing and I can not figure out why. I have tried printing the incoming parameters and they appear to be coming in as 0 for x and -1 for y and not the actual parameters supplied. I really need help and thank you in advance.

movement.py
# EXAMPLES:
# move((1, 1, 10), (-1, 0)) => (0, 1, 10)
# move((0, 1, 10), (-1, 0)) => (0, 1, 5)
# move((0, 9, 5), (0, 1)) => (0, 9, 0)

def move(player, direction):

    x,y,hp = player
    x1,y1 = direction

    while True:

        if x == 0 and x1 == -1:
            hp -= 5
            break
        if x == 9 and x1 == 1:
            hp -= 5
            break
        if y == 0 and y1 == -1:
            hp -= 5
            break
        if y == 9 and y1 == 1:
            hp -= 5
            break
        if x1 == -1:
            x -= 1
        if x1 == 1:
            x += 1
        if y1 == -1:
            y -=1
        if y1 == 1:
            y += 1
    return(x,y,hp)

2 Answers

Eric M
Eric M
11,546 Points

Consider this function to be handling a single key press, it probably gets executed every game loop, which is quite often. So when a player hits a key they don't expect their character to continue in that direction until they hit a wall.

As it stands your code will not break out of the while loop until a collision occurs.

As you're using the breaks to get to your return, why not just return on your conditional branches?

def move(player, direction):
    x, y, hp = player

    #handle left collision
    if direction[0] < 0 and x == 0:
        return(x, y, hp - 5)

    #handle right collision
    if direction[0] > 0 and x == 9:
        return(x, y, hp - 5)

    #handle up collision
    if direction[1] > 0 and y == 9:
        return(x, y, hp - 5)

    #handle down collision
    if direction[1] < 0 and y == 0:
        return(x, y, hp - 5)

    #handle valid move
    return x + direction[0], y + direction[1], hp