Member-only story
Build a Snake Game in Python in Under 50 Lines of Code
Published in
2 min readJan 5, 2021

Learning Python? Enjoy a quick tutorial on how to build a super simple Snake game right in your terminal!
Pre-requisites:
- Python 3
- Your favorite text editor
- The Python curses library (install by running: pip install windows-curses)
Github repository linked at the bottom.
To get started, let’s first import the necessary libraries:
import cursesfrom curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWNfrom random import randint
Next, we need to initialize the game window:
curses.initscr() #initialize screen
window = curses.newwin(30, 60, 0, 0) #create new window H=30, W=60
window.keypad(True) #enable keypad
curses.noecho() #turn off automatic echoing of keys to the screen
curses.curs_set(0)
window.nodelay(True) #do not wait for the user input
Now, let’s set some global variables for the key, score, snake, and food coordinates. We will also display the first food item:
#initiate values
key = KEY_RIGHT
score = 0#initialize first food and snake coordinates
snake = [[5,8], [5,7], [5,6]]
food = [10,25]#display the first food
window.addch(food[0], food[1], 'O')
Next, we need to write the logic of the snake moving across the game window and growing as it eats more food:
while key != 27: # While they Esc key is not pressed
window.border(0)
#display the score and title
window.addstr(0, 2, 'Score: ' + str(score) + ' ')
window.addstr(0, 27, ' SNAKE! ') #make the snake faster as it eats more
window.timeout(140 - (len(snake)/5 + len(snake)/10)%120)
#refreshes the screen and then waits for the user to hit a key
event = window.getch()
key = key if event == -1 else event
#Calculates the new coordinates of the head of the snake.
snake.insert(0, [snake[0][0] +…