Skip to content
The Chat Archive
o4-mini-2025-04-16· OpenAI LMArena Human Preference 140K

hazme codigo en python de snake

  1. User

    hazme codigo en python de snake

  2. Assistant

    ¡Claro! Aquí tienes un ejemplo completo de un juego Snake en Python usando Pygame. Sólo necesitas tener instalado Pygame (pip install pygame) y guardarlo en un archivo, por ejemplo snake.py.

    import pygame
    import sys
    import random
    
    # -------- CONFIGURACIÓN INICIAL --------
    pygame.init()
    ANCHO, ALTO = 640, 480
    TAM_CELDA = 20
    COLUMNAS = ANCHO // TAM_CELDA
    FILAS = ALTO // TAM_CELDA
    
    # Colores
    NEGRO  = (  0,   0,   0)
    BLANCO = (255, 255, 255)
    ROJO   = (200,   0,   0)
    VERDE  = (  0, 200,   0)
    
    pantalla = pygame.display.set_mode((ANCHO, ALTO))
    reloj = pygame.time.Clock()
    pygame.display.set_caption("Snake 🐍")
    
    # -------- FUNCIONES --------
    def dibujar_celda(x, y, color):
        rect = pygame.Rect(x * TAM_CELDA, y * TAM_CELDA, TAM_CELDA, TAM_CELDA)
        pygame.draw.rect(pantalla, color, rect)
    
    def texto_central(texto, tamaño, color, offset_y=0):
        font = pygame.font.SysFont('Arial', tamaño, True)
        surf = font.render(texto, True, color)
        rect = surf.get_rect(center=(ANCHO//2, ALTO//2 + offset_y))
        pantalla.blit(surf, rect)
    
    # -------- LÓGICA DEL JUEGO --------
    def main():
        # Posición y cuerpo de la serpiente (lista de tuplas)
        serpiente = [(COLUMNAS//2, FILAS//2)]
        direccion = (0, -1)  # Inicialmente sube
        # Posición de la comida
        comida = (random.randrange(COLUMNAS), random.randrange(FILAS))
        puntuación = 0
        velocidad = 10
    
        en_juego = True
        while True:
            # --- Eventos ---
            for evento in pygame.event.get():
                if evento.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif evento.type == pygame.KEYDOWN:
                    if en_juego:
                        if evento.key == pygame.K_UP    and direccion != (0, 1):
                            direccion = (0, -1)
                        if evento.key == pygame.K_DOWN  and direccion != (0, -1):
                            direccion = (0, 1)
                        if evento.key == pygame.K_LEFT  and direccion != (1, 0):
                            direccion = (-1, 0)
                        if evento.key == pygame.K_RIGHT and direccion != (-1, 0):
                            direccion = (1, 0)
                    else:
                        # Reiniciar si terminó el juego
                        if evento.key == pygame.K_r:
                            main()
    
            if en_juego:
                # --- Actualizar estado ---
                cabeza_x, cabeza_y = serpiente[0]
                dx, dy = direccion
                nueva_cabeza = (cabeza_x + dx, cabeza_y + dy)
    
                # Colisiones con muros
                if (not 0 <= nueva_cabeza[0] < COLUMNAS) or (not 0 <= nueva_cabeza[1] < FILAS):
                    en_juego = False
    
                # Colisión consigo misma
                if nueva_cabeza in serpiente:
                    en_juego = False
    
                serpiente.insert(0, nueva_cabeza)
    
                # Comer comida
                if nueva_cabeza == comida:
                    puntuación += 1
                    velocidad += 1 if velocidad < 25 else 0
                    # Colocar nueva comida en posición libre
                    while True:
                        pos = (random.randrange(COLUMNAS), random.randrange(FILAS))
                        if pos not in serpiente:
                            comida = pos
                            break
                else:
                    serpiente.pop()  # Mover: quitar cola
    
            # --- Dibujado ---
            pantalla.fill(NEGRO)
            # Dibuja serpent
            for segmento in serpiente:
                dibujar_celda(*segmento, VERDE)
            # Dibuja comida
            dibujar_celda(*comida, ROJO)
    
            # Puntuación
            font = pygame.font.SysFont('Arial', 24)
            texto = font.render(f"Puntuación: {puntuación}", True, BLANCO)
            pantalla.blit(texto, (10, 10))
    
            if not en_juego:
                texto_central("¡GAME OVER!", 48, ROJO, offset_y=-20)
                texto_central("Presiona R para reiniciar", 24, BLANCO, offset_y=30)
    
            pygame.display.flip()
            reloj.tick(velocidad)
    
    if __name__ == "__main__":
        main()
    

    Cómo funciona:

    1. Creamos una ventana de 640×480 px y una “cuadrícula” de celdas de 20×20 px.
    2. La serpiente es una lista de coordenadas (x,y).
    3. Cada frame movemos la cabeza según la dirección y gestionamos colisiones.
    4. Si la cabeza alcanza la “comida”, aumentamos la puntuación y alargamos la serpiente.
    5. En GAME OVER permitimos reiniciar pulsando R.

    ¡Listo! 🐍
    Si quieres mejoras (niveles, menú, sonidos…), dímelo y lo vemos juntos.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.