Created
February 27, 2022 20:46
-
-
Save Techwizz-somboo/18e2c5d81476707aaca3dd28afc7809c to your computer and use it in GitHub Desktop.
SNAKE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import * | |
from kandinsky import * | |
from ion import * | |
from time import * | |
class Snake: | |
def __init__(self): | |
self.body=[[0,0]] | |
self.add=4 | |
self.dir=(1,0) | |
self.cherry=(0,0) | |
self.grid_size=(32,20) | |
self.rec=(320//self.grid_size[0],222//self.grid_size[1]) | |
self.tail=self.body[-1] | |
fill_rect(0,0,self.rec[0],self.rec[1],color(0,200,0)) | |
fill_rect(0,0,320,222,color(50,50,50)) | |
self.add_cherry() | |
self.draw_cherry() | |
self.dir_state=list(self.dir) | |
self.t=monotonic() | |
def add_cherry(self): | |
self.cherry=[randint(0,16),randint(0,10)] | |
for x in self.body: | |
if x==self.cherry: | |
self.add_cherry() | |
break | |
def draw_cherry(self): | |
fill_rect(self.cherry[0]*self.rec[0],self.cherry[1]*self.rec[1],self.rec[0],self.rec[1],color(255,0,0)) | |
def up(self): | |
if keydown(KEY_UP) and self.dir_state[1]!=1: | |
self.dir=[0,-1] | |
elif keydown(KEY_LEFT) and self.dir_state[0]!=1: | |
self.dir=[-1,0] | |
elif keydown(KEY_DOWN) and self.dir_state[1]!=-1: | |
self.dir=[0,1] | |
elif keydown(KEY_RIGHT) and self.dir_state[0]!=-1: | |
self.dir=[1,0] | |
if monotonic()-self.t>1/10: | |
fill_rect(self.body[0][0]*self.rec[0],self.body[0][1]*self.rec[1],self.rec[0],self.rec[1],color(0,200,0)) | |
self.dir_state=list(self.dir) | |
self.t=monotonic() | |
self.tail=list(self.body[-1]) | |
for x in range(len(self.body)-1,0,-1): | |
self.body[x]=list(self.body[x-1]) | |
self.body[0][0]=(self.body[0][0]+self.dir[0])%self.grid_size[0] | |
self.body[0][1]=(self.body[0][1]+self.dir[1])%self.grid_size[1] | |
if self.add>0: | |
self.body.append(self.tail) | |
self.add-=1 | |
else: | |
fill_rect(self.tail[0]*self.rec[0],self.tail[1]*self.rec[1],self.rec[0],self.rec[1],color(50,50,50)) | |
if self.body[0]==self.cherry: | |
self.add+=1 | |
self.add_cherry() | |
self.draw_cherry() | |
for x in range(1,len(self.body)): | |
if self.body[x]==list(self.body[0]): | |
draw_string("You lost",0,0) | |
raise KeyboardInterrupt | |
fill_rect(self.body[0][0]*self.rec[0],self.body[0][1]*self.rec[1],self.rec[0],self.rec[1],color(0,225,0)) | |
snake=Snake() | |
t=monotonic() | |
try: | |
while 1: | |
snake.up() | |
except KeyboardInterrupt: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment