Skip to content

Instantly share code, notes, and snippets.

@x13machine
Last active March 21, 2016 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x13machine/28192469e203fbc93ecb to your computer and use it in GitHub Desktop.
Save x13machine/28192469e203fbc93ecb to your computer and use it in GitHub Desktop.
Shell Shakes - A snake Game using curses.
import curses, math, signal, time, thread, random
#init
screen = curses.initscr()
curses.noecho()
curses.curs_set(0)
curses.start_color();
curses.use_default_colors()
#colors
for i in range(0, curses.COLORS):
curses.init_pair(i + 1,-1,i)
#ctrl-c handler
running=True
def signal_handler(signal, frame):
global running
running=False
signal.signal(signal.SIGINT, signal_handler)
#player
pos=[0,0,2]
direction=[0,1]
parts=[]
screen.timeout(-1)
screen.nodelay(1)
lastframe=time.time()
dims=screen.getmaxyx()
apple=[random.randrange(1,dims[1]-2),random.randrange(1,dims[0]-2)]
#game loop
while running:
ch=screen.getch()
if ch==ord('w') and direction[1]!=1: direction=[0,-1]
elif ch==ord('s') and direction[1]!=-1: direction=[0,1]
elif ch==ord('a') and direction[0]!=1: direction=[-1,0]
elif ch==ord('d') and direction[0]!=-1: direction=[1,0]
if time.time()-lastframe>0.05:
#update
lastframe=time.time()
parts+=[[pos[0], pos[1], pos[2]]]
x=0
for i in parts:
i[2]-=1
if i[2]<0: del parts[x]
x+=1
dims=screen.getmaxyx()
pos[0]+=direction[0]
pos[1]+=direction[1]
if pos[0]<0: pos[0]=dims[1]-2
if pos[0]>dims[1]-2: pos[0]=0
if pos[1]<0: pos[1]=dims[0]-1
if pos[1]>dims[0]-1: pos[1]=0
if apple[0]==pos[0] and apple[1]==pos[1]:
apple=[random.randrange(1,dims[1]-1),random.randrange(1,dims[0]-1)]
pos[2]+=3
for i in parts:
if pos[0]==i[0] and pos[1]==i[1]:
running=False
break
#render
screen.clear()
for i in parts:
screen.addstr(i[1],i[0],' ',curses.color_pair(3))
screen.addstr(pos[1],pos[0],' ',curses.color_pair(2))
screen.addstr(apple[1],apple[0],' ',curses.color_pair(5))
screen.refresh()
#the end
curses.endwin()
print "Your Score: "+ str(pos[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment