I am following a tutorial using curses to make the snake game. I wanted to use match/case instead of if/else statements to detect key presses.
key = win.getch()
match key:
case ord("q"): # => "TypeError: called match pattern must be a type"
sys.exit("Game terminated by user.")
case curses.KEY_RIGHT:
snakehead = (snake[0][0], snake[0][1] + 1)
case curses.KEY_LEFT:
snakehead = (snake[0][0], snake[0][1] - 1)
case ord("q")
raises a TypeError, but if I replace with case 113
it works.
ord("q") == 113
evaluates as True
.
I can get the key press to work by making a conditional statement outside the match/case with if key == ord("q")
, but I still would like to find the reason for the exception.
In Python, the ord function is used to convert a character to its corresponding Unicode integer representation. The match statement, on the other hand, requires all cases to have the same pattern, which means that the values used in the cases need to be integers.
Since curses.KEY_RIGHT is already an integer variable, it is suitable for use in the match statement. However, ord is a function, not an integer, so it cannot be used directly in the match statement.
A solution to this is to use a class namespace. In your case it would be:
class SpecialCode:
QUIT = ord('q')
key = win.getch()
match key:
case SpecialCode.QUIT:
sys.exit("Game terminated by user.")
case curses.KEY_RIGHT:
snakehead = (snake[0][0], snake[0][1] + 1)
case curses.KEY_LEFT:
snakehead = (snake[0][0], snake[0][1] - 1)