Spaces:
Running
Running
import gradio as gr | |
def snake_game(): | |
# This function will just return the HTML since no user input is needed for this simple demo | |
return f""" | |
<div id="gameCanvas" style="width:400px;height:400px;border:1px solid black;"></div> | |
<script> | |
// Insert the JavaScript code here (Remove the script tags as they're not needed within this context) | |
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; | |
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(); | |
}} | |
}} | |
init(); | |
</script> | |
""" | |
with gr.Blocks() as demo: | |
gr.HTML(snake_game()) | |
demo.launch() |