File size: 1,465 Bytes
9fd0d3c
 
3ab14b8
c94f5bc
 
 
 
 
 
3ab14b8
c94f5bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ab14b8
 
 
 
c94f5bc
3ab14b8
 
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
import gradio as gr

def snake_game():
    return """
    <style>
        body { margin: 0; padding: 0; }
        #gameCanvas { border: 1px solid black; }
    </style>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <script>
        let canvas = document.getElementById('gameCanvas');
        let ctx = canvas.getContext('2d');
        let snake = [{x: 10, y: 10}];
        let food = {x: 15, y: 15};
        let gameLoop;

        function init() {
            gameLoop = setInterval(game, 100);
        }

        function game() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            snake.unshift({x: snake[0].x, y: snake[0].y});
            snake[0].x += 1; // Simple movement for demonstration
            if(snake[0].x > 39) snake[0].x = 0; // Wrap around

            ctx.fillStyle = "green";
            snake.forEach(part => {
                ctx.fillRect(part.x * 10, part.y * 10, 10, 10);
            });

            ctx.fillStyle = "red";
            ctx.fillRect(food.x * 10, food.y * 10, 10, 10);

            if(snake[0].x == food.x && snake[0].y == food.y) {
                food.x = Math.floor(Math.random() * 40);
                food.y = Math.floor(Math.random() * 40);
            } else {
                snake.pop();
            }
        }

        // Start the game
        init();
    </script>
    """

with gr.Blocks() as demo:
    gr.HTML(snake_game(), elem_id="snake-game-block")

demo.launch()