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

Move function code challenge: need help understanding what is wrong or required.

Here is the code i gave:

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

x += a
if x < 0:
    hp -= 5
    x = 0  # also tried x -= a
elif x > 9:
    hp -= 5 
    x = 9 # also tried x -= a
else:
    y += b 
    if y < 0:
        hp -= 5
        y = 0 # also tried y -= a

    elif y > 9:
        hp -= 5
        y = 9 # also tried y -= a


return x, y, hp

1 Answer

diogorferreira
diogorferreira
19,363 Points

Hello, the only problem with your code is that you're checking the player's current position instead of where they are trying to move to.

  • In this case to make it easier to understand I renamed your (a, b) variables into xdir and ydir (x - direction, y - direction).
  • After setting the variables you have to check if the player wants to move left or right, (if xdir is -1 or 1)
  • Then to make sure they don't cross the invisible border and leave the game so you'd have to check if they are on 0, or 9 as moving left on 0 would mean they exit and are moved to -1 and so on...
  • If it's a valid move then apply the change to their current position on x
  • You re-do the same thing for y
  • And finally return it
def move(player, direction):
    x, y, hp = player
    xdir, ydir = direction

    #Checking whether it moves right or left
    #-1 moves left, 1 moves right
    if xdir == -1:
        if x != 0:
            x -= 1
        else:
            hp -= 5

    elif xdir == 1:
        if x != 9:
            x += 1
        else:
            hp -= 5

    #Checking whether it moves up or down
    #-1 moves down, 1 moves up
    if ydir == -1:
        if y != 0:
            y -= 1
        else:
            hp -= 5

    elif ydir == 1:
        if y != 9:
            y += 1
        else:
            hp -= 5

    #Sending back the changed positions and hp
    return x, y, hp