If statement not working properly

Question:
For some reason, the conditions in my if statement are ignored.
Repl link:
https://replit.com/@SnakeyKing/Cells#main.py

...
match key:
    case 'w':
      if (y != 0) and notwall(x, y-1):
        game.change_cell(x, y, EMPTY)
        y -= 1
        game.change_cell(x, y, PLAYER)
    case 's':
      if (y != HEIGHT) and notwall(x, y+1):
        game.change_cell(x, y, EMPTY)
        y += 1
        game.change_cell(x, y, PLAYER)
    case 'a':
      if (x != 0) and notwall(x-1, y):
        game.change_cell(x, y, EMPTY)
        x -= 1
        game.change_cell(x, y, PLAYER)
    case 'd':
      if (x != WIDTH) and notwall(x+1, y):
        game.change_cell(x, y, EMPTY)
        x += 1
        game.change_cell(x, y, PLAYER)

You are not checking the boundaries properly.
Instead of using:

if (y != HEIGHT) ...

You should be using:

if (y != HEIGHT-1) ...

The same applies to WIDHT

In programming, it’s common to follow certain procedures when you index lists (or arrays).

For example, in Python, list indices start at 0, not 1. So, for a list of lenght β€œn”, the first item is at index β€œ0” and the last item is at index β€œn-1”.

1 Like

I already figured that out, but thanks.
btw, I have problems with the notwall conditions as well

Probably because you are referencing the global variables.

Try to use the variable you pass into the function

Just change this part:

return (game.get_cell(_x, _y) != '#')

oh, I made a typo.
Thanks for the help!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.