I create the snake game with python and curses library. However I found the bug in the program. When pressing the key repeatedly, the snake move faster. Here is some part the code
# standard initialization
s = curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.noecho()
curses.curs_set(0)
sh, sw = 30, 60
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
w.nodelay(1)
#Snake moving loop
while True:
next_key = w.getch()
#Check if user is pressing the key or not, or pressing the opposite direction key
if (next_key == -1):
key = key
elif (key == curses.KEY_DOWN and next_key == curses.KEY_UP) or (key == curses.KEY_UP and next_key == curses.KEY_DOWN):
key = key
elif (key == curses.KEY_LEFT and next_key == curses.KEY_RIGHT) or (key == curses.KEY_RIGHT and next_key == curses.KEY_LEFT):
key = key
else:
key = next_key
#Current location of the head
new_head = [snake[0][0], snake[0][1]]
#moving up, down,left,right according to the key
if key == curses.KEY_DOWN:
new_head[0] += 1
if key == curses.KEY_UP:
new_head[0] -= 1
if key == curses.KEY_LEFT:
new_head[1] -= 1
if key == curses.KEY_RIGHT:
new_head[1] += 1
snake.insert(0, new_head)
I think it is because the getch() get called many time as the key is pressed and get into the moving loop without waiting for the timeout.
I tried curses.napms(100),curses.cbreak(1),curses.halfdelay(1) nothing work.