File size: 2,174 Bytes
89ef29a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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)