snake.py

Created by laigna

Created on March 14, 2026

1.61 KB

Arrow keys to steer, Back to exit. Wrapping edges, speed increases, extra food every 5 points.


# Snake - NumWorks
# Created by Alvar Laigna - https://alvarlaigna.com
from random import randint
from ion import keydown
from ion import KEY_BACK,KEY_UP,KEY_DOWN
from ion import KEY_LEFT,KEY_RIGHT
from kandinsky import fill_rect,draw_string
from time import sleep

W,H = 32,22
BG = (255,255,255)
SN = (0,200,0)
HD = (0,0,200)
FD = (255,0,0)

def dr(c,r,col):
  fill_rect(c*10,r*10,10,10,col)

def food(s,fl):
  while True:
    f = (randint(0,W-1),randint(0,H-1))
    if f not in s and f not in fl:
      return f

def run():
  s = [(0,0),(1,0),(2,0)]
  h = (2,0)
  d = "R"
  fl = {food(s,set())}
  fill_rect(0,0,320,222,BG)
  for c,r in s[:-1]:
    dr(c,r,SN)
  dr(h[0],h[1],HD)
  for f in fl:
    dr(f[0],f[1],FD)
  while True:
    if keydown(KEY_BACK): break
    if keydown(KEY_UP) and d!="D": d="U"
    if keydown(KEY_RIGHT) and d!="L": d="R"
    if keydown(KEY_DOWN) and d!="U": d="D"
    if keydown(KEY_LEFT) and d!="R": d="L"
    if d=="U": h=(h[0],(h[1]-1)%H)
    elif d=="R": h=((h[0]+1)%W,h[1])
    elif d=="D": h=(h[0],(h[1]+1)%H)
    elif d=="L": h=((h[0]-1)%W,h[1])
    if h in s: break
    s.append(h)
    dr(h[0],h[1],HD)
    if h in fl:
      fl.discard(h)
      fl.add(food(s,fl))
      if len(s)%5==0:
        fl.add(food(s,fl))
    else:
      t = s.pop(0)
      dr(t[0],t[1],BG)
    for f in fl:
      dr(f[0],f[1],FD)
    p = s[-2]
    dr(p[0],p[1],SN)
    sleep(max(0.05,0.25/len(s)**0.5))
  fill_rect(85,80,150,55,(220,220,220))
  draw_string("GAME OVER",100,85,FD,
    (220,220,220))
  draw_string("Score: "+str(len(s)),
    105,108,(0,0,0),(220,220,220))
  while not keydown(KEY_BACK):
    sleep(0.1)

run()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.