############################################################################# # # by jesper@taxboel.dk Feb '08 - Use freely # ############################################################################# import pygame from pygame import * from random import * pygame.init() screen = Surface size = width, height = 1000, 500 bnd = 22 class Snake: score = 0 length = 30 direction = K_UP def __init__(self): self.length = 30 self.tail = [(width/2,height/2)] self.dir = K_UP def update(self): x,y = self.tail[0] if self.dir==K_UP: y-=2 elif self.dir==K_DOWN: y+=2 elif self.dir==K_LEFT: x-=2 elif self.dir==K_RIGHT: x+=2 Doomed = False #Bounds if x < bnd or x >= width-bnd or y < bnd or y >= height-bnd: Doomed = True for i in range(len(self.tail)): tx,ty = self.tail [i] if i != 0: if self.tail[i] == (x,y): Doomed = True if Doomed: global snake snake = Snake() self.tail.insert(0,(x,y)) global Goodies for G in Goodies: gx,gy = G.position if (gx - x)*(gx - x)+(gy - y)*(gy - y) < G.size*G.size: Goodies.remove(G) self.length += G.size*3 self.score += G.size/10 * self.length while len(Goodies) < 3: Goodies.append(Goodie()) l = len(self.tail) if len(self.tail) > self.length: self.tail.pop() def draw(self): global screen if(len(self.tail) > 2): pygame.draw.lines(screen, (0,200,12), False, self.tail, 1) pygame.draw.circle(screen, (0,255,12), self.tail [0], 3) class Goodie: def __init__(self): safebnd = bnd + 15 self.position = (int(random()*(width-2*safebnd)+safebnd), int(random()*(height-2*safebnd)+safebnd)) self.size = int(8+random()*7) def draw(self): pygame.draw.circle(screen, (255,255,0), self.position, self.size) snake = Snake() Goodies = [] screen = Surface(size) screen = pygame.display.set_mode (size) pygame.display.set_caption("Simple Snake 1.0") done = False while not done: for e in pygame.event.get(): if( e.type == QUIT ): done = True break elif (e.type == KEYDOWN): if( e.key == K_ESCAPE ): done = True break elif e.key == K_LEFT and snake.dir != K_RIGHT or e.key == K_RIGHT or e.key == K_UP or e.key == K_DOWN: snake.dir = e.key screen.fill((0,0,0)) #bounds pygame.draw.rect (screen,(10,100,255),Rect(bnd,bnd,width-bnd*2,height-bnd*2),2) #score #font = pygame.font.Font('freesansbold.ttf', 15) #screen.blit(font.render("Score: %d" % snake.score, 1, (200, 10, 10, 0)), (25,5)) snake.update() for G in Goodies: G.draw() snake.draw() if not snake.score / 1000 % 2: pygame.time.delay(4) pygame.display.flip()