import pygame import random # Dimensiones del tablero y tamaƱo de la celda ANCHO = 640 ALTO = 480 CELDA_SIZE = 20 # Colores NEGRO = (0, 0, 0) BLANCO = (255, 255, 255) VERDE = (0, 255, 0) ROJO = (255, 0, 0) class Snake: def __init__(self): self.segmentos = [(ANCHO // 2, ALTO // 2)] self.direccion = random.choice(['izquierda', 'derecha', 'arriba', 'abajo']) def mover(self): x, y = self.segmentos[0] if self.direccion == 'izquierda': x -= CELDA_SIZE elif self.direccion == 'derecha': x += CELDA_SIZE elif self.direccion == 'arriba': y -= CELDA_SIZE elif self.direccion == 'abajo': y += CELDA_SIZE self.segmentos.insert(0, (x, y)) self.segmentos.pop() def cambiar_direccion(self, direccion): if direccion == 'izquierda' and self.direccion != 'derecha': self.direccion = 'izquierda' elif direccion == 'derecha' and self.direccion != 'izquierda': self.direccion = 'derecha' elif direccion == 'arriba' and self.direccion != 'abajo': self.direccion = 'arriba' elif direccion == 'abajo' and self.direccion != 'arriba': self.direccion = 'abajo' def dibujar(self, pantalla): for segmento in self.segmentos: pygame.draw.rect(pantalla, VERDE, (segmento[0], segmento[1], CELDA_SIZE, CELDA_SIZE)) def main(): pygame.init() pantalla = pygame.display.set_mode((ANCHO, ALTO)) pygame.display.set_caption('Snake') reloj = pygame.time.Clock() snake = Snake() juego_terminado = False while not juego_terminado: for event in pygame.event.get(): if event.type == pygame.QUIT: juego_terminado = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: snake.cambiar_direccion('izquierda') elif event.key == pygame.K_RIGHT: snake.cambiar_direccion('derecha') elif event.key == pygame.K_UP: snake.cambiar_direccion('arriba') elif event.key == pygame.K_DOWN: snake.cambiar_direccion('abajo') snake.mover() pantalla.fill(NEGRO) snake.dibujar(pantalla) pygame.display.flip() reloj.tick(10) pygame.quit() if __name__ == '__main__': main()