Skip to content

Instantly share code, notes, and snippets.

@honzakral
Last active October 31, 2021 02:20
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save honzakral/833ee2b30231c53ec78e to your computer and use it in GitHub Desktop.
Save honzakral/833ee2b30231c53ec78e to your computer and use it in GitHub Desktop.
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[0]
movement = DIRECTIONS[direction]
new_head = (old_head[0]+movement[0], old_head[1]+movement[1])
if (
new_head[0] < 0 or
new_head[0] >= ARRAY_SIZE or
new_head[1] < 0 or
new_head[1] >= 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[0] * 10, (ARRAY_SIZE - bit[1] - 1) * 10))
s.blit(appleimage, (fruit[0] * 10, (ARRAY_SIZE - fruit[1]-1) * 10))
pygame.display.flip()
run()
@Azeemsha
Copy link

Azeemsha commented Apr 6, 2018

Hi, I get the below error. Possible reason?

File "snake.py", line 63
print('|', end='')
^
SyntaxError: invalid syntax

@alwye
Copy link

alwye commented Jun 9, 2018

Hi @Azeemsha

Try using python3

@Al3ksandar1
Copy link

Traceback (most recent call last):
File "<pyshell#20>", line 1, in
place_fruit((ARRAY_SIZE // 2, ARRAY_SIZE // 2))
NameError: name 'place_fruit' is not defined

Can you help me please?

@SHATSON
Copy link

SHATSON commented Jul 25, 2018

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

@OmegaPlusOne
Copy link

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

@VladislavTikhomirov
Copy link

how do you move

@i12utida
Copy link

i12utida commented Nov 18, 2018

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
Copy link

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
Copy link

NiksanJP commented May 4, 2019

Almost gave me cancer! nice logic but bad programmer

@minje-Jun
Copy link

@Phineas2019
Open cmd and write "pip install pygame"

@AyoubOuddah
Copy link

AyoubOuddah commented Feb 23, 2020

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
Copy link

lleavelle commented Mar 14, 2020

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[0]
movement = DIRECTIONS[direction]
new_head = (old_head[0]+movement[0], old_head[1]+movement[1])

if (
        new_head[0] < 0 or
        new_head[0] >= ARRAY_SIZE or
        new_head[1] < 0 or
        new_head[1] >= 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[0] * 10, (ARRAY_SIZE - bit[1] - 1) * 10))
    s.blit(appleimage, (fruit[0] * 10, (ARRAY_SIZE - fruit[1]-1) * 10))
    pygame.display.flip()

run()

Please help me

@honzakral
Copy link
Author

@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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment