Skip to content
{{ message }}

Instantly share code, notes, and snippets.

# HonzaKral/snake.py

Last active Mar 14, 2020
snake game in python
 import pygame from pygame.locals import * from random import randint import os, sys ARRAY_SIZE = 50 DIRECTIONS = { "LEFT": (-1, 0), "RIGHT": (1, 0), "UP": (0, 1), "DOWN": (0, -1), } snake, fruit = None, None def init(): global snake snake = [ (0, 2), (0, 1), (0, 0)] place_fruit((ARRAY_SIZE // 2, ARRAY_SIZE // 2)) def place_fruit(coord=None): global fruit if coord: fruit = coord return while True: x = randint(0, ARRAY_SIZE-1) y = randint(0, ARRAY_SIZE-1) if (x, y) not in snake: fruit = x, y return def step(direction): old_head = snake movement = DIRECTIONS[direction] new_head = (old_head+movement, old_head+movement) if ( new_head < 0 or new_head >= ARRAY_SIZE or new_head < 0 or new_head >= ARRAY_SIZE or new_head in snake ): return False if new_head == fruit: place_fruit() else: tail = snake[-1] del snake[-1] snake.insert(0, new_head) return True def print_field(): os.system('clear') print('=' * (ARRAY_SIZE+2)) for y in range(ARRAY_SIZE-1, -1, -1): print('|', end='') for x in range(ARRAY_SIZE): out = ' ' if (x, y) in snake: out = 'X' elif (x, y) == fruit: out = 'O' print(out, end='') print('|') print('=' * (ARRAY_SIZE+2)) def test(): global fruit init() assert step('UP') assert snake == [(0, 3), (0, 2), (0, 1)] fruit = (0, 4) assert step('UP') assert snake == [(0, 4), (0, 3), (0, 2), (0, 1)] assert fruit != (0, 4) assert not step('DOWN'), 'Kdyz nacouvam do sebe, umru!' DIRS = ['UP', 'RIGHT', 'DOWN', 'LEFT'] def run(): init() direction = 0 pygame.init() s = pygame.display.set_mode((ARRAY_SIZE * 10, ARRAY_SIZE * 10)) #pygame.display.set_caption('Snake') appleimage = pygame.Surface((10, 10)) appleimage.fill((0, 255, 0)) img = pygame.Surface((10, 10)) img.fill((255, 0, 0)) clock = pygame.time.Clock() pygame.time.set_timer(1, 100) while True: e = pygame.event.wait() if e.type == QUIT: pygame.quit() elif e.type == MOUSEBUTTONDOWN: if e.button == 3: direction = (direction+1) % 4 elif e.button == 1: direction = (direction+3) % 4 if not step(DIRS[direction]): pygame.quit() sys.exit(1) s.fill((255, 255, 255)) for bit in snake: s.blit(img, (bit * 10, (ARRAY_SIZE - bit - 1) * 10)) s.blit(appleimage, (fruit * 10, (ARRAY_SIZE - fruit-1) * 10)) pygame.display.flip() run()

### Azeemsha commented Apr 6, 2018

 Hi, I get the below error. Possible reason? File "snake.py", line 63 print('|', end='') ^ SyntaxError: invalid syntax

### alwye commented Jun 9, 2018

 Try using python3

### Al3ksandar1 commented Jun 10, 2018

 Traceback (most recent call last): File "", line 1, in place_fruit((ARRAY_SIZE // 2, ARRAY_SIZE // 2)) NameError: name 'place_fruit' is not defined Can you help me please?

### SHATSON commented Jul 25, 2018

 replace end = ' ' with "\n" That should do the job for you.

### OmegaPlusOne commented Sep 17, 2018

 what is the purpose of the test and print_field functions? they're not called and I'm just curious.

### VladislavTikhomirov commented Oct 25, 2018

 how do you move

### i12utida commented Nov 18, 2018 • edited

 I can't move it..... so I changed your code little bit -------------- your code ---------------- `````` while True: e = pygame.event.wait() if e.type == QUIT: pygame.quit() elif e.type == MOUSEBUTTONDOWN: if e.button == 3: direction = (direction+1) % 4 elif e.button == 1: direction = (direction+3) % 4 if not step(DIRS[direction]): pygame.quit() sys.exit(1) `````` ------------------ changed code -------------------------- ``````while True: e = pygame.event.wait() if e.type == QUIT: pygame.quit() elif e.type == KEYDOWN: key=pygame.key.get_pressed() if key[pygame.K_UP]: direction = 0 elif key[pygame.K_RIGHT]: direction = 1 elif key[pygame.K_DOWN]: direction = 2 elif key[pygame.K_LEFT]: direction = 3 #elif e.type == MOUSEBUTTONDOWN: # if e.button == 3: # direction = (direction+1) % 4 # elif e.button == 1: # direction = (direction+3) % 4 if not step(DIRS[direction]): pygame.quit() sys.exit() ``````

### Phineas2019 commented Apr 30, 2019

 When I try to run this program I get this error: ( The xxx's are stuff I deleted) Traceback (most recent call last): File "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxSnake Game.py", line 1, in import pygame ModuleNotFoundError: No module named 'pygame'

### NiksanJP commented May 4, 2019

 Almost gave me cancer! nice logic but bad programmer

### minje-Jun commented Dec 18, 2019

 @Phineas2019 Open cmd and write "pip install pygame"

### AyoubOuddah commented Feb 23, 2020 • edited

 I can't move it..... so I changed your code little bit -------------- your code ---------------- `````` while True: e = pygame.event.wait() if e.type == QUIT: pygame.quit() elif e.type == MOUSEBUTTONDOWN: if e.button == 3: direction = (direction+1) % 4 elif e.button == 1: direction = (direction+3) % 4 if not step(DIRS[direction]): pygame.quit() sys.exit(1) `````` ------------------ changed code -------------------------- ``````while True: e = pygame.event.wait() if e.type == QUIT: pygame.quit() elif e.type == KEYDOWN: key=pygame.key.get_pressed() if key[pygame.K_UP]: direction = 0 elif key[pygame.K_RIGHT]: direction = 1 elif key[pygame.K_DOWN]: direction = 2 elif key[pygame.K_LEFT]: direction = 3 #elif e.type == MOUSEBUTTONDOWN: # if e.button == 3: # direction = (direction+1) % 4 # elif e.button == 1: # direction = (direction+3) % 4 if not step(DIRS[direction]): pygame.quit() sys.exit() `````` Plus you can add a test on the previous snake's direction to avoid accidental Game Over. The events should be as follows ``````while True: e = pygame.event.wait() if e.type == QUIT: pygame.quit() elif e.type == KEYDOWN: key=pygame.key.get_pressed() if key[pygame.K_UP] and direction != 2: direction = 0 elif key[pygame.K_RIGHT] and direction != 3: direction = 1 elif key[pygame.K_DOWN] and direction != 0: direction = 2 elif key[pygame.K_LEFT] and direction != 1: direction = 3 if not step(DIRS[direction]): pygame.quit() sys.exit() ``````

### lleavelle commented Mar 14, 2020 • edited

My snake game is working, but the program ends before i die, this is my code:

import pygame
from pygame.locals import *
from random import randint
import os, sys

ARRAY_SIZE = 50

DIRECTIONS = {
"LEFT": (-1, 0),
"RIGHT": (1, 0),
"UP": (0, 1),
"DOWN": (0, -1),
}

snake, fruit = None, None

def init():
global snake
snake = [ (0, 2), (0, 1), (0, 0)]

``````place_fruit((ARRAY_SIZE // 2, ARRAY_SIZE // 2))
``````

def place_fruit(coord=None):
global fruit
if coord:
fruit = coord
return

``````while True:
x = randint(0, ARRAY_SIZE-1)
y = randint(0, ARRAY_SIZE-1)
if (x, y) not in snake:
fruit = x, y
return
``````

def step(direction):
old_head = snake
movement = DIRECTIONS[direction]
new_head = (old_head+movement, old_head+movement)

``````if (
new_head < 0 or
new_head >= ARRAY_SIZE or
new_head < 0 or
new_head >= ARRAY_SIZE or
new_head in snake
):
return False

if new_head == fruit:
place_fruit()
else:
tail = snake[-1]
del snake[-1]

snake.insert(0, new_head)
return True
``````

def print_field():
os.system('clear')
print('=' * (ARRAY_SIZE+2))
for y in range(ARRAY_SIZE-1, -1, -1):
print('|', end='')
for x in range(ARRAY_SIZE):
out = ' '
if (x, y) in snake:
out = 'X'
elif (x, y) == fruit:
out = 'O'
print(out, end='')
print('|')
print('=' * (ARRAY_SIZE+2))

def test():
global fruit
init()
assert step('UP')

``````assert snake == [(0, 3), (0, 2), (0, 1)]

fruit = (0, 4)
assert step('UP')

assert snake == [(0, 4), (0, 3), (0, 2), (0, 1)]
assert fruit != (0, 4)

assert not step('DOWN'), 'Kdyz nacouvam do sebe, umru!'
``````

DIRS = ['UP', 'RIGHT', 'DOWN', 'LEFT']
def run():
init()

``````direction = 0

pygame.init()
s = pygame.display.set_mode((ARRAY_SIZE * 10, ARRAY_SIZE * 10))
#pygame.display.set_caption('Snake')
appleimage = pygame.Surface((10, 10))
appleimage.fill((0, 255, 0))
img = pygame.Surface((10, 10))
img.fill((255, 0, 0))
clock = pygame.time.Clock()

pygame.time.set_timer(1, 100)

while True:
e = pygame.event.wait()
if e.type == QUIT:
pygame.quit()

elif e.type == KEYDOWN:
key=pygame.key.get_pressed()

if      key[pygame.K_UP]:     direction = 0
elif    key[pygame.K_RIGHT]:    direction = 1
elif    key[pygame.K_DOWN]:       direction = 2
elif    key[pygame.K_LEFT]:     direction = 3

#elif e.type == MOUSEBUTTONDOWN:
#    if e.button == 3:
#        direction = (direction+1) % 4
#    elif e.button == 1:
#        direction = (direction+3) % 4

if not step(DIRS[direction]):
pygame.quit()
sys.exit()

s.fill((255, 255, 255))
for bit in snake:
s.blit(img, (bit * 10, (ARRAY_SIZE - bit - 1) * 10))
s.blit(appleimage, (fruit * 10, (ARRAY_SIZE - fruit-1) * 10))
pygame.display.flip()
``````

## run()

Please help me

### HonzaKral commented Mar 14, 2020

 @lleavelle You need to be a bit more specific, when I run your code I can play the game just fine and it only quits after I crash. What is happening for you?
to join this conversation on GitHub. Already have an account? Sign in to comment