Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| # Simple Car Game HTML + JavaScript embedded inside Gradio | |
| car_game_html = """ | |
| <style> | |
| body { | |
| background-color: #111; | |
| color: white; | |
| font-family: Arial, sans-serif; | |
| } | |
| #gameCanvas { | |
| background: #222; | |
| display: block; | |
| margin: 1em auto; | |
| border: 3px solid white; | |
| border-radius: 8px; | |
| } | |
| #instructions { | |
| text-align: center; | |
| margin-top: 0.5em; | |
| } | |
| </style> | |
| <canvas id="gameCanvas" width="400" height="600"></canvas> | |
| <div id="instructions">Use Left and Right Arrow keys to move the car</div> | |
| <script> | |
| const canvas = document.getElementById('gameCanvas'); | |
| const ctx = canvas.getContext('2d'); | |
| let car = { x: 180, y: 520, width: 40, height: 60 }; | |
| let obstacles = []; | |
| let speed = 5; | |
| let gameOver = false; | |
| let score = 0; | |
| document.addEventListener('keydown', function(event) { | |
| if (gameOver) return; | |
| if(event.key === "ArrowLeft" && car.x > 0) car.x -= 20; | |
| if(event.key === "ArrowRight" && car.x < canvas.width - car.width) car.x += 20; | |
| }); | |
| function createObstacle() { | |
| let size = 40; | |
| let x = Math.floor(Math.random() * (canvas.width - size)); | |
| obstacles.push({ x: x, y: -size, width: size, height: size }); | |
| } | |
| function drawCar() { | |
| ctx.fillStyle = '#00ffff'; | |
| ctx.fillRect(car.x, car.y, car.width, car.height); | |
| } | |
| function drawObstacles() { | |
| ctx.fillStyle = '#ff0000'; | |
| for(let i = 0; i < obstacles.length; i++) { | |
| let ob = obstacles[i]; | |
| ctx.fillRect(ob.x, ob.y, ob.width, ob.height); | |
| ob.y += speed; | |
| // Collision detection | |
| if ( | |
| ob.x < car.x + car.width && | |
| ob.x + ob.width > car.x && | |
| ob.y < car.y + car.height && | |
| ob.y + ob.height > car.y | |
| ) { | |
| gameOver = true; | |
| alert("Game Over! Your score: " + score); | |
| document.location.reload(); | |
| } | |
| // Remove obstacles that go off screen | |
| if (ob.y > canvas.height) { | |
| obstacles.splice(i, 1); | |
| i--; | |
| score++; | |
| } | |
| } | |
| } | |
| function drawScore() { | |
| ctx.fillStyle = '#fff'; | |
| ctx.font = '20px Arial'; | |
| ctx.fillText('Score: ' + score, 10, 30); | |
| } | |
| function gameLoop() { | |
| ctx.clearRect(0, 0, canvas.width, canvas.height); | |
| drawCar(); | |
| drawObstacles(); | |
| drawScore(); | |
| if (!gameOver) { | |
| requestAnimationFrame(gameLoop); | |
| } | |
| } | |
| setInterval(createObstacle, 1000); | |
| gameLoop(); | |
| </script> | |
| """ | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# ๐ Simple Car Game with Gradio & Hugging Face") | |
| gr.HTML(car_game_html) | |
| demo.launch() | |