Snake game has a fixed time for a keypress. If you press any button in that time, the snake should move in that direction otherwise continue moving in the previous direction. Sadly, with OpenCV cv2.waitKey() function, if you hold down the left direction button, the snake starts moving fast in that direction. So, to make the snake movement uniform, i did something like this.

1

2

3

4

5

6

7

t_end=time.time()+0.2

k=-1

whiletime.time()<t_end:

ifk==-1:

k=cv2.waitKey(125)

else:

continue

Because cv2.waitKey() returns -1 when no key is pressed, so this ‘k’ stores the first key pressed in that time. Because the while loop is for a fixed time, so it doesn’t matter how fast you pressed a key. It will always wait a fixed time.

Snake cannot move backward: Here, I have used the w, a, s, d controls for moving the snake. If the snake was moving right and we pressed the left button, it will continue moving right or in short snake cannot directly move backwards.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

# 0-Left, 1-Right, 3-Up, 2-Down, q-Break

# a-Left, d-Right, w-Up, s-Down

ifk==ord('a')andprev_button_direction!=1:

button_direction=0

elifk==ord('d')andprev_button_direction!=0:

button_direction=1

elifk==ord('w')andprev_button_direction!=2:

button_direction=3

elifk==ord('s')andprev_button_direction!=3:

button_direction=2

elifk==ord('q'):

break

else:

button_direction=button_direction

After seeing which direction button is pressed, we change our head position