# Snake Game In Python - Python Beginner Tutorial

Implement the famous Snake game in this beginner tutorial using the curses module!

Implement the famous Snake game in this beginner tutorial! Learn also how to use the curses module to build terminal applications. This tutorial is aimed at beginners. You will learn about different data structures (e.g. lists and tuples) and how to implement the game logic with different control flows (e.g. while loop / if-statements).

You can find the code also on GitHub.

``````import curses
from random import randint

# setup window
curses.initscr()
win = curses.newwin(20, 60, 0, 0) # y,x
curses.noecho()
curses.curs_set(0)
win.border(0)
win.nodelay(1) # -1

# snake and food
snake = [(4, 10), (4, 9), (4, 8)]
food = (10, 20)

# game logic
score = 0

ESC = 27
key = curses.KEY_RIGHT

while key != ESC:
win.addstr(0, 2, 'Score ' + str(score) + ' ')
win.timeout(150 - (len(snake)) // 5 + len(snake)//10 % 120) # increase speed

prev_key = key
event = win.getch()
key = event if event != -1 else prev_key

if key not in [curses.KEY_LEFT, curses.KEY_RIGHT, curses.KEY_UP, curses.KEY_DOWN, ESC]:
key = prev_key

# calculate the next coordinates
y = snake
x = snake
if key == curses.KEY_DOWN:
y += 1
if key == curses.KEY_UP:
y -= 1
if key == curses.KEY_LEFT:
x -= 1
if key == curses.KEY_RIGHT:
x += 1

snake.insert(0, (y, x)) # append O(n)

# check if we hit the border
if y == 0: break
if y == 19: break
if x == 0: break
if x == 59: break

# if snake runs over itself
if snake in snake[1:]: break

if snake == food:
# eat the food
score += 1
food = ()
while food == ():
food = (randint(1,18), randint(1,58))
if food in snake:
food = ()
else:
# move snake
last = snake.pop()

curses.endwin()
print(f"Final score = {score}")
``````

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*

PySaaS: The Pure Python SaaS Starter Kit