GAME ULAR

<!DOCTYPE html>

<html lang="id">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Snake Game</title>


<style>

body{

    margin:0;

    background:#222;

    display:flex;

    justify-content:center;

    align-items:center;

    height:100vh;

    flex-direction:column;

    color:white;

    font-family:Arial, sans-serif;

}


h2{

    margin-bottom:10px;

}


canvas{

    background:#000;

    border:5px solid lime;

}


#score{

    margin:10px;

    font-size:22px;

    font-weight:bold;

}

</style>


</head>

<body>


<h2>🐍 Snake Game</h2>

<div id="score">Score : 0</div>


<canvas id="game" width="400" height="400"></canvas>


<p>Gunakan tombol ⬅⬆➡⬇ untuk bermain.</p>


<script>

const canvas = document.getElementById("game");

const ctx = canvas.getContext("2d");


const box = 20;


let snake = [

    {x:9*box, y:10*box}

];


let food = {

    x:Math.floor(Math.random()*20)*box,

    y:Math.floor(Math.random()*20)*box

};


let score = 0;


let direction = "";


document.addEventListener("keydown", event=>{

    if(event.key=="ArrowLeft" && direction!="RIGHT") direction="LEFT";

    if(event.key=="ArrowUp" && direction!="DOWN") direction="UP";

    if(event.key=="ArrowRight" && direction!="LEFT") direction="RIGHT";

    if(event.key=="ArrowDown" && direction!="UP") direction="DOWN";

});


function draw(){


    ctx.fillStyle="black";

    ctx.fillRect(0,0,400,400);


    // makanan

    ctx.fillStyle="red";

    ctx.fillRect(food.x,food.y,box,box);


    // ular

    for(let i=0;i<snake.length;i++){

        ctx.fillStyle=(i==0)?"lime":"green";

        ctx.fillRect(snake[i].x,snake[i].y,box,box);


        ctx.strokeStyle="black";

        ctx.strokeRect(snake[i].x,snake[i].y,box,box);

    }


    let headX=snake[0].x;

    let headY=snake[0].y;


    if(direction=="LEFT") headX-=box;

    if(direction=="UP") headY-=box;

    if(direction=="RIGHT") headX+=box;

    if(direction=="DOWN") headY+=box;


    // makan

    if(headX==food.x && headY==food.y){


        score++;

        document.getElementById("score").innerHTML="Score : "+score;


        food={

            x:Math.floor(Math.random()*20)*box,

            y:Math.floor(Math.random()*20)*box

        };


    }else{

        snake.pop();

    }


    let newHead={

        x:headX,

        y:headY

    };


    // game over

    if(

        headX<0 ||

        headY<0 ||

        headX>=400 ||

        headY>=400 ||

        collision(newHead,snake)

    ){

        clearInterval(game);

        alert("Game Over!\nScore : "+score);

        location.reload();

    }


    snake.unshift(newHead);


}


function collision(head,array){

    for(let i=0;i<array.length;i++){

        if(head.x==array[i].x && head.y==array[i].y){

            return true;

        }

    }

    return false;

}


let game=setInterval(draw,120);

</script>


</body>

</html>


Posting Komentar

0 Komentar