Skip to content

Snake #345

@pespespesjepes-hash

Description

@pespespesjepes-hash
<title>Retro Snake – hezčí had</title> <style> body { background: #000; color: white; text-align: center; font-family: Arial, sans-serif; } canvas { background: #111; display: block; margin: 20px auto; border: 2px solid #555; border-radius: 10px; } </style>

Snake Retro – krásný had

<script> const canvas = document.getElementById('game'); const ctx = canvas.getContext('2d');

const box = 20;
let snake = [{x: 10box, y: 10box}];
let food = spawnFood();
let dx = box;
let dy = 0;
let score = 0;

document.addEventListener("keydown", direction);

function direction(event){
if(event.key === "ArrowUp" && dy === 0){ dx=0; dy=-box; }
if(event.key === "ArrowDown" && dy === 0){ dx=0; dy=box; }
if(event.key === "ArrowLeft" && dx === 0){ dx=-box; dy=0; }
if(event.key === "ArrowRight" && dx === 0){ dx=box; dy=0; }
}

function spawnFood(){
return {
x: Math.floor(Math.random()*20)*box,
y: Math.floor(Math.random()*20)*box
};
}

function draw(){
// pozadí
ctx.fillStyle = "#111";
ctx.fillRect(0, 0, canvas.width, canvas.height);

// had
for(let i=0;i<snake.length;i++){
    let gradient = ctx.createLinearGradient(snake[i].x, snake[i].y, snake[i].x+box, snake[i].y+box);
    if(i===0){
        gradient.addColorStop(0, "#00FF00");
        gradient.addColorStop(1, "#88FF88");
    } else {
        gradient.addColorStop(0, "#33AA33");
        gradient.addColorStop(1, "#66CC66");
    }
    ctx.fillStyle = gradient;
    ctx.beginPath();
    ctx.arc(snake[i].x + box/2, snake[i].y + box/2, box/2, 0, Math.PI*2);
    ctx.fill();
    ctx.closePath();
}

// jídlo
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(food.x + box/2, food.y + box/2, box/2, 0, Math.PI*2);
ctx.fill();
ctx.closePath();

// skóre
ctx.fillStyle = "white";
ctx.font = "20px Arial";
ctx.fillText("Skóre: " + score, 10, 20);

// pohyb hada
let snakeX = snake[0].x + dx;
let snakeY = snake[0].y + dy;

// sbírání jídla
if(snakeX === food.x && snakeY === food.y){
    score++;
    food = spawnFood();
} else {
    snake.pop();
}

let newHead = {x: snakeX, y: snakeY};

// konec hry
if(snakeX < 0 || snakeX >= canvas.width || snakeY < 0 || snakeY >= canvas.height || snake.some(seg => seg.x === newHead.x && seg.y === newHead.y)){
    alert("Konec hry! Skóre: " + score);
    snake = [{x: 10*box, y: 10*box}];
    dx = box; dy = 0;
    score = 0;
    food = spawnFood();
}

snake.unshift(newHead);

}

setInterval(draw, 100);
</script>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions