snake / app.py
prathamt's picture
Update app.py
89ef29a verified
Raw
History Blame Contribute Delete
2.17 kB
import gradio as gr
html_code = """
<!DOCTYPE html>
<html>
<head>
<style>
body {
background: black;
color: white;
text-align: center;
}
canvas {
background: #111;
border: 2px solid #0f0;
margin-top: 10px;
}
.controls button {
width: 60px;
height: 60px;
margin: 5px;
font-size: 20px;
}
</style>
</head>
<body>
<h2>🐍 Snake Game</h2>
<canvas id="game" width="300" height="300"></canvas>
<p>Score: <span id="score">0</span></p>
<div class="controls">
<br>
<button onclick="setDir(0,-20)">⬆️</button><br>
<button onclick="setDir(-20,0)">⬅️</button>
<button onclick="setDir(20,0)">➡️</button><br>
<button onclick="setDir(0,20)">⬇️</button>
</div>
<script>
let canvas = document.getElementById("game");
let ctx = canvas.getContext("2d");
let snake = [{x:150,y:150}];
let dx = 20, dy = 0;
let food = {x:100,y:100};
let score = 0;
document.addEventListener("keydown", changeDirection);
function changeDirection(event){
if(event.key==="ArrowUp" && dy===0){dx=0;dy=-20;}
if(event.key==="ArrowDown" && dy===0){dx=0;dy=20;}
if(event.key==="ArrowLeft" && dx===0){dx=-20;dy=0;}
if(event.key==="ArrowRight" && dx===0){dx=20;dy=0;}
}
function setDir(x,y){
dx = x;
dy = y;
}
function draw(){
ctx.fillStyle="#111";
ctx.fillRect(0,0,300,300);
ctx.fillStyle="#0f0";
snake.forEach(s=>{
ctx.fillRect(s.x,s.y,20,20);
});
ctx.fillStyle="red";
ctx.fillRect(food.x,food.y,20,20);
let head = {x: snake[0].x + dx, y: snake[0].y + dy};
snake.unshift(head);
if(head.x===food.x && head.y===food.y){
score++;
document.getElementById("score").innerText = score;
food = {
x: Math.floor(Math.random()*15)*20,
y: Math.floor(Math.random()*15)*20
};
} else {
snake.pop();
}
if(head.x<0 || head.y<0 || head.x>=300 || head.y>=300){
alert("Game Over! Score: " + score);
location.reload();
}
}
setInterval(draw, 120);
</script>
</body>
</html>
"""
with gr.Blocks() as demo:
gr.HTML(html_code)
demo.launch(server_name="0.0.0.0", server_port=7860)