Reading-Notes-for-Advanced-Software-Development-in-Python-Course

Snake Game

You can find the implementation of the game and the full code in my repo here

The is a tutorial to learn how to create a snake game using python.

If you are not familliar with curses, check out my notes here

The game implementation is divided into parts:

  1. Initializing Game Screen
  2. Initialize snake and apple initial positions
  3. Specifying Game Over Conditions and Scoring
  4. Playing the Game with the game logic

Part 1: Initializing Game Screen

Part 2: Initialize snake and apple initial positions

Part 3: Specifying Game Over Conditions and Scoring

Part 4: Playing the Game

In this game we will use four keyboard buttons, ‘up’, ‘down’, ‘left’ and ‘right’. To get a user input from keyboard we need to use win.getch() function.

win.border(0)
win.timeout(100)

next_key = win.getch()
if next_key == -1:
    key = key
else:
    key = next_key

Game Logic

Now we will see the logic to move snake and eat apple. According to the game rules, snake will continue to move in the same direction if user do not press any button. Also snake can not move backward. In case user press any button, we need to update snake head’s position.

if key == curses.KEY_LEFT and prev_button_direction != 1:
    button_direction = 0
elif key == curses.KEY_RIGHT and prev_button_direction != 0:
    button_direction = 1
elif key == curses.KEY_UP and prev_button_direction != 2:
    button_direction = 3
elif key == curses.KEY_DOWN and prev_button_direction != 3:
    button_direction = 2
else:
    pass

prev_button_direction = button_direction

if button_direction == 1:
    snake_head[1] += 1
elif button_direction == 0:
    snake_head[1] -= 1
elif button_direction == 2:
    snake_head[0] += 1
elif button_direction == 3:
    snake_head[0] -= 1

Next there are two situations. One, in next step snake will move to a new position and second, in next step snake will eat apple. In case snake only moves to a new position, we will add one unit at it’s head and remove one unit from its tail according to the pressed direction. Another situation, if snake eats apple then we will add one unit at snake’s head and do not remove from it’s tail. We will also display a new apple at different location.