Herramientas de usuario

Herramientas del sitio


informatica:programacion:python:pyxel:juego_tipo_snake

Snake clon

Juego tipo Snake usando Pyxel.

El código fue generado por DeepSeek (una inteligencia artificial generativa)

import pyxel
import random
 
class SnakeGame:
    def __init__(self):
        pyxel.init(128, 128, title="Pyxel Snake", fps=30)
        self.reset_game()
        pyxel.run(self.update, self.draw)
 
    def reset_game(self):
        self.snake = [(64, 64), (56, 64), (48, 64)]
        self.direction = (8, 0)
        self.next_direction = (8, 0)
        self.food = self.generate_food()
        self.score = 0
        self.game_over = False
        self.speed = 15  # Menor = más rápido
        self.frame_count = 0
 
    def generate_food(self):
        while True:
            food = (random.randint(0, 15)*8, random.randint(0, 15)*8)
            if food not in self.snake:
                return food
 
    def update(self):
        if self.game_over:
            if pyxel.btnp(pyxel.KEY_R):
                self.reset_game()
            return
 
        self.frame_count += 1
        if self.frame_count < self.speed:
            return
 
        self.frame_count = 0
 
        # Control de dirección
        if pyxel.btn(pyxel.KEY_UP) and self.direction != (0, 8):
            self.next_direction = (0, -8)
        if pyxel.btn(pyxel.KEY_DOWN) and self.direction != (0, -8):
            self.next_direction = (0, 8)
        if pyxel.btn(pyxel.KEY_LEFT) and self.direction != (8, 0):
            self.next_direction = (-8, 0)
        if pyxel.btn(pyxel.KEY_RIGHT) and self.direction != (-8, 0):
            self.next_direction = (8, 0)
 
        self.direction = self.next_direction
 
        # Movimiento con wrap-around
        new_head = (
            (self.snake[0][0] + self.direction[0]) % 128,
            (self.snake[0][1] + self.direction[1]) % 128
        )
 
        # Colisiones
        if new_head in self.snake:
            self.game_over = True
            return
 
        # Comer comida
        if new_head == self.food:
            self.score += 10
            self.speed = max(5, self.speed - 1)  # Aumentar velocidad
            self.food = self.generate_food()
            self.snake.insert(0, new_head)
        else:
            self.snake = [new_head] + self.snake[:-1]
 
    def draw(self):
        pyxel.cls(0)
 
        # Comida
        pyxel.rect(self.food[0], self.food[1], 8, 8, 8)
 
        # Serpiente
        for i, (x, y) in enumerate(self.snake):
            color = 11 if i == 0 else 3
            pyxel.rect(x, y, 8, 8, color)
 
        # UI
        pyxel.text(5, 5, f"SCORE: {self.score}", 7)
        pyxel.text(5, 15, f"SPEED: {30 - self.speed}", 7)
 
        if self.game_over:
            pyxel.text(40, 60, "GAME OVER!", pyxel.frame_count % 16)
            pyxel.text(35, 80, "Press R to restart", 7)
 
SnakeGame()
informatica/programacion/python/pyxel/juego_tipo_snake.txt · Última modificación: por tempwin