jueves, 31 de enero de 2013

snake with pygame



import pygame, random , sys, os
from pygame.locals import *

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255, 0, 0)
GREEN = (0,255,0)
BLUE = (0,0,255)
DARKCYAN = (0, 139, 139)
SCREEN_SIZE = (800,600)
UP    = 'up'
DOWN  = 'down'
LEFT  = 'left'
RIGHT = 'right'
WIDTH =  10
HEIGHT = 10
DIRECCION_INICIAL = RIGHT#Es hacia donde parte la serpiente

class Alimento:
    def __init__(self):
        self.x = random.choice(range(0,SCREEN_SIZE[0] - 20, 20))
        self.y = random.choice(range(0,SCREEN_SIZE[1] -20, 20))
    def pintar(self, screen):
        pygame.draw.rect(screen, BLACK, pygame.Rect(self.x, self.y, 20,20))

class Nodo:
    def __init__(self, x, y, siguiente = None, direccion = None):
        self.x = x
        self.y = y
        self.siguiente = siguiente
        self.direccion = direccion
        if self.siguiente ==  None:
            self.isHead = True
        else:
            self.isHead = False
    def __str__(self):
        return 'x = %d,  y = %d'%(self.x, self.y)

class Snake:
    def __init__(self, head_x, head_y, tamanio = 33):
        self.head_x = head_x
        self.head_y = head_y
        self.nodos = []
        self.tamanio = tamanio
        self.crear()

    def crear(self):
        #Aqui se crea la cuestion
        for i in range(self.tamanio):
            if i == 0: #Aqui se crea la cabecera
                self.nodos.append(Nodo( self.head_x, self.head_y,
                    siguiente = None, direccion = DIRECCION_INICIAL))#snake va a la derecha
            else:
                self.nodos.append(Nodo( self.head_x - i*20, self.head_y,
                    siguiente = self.nodos[i-1], direccion = None))
    def crecer(self):
        #aqui quedo lo que estaba haciendo ...
        self.tamanio += 1
    def comer(self):
        self.tamanio += 1
    def dibujar(self):
        pass
    def avanzar(self):
        for i in range(1, len(self.nodos) + 1):
            nodo = self.nodos[-i]
            if nodo.isHead:
                if nodo.direccion == UP:
                    nodo.y -= 20
                elif nodo.direccion  == DOWN:
                    nodo.y += 20  
                elif nodo.direccion == LEFT:
                    nodo.x -= 20
                elif nodo.direccion == RIGHT:
                    nodo.x += 20#WIDTH
             #   print nodo, 'is Head'
            else:
                nodo.x = nodo.siguiente.x
                nodo.y = nodo.siguiente.y
             #   print nodo, 'is Body'
    def cambiar_direccion(self, direccion):
        if  direccion == UP and self.nodos[0].direccion != DOWN:
            self.nodos[0].direccion = UP
        elif  direccion == DOWN and self.nodos[0].direccion != UP:
            self.nodos[0].direccion =  DOWN
        elif  direccion == LEFT and self.nodos[0].direccion != RIGHT:
            self.nodos[0].direccion = LEFT
        elif  direccion == RIGHT and self.nodos[0].direccion != LEFT:
            self.nodos[0].direccion = RIGHT
    def imprimir(self):
        for i in range(1, len(self.nodos) + 1):
            nodo = self.nodos[-i]
            print nodo
        print '#'*20
    def getNodos(self):
        return self.nodos
    def detectar_colision_consigo_misma(self):
        for nodo in self.nodos[1:]:
            if self.nodos[0].x == nodo.x and self.nodos[0].y == nodo.y:
                sys.exit()
class Juego:
    def __init__(self):
        self.snake = Snake(100,100, 2)
        self.alimento = Alimento()
    def run(self):
        self.screen = pygame.display.get_surface()
        clock = pygame.time.Clock()
        fps = 30
        pygame.init()
        #ocultar puntero del mouse
        pygame.mouse.set_visible(False)
        self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32 )
        pygame.display.set_caption('sdajkashdahdsjahdskhasa')
        self.screen.fill(DARKCYAN)
        contador = 1
        while True:
            clock.tick(12)
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
            keys_pressed = pygame.key.get_pressed()
            if keys_pressed[K_UP]:
                self.snake.cambiar_direccion(UP)
            elif keys_pressed[K_DOWN]:
                self.snake.cambiar_direccion(DOWN)
            elif keys_pressed[K_LEFT]:
                self.snake.cambiar_direccion(LEFT)
            elif keys_pressed[K_RIGHT]:
                self.snake.cambiar_direccion(RIGHT)
            elif keys_pressed[K_ESCAPE]:
                pygame.quit()
            self.screen.fill(DARKCYAN)
            self.alimento.pintar(self.screen)
            self.pintarSnake()
            #Detectar collisiones
            self.detectar_colision_snake_comida()
            pygame.display.update()
            self.snake.avanzar()
            self.detectar_colision_snake_paredes()
            self.snake.detectar_colision_consigo_misma()
    def pintarSnake(self):
        nodos = self.snake.getNodos()
        for nodo in nodos:
#           pygame.draw.circle(self.screen, RED, (nodo.x, nodo.y), WIDTH)
           pygame.draw.rect(self.screen, BLACK, pygame.Rect(nodo.x, nodo.y, 20, 20))
    def crecer(self):
        nodos = self.snake.getNodos()
        nodos.append(Nodo(nodos[-1].x, nodos[-1].y, nodos[-1]))
    def detectar_colision_snake_comida(self):
        #print 'cabeza snake = ', self.snake.getNodos()[0].x, self.snake.getNodos()[0].y
        #print 'alimento = ', self.alimento.x, self.alimento.y
        if self.snake.getNodos()[0].x == self.alimento.x and self.snake.getNodos()[0].y == self.alimento.y:
            self.crecer()
            #de aqui haste el final de la funcion es para que cuando aparezca un nuevo alimento
            #aparezca encima de la serpiente
            self.alimento = Alimento()
            nodoalimento = Nodo(self.alimento.x, self.alimento.y)
            while True:
                if nodoalimento not in self.snake.getNodos():
                    break
                else:
                    self.alimento = Alimento()
                    nodoalimento = Nodo(self.alimento.x, self.alimento.y)
    def detectar_colision_snake_paredes(self):
        if self.snake.getNodos()[0].x >= SCREEN_SIZE[0]:
            sys.exit()
        elif self.snake.getNodos()[0].y >= SCREEN_SIZE[1]:
            sys.exit()
        elif self.snake.getNodos()[0].x <  0:
            sys.exit()
        elif self.snake.getNodos()[0].y < 0:
            sys.exit()

if __name__ == '__main__':
    Juego().run()
#    snake = Snake(pos_x_head, pos_y_head, tamanio = 4)
#    snake.imprimir()
#    snake.avanzar()
#    snake.imprimir()