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

victor escarcega
victor escarcega
5,439 Points

not sure what im missing with these tuples

what am i missing?

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

    if direction == 'LEFT':
        if x == 0:
            hp -= 5
            x = 0
        else:
            x -=1

    if direction == 'RIGHT':
        if x == 9:
            hp -= 5
            x = 9
        else:
            x +=1
    if direction == 'UP':
        if y == 0:
            hp -= 5
            y = 0
        else:
            y -=1
    if direction == 'DOWN':
        if y == 9:
            hp -= 5
            y = 9
        else:
            y +=1

    return x, y, hp

1 Answer

Josh Keenan
Josh Keenan
17,364 Points

Pasting in the last time I answered this:

Here's my solution to this:

def move(player, direction):
    x, y, hp = player
    x += direction[0]
    y += direction[1]
    if x > 9:
        x = 9
        hp -= 5
    elif x < 0:
        x = 0
        hp -= 5

    if y > 9:
        y = 9
        hp -= 5
    elif y < 0:
        y = 0
        hp -=5

    return x, y, hp

So all that needs to be done is to check if the player is leaving the permitted area. To do this we need to take the new movements and add them to the current position, if they are negative they will go down, if it is positive it will be added fine.

After that we need to check if the player is still on the board, if not we need to put them back on it, they will be off the board if one of four conditions are met, the x or y is above 9, or the x or y is below 0. So we test for them, but since it can't be both greater and less than the limit on any one axis, we can use and if/elif clause without an else, as we don't need to do anything in the situation that none of these conditions are met.

Hope this makes sense and helps, feel free to ask any questions!

victor escarcega
victor escarcega
5,439 Points

thank you this really simplified it.