Python Python Collections (2016, retired 2019) Dungeon Game Hit points

Al Craig
Al Craig
20,305 Points

Hitting a wall...

Why doesn't this work?

Our game's player only has two attributes, x and y coordinates. Let's practice with a slightly different one, though. This one has x, y, and "hp", which stands for hit points. Our move function takes this three-part tuple player and a direction tuple that's two parts, the x to move and the y (like (-1, 0) would move to the left but not up or down). Finish the function so that if the player is being run into a wall, their hp is reduced by 5. Don't let them go past the wall. Consider the grid to be 0-9 in both directions. Don't worry about keeping their hp above 0 either.

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
    dx, dy = direction  #Unpacks directions (player can move x or y but not both)
    x += dx             #Sets new x
    y += dy             #Sets new y
    if 0 > x > 9:       #Checks x bounds
        hp -= 5         #Applies damage if hit wall
        x -= dx         #Resets x in bounds if hit wall
    if 0 > y > 9:       #Checks y bounds
        hp -= 5         #Applies damage if hit wall
        y -= dy         #Resets y in bounds if hit wall
    return (x, y, hp)   #Returns player tuple

4 Answers

Louise St. Germain
Louise St. Germain
17,948 Points

Hi Al,

You're almost there - but try two separate comparisons for what you want to do. The general format (0 < x < 9) is for determining whether your value falls in a single range between two other numbers, but in this case you're checking two separate ranges: the numbers below 0, and those above 9.

# try this:
if x < 0 or x > 9:

# instead of this:
if 0 > x > 9:

Hope this helps!

Baruch Zeif
Baruch Zeif
7,242 Points

You've gotten pretty close! If I'm reading it correctly, 0 > x > 9 looks like that would read 0 is greater than x which is greater than 9. It looks to me like you tried writing it together but you may have to use an or.

Al Craig
Al Craig
20,305 Points

Thanks for your help guys - much appreciated!

Hey Al Craig, you don't know this, but by posting your question, you've helped me write a more compact solution! I credit you with this inspiration:

# new code
def move(coordinates, change):
    x, y, hp = coordinates
    dx, dy = change
    x += dx
    y += dy
    if x < 0 or x > 9:
        hp -= 5
        x -= dx
    elif y < 0 or y > 9:
        hp -= 5
        y -= dy
    return x, y, hp

# old code
# ...
#     if x < 0:
#         x = 0
#         hp -= 5
#     elif y < 0:
#         y = 0
#         hp -= 5
#     if x > 9:
#         x = 9
#         hp -= 5
#     elif y > 9:
#         y = 9
#         hp -= 5
#     return x, y, hp

Thanks!