import curses from random import randint # initialize screen curses.initscr() win = curses.newwin(20, 60, 0, 0) win.keypad(1) curses.noecho() curses.curs_set(0) win.border(0) win.nodelay(1) # initialize snake snake = [(4, 10), (4, 9), (4, 8)] food = (10, 20) win.addch(food[0], food[1], '*') # initialize game variables score = 0 ESC = 27 key = curses.KEY_RIGHT # main game loop while key != ESC: win.border(0) win.addstr(0, 2, 'Score: ' + str(score) + ' ') win.addstr(0, 27, ' SNAKE ') win.timeout(150 - len(snake) // 5 + len(snake) // 10 % 120) prev_key = key event = win.getch() key = key if event == -1 else event if key not in [curses.KEY_LEFT, curses.KEY_RIGHT, curses.KEY_UP, curses.KEY_DOWN, ESC]: key = prev_key # calculate the next position of the snake y = snake[0][0] x = snake[0][1] if key == curses.KEY_DOWN: y += 1 elif key == curses.KEY_UP: y -= 1 elif key == curses.KEY_LEFT: x -= 1 elif key == curses.KEY_RIGHT: x += 1 # check if snake has hit the border or itself if y == 0 or y == 19 or x == 0 or x == 59 or (y, x) in snake: curses.endwin() quit() # check if snake has eaten the food if (y, x) == food: score += 1 food = () while food == (): food = (randint(1, 18), randint(1, 58)) if food in snake: food = () win.addch(food[0], food[1], '*') else: tail = snake.pop() win.addch(tail[0], tail[1], ' ') snake.insert(0, (y, x)) win.addch(snake[0][0], snake[0][1], '#') curses.endwin() quit()