Play Your 90s Favourite Game With Odinub

In this article we will learn how to create a snake game using python with curses.

The curses is a library that can be used to create text user interface application.It is terminal controlled library i.e. the code written using curses can only be run through terminal. 

Step 1:- Create the File:

Install the geditor on your system for installing you need to enable Wi-Fi.

sudo apt-get install gedit

Create a new python file using editor by following command:

gedit filename.py 

Step 2:- Import Libraries:

To start with creating a snake game using curses, first we need to import some libraries.

import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
from random import randint

If you don’t have the curses library than install it by following command:

sudo apt-get install libncurses5 libncurses5-dev libncursesw5 

Step 3:- Initializing the game screen:

After importing the required libraries we need to start the game screen and get the maximum width and height of the opened terminal. By defining this height and width we will able to create the window for a game.

curses.initscr()
win = curses.newwin(20, 60, 0, 0) #height=20 and width=60
win.keypad(1)
curses.noecho()
curses.curs_set(0)
win.nodelay(1) 

Step 4:- Initialize the position of snake and food:

Further we will initialize the  position of snake and food. Also we will initialize our game score to be zero.

win.addch() will add the diamond symbol to represent the position of food.

key = KEY_RIGHT               # Initializing the values
score = 0
snake = [[4,10], [4,9], [4,8]]   # starting coordinates of snake
food = [10,20]                   # First food co-ordinates
win.addch(food[0], food[1],curses.ACS_DIAMOND)

Step 5:- Specifying the game over conditions:

  • There are two basic conditions in which the  game ends: First the snake will collide with one of the game window boundaries and second  the snake will collide with itself.
# Exit if snake crosses the boundaries 
if snake[0][0] == 0 or snake[0][0] == 19 or snake[0][1] == 0 or    snake[0][1] == 59:
    break
# If snake runs over itself
if snake[0] in snake[1:]: 
    break
  • There is additional feature is available with this code is ,if you want that snake exits from one boundary and enters from another then that can be possible by following code:
# If snake crosses the boundaries, make it enter from the other side (uncomment to enable)
    #if snake[0][0] == 0: snake[0][0] = 18
    #if snake[0][1] == 0: snake[0][1] = 58
    #if snake[0][0] == 19: snake[0][0] = 1
    #if snake[0][1] == 59: snake[0][1] = 1 

Step 6:- Playing the game:

  • In this game we will use the four keys of keyboard that are ‘up’,’down’,’right’ & ‘left’ to move snake. To get the user input from the keyboard we have to use win.getch().
prevKey = key                          # Previous key pressed
    event = win.getch()
    key = key if event == -1 else event 
  • If spacebar is pressed then the game will paused until it is released.
if key == ord(' '):      # If SPACEBAR is pressed, wait for another
       key = -1           # one (Pause/Resume)
       while key != ord(' '):
           key = win.getch()
           key = prevKey
     continue 
  • If invalid key is pressed then it will  continue to move in the previous direction.
if key not in [KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, 27]: 
    # If an invalid key is pressed
       key = prevKey  
  • To create a border around the game screen we have following command:
win.border(0) 
  • To increase the speed of snake similar to its length .We have following command:
win.timeout(150 - (len(snake)/5 + len(snake)/10)%120) 
  • There are two situations: First, in next step snake eats  food then we will add one unit on snake’s head and will not  remove unit from it’s tail. Second, in next step snake will only move to next position but not to eat  food then we will add one unit on snake’s head and will remove one unit from it’s tail. Also we will display a food to another location:
if snake[0] == food:               # When snake eats the food
       food = [ ]
       score += 1
       while food == [ ]:
           food = [randint(1, 18), randint(1, 58)]    # Calculating next food's coordinates
            if food in snake: food = [ ]
       win.addch(food[0], food[1],curses.ACS_DIAMOND)
    else:    
       last = snake.pop()  # [1] If it does not eat the food, length decreases
       win.addch(last[0], last[1], ' ')
    win.addch(snake[0][0], snake[0][1], '~')    

Step 7:- Display the Score:

Finally we will display the score and close the game window.

curses.endwin()
print("\nScore - " + str(score)) 

To execute this code we have the following command:

python filename.py 

The Output of this game is:

Code :
Code Title :
snake.py
Code Language :
python
0 Commenting Overall Comment