CoolFace
Apppublic

awacke1/TensorflowJS

sourceHugging Faceupdated 2y agoView on Hugging Face
1likes
app.js90 linesDownload Raw Back to root
1const canvas = document.getElementById('gameCanvas');2const ctx = canvas.getContext('2d');3 4const agent = {5    x: canvas.width / 2,6    y: canvas.height - 30,7    dx: 2,8    dy: -2,9    radius: 10,10    score: 011};12 13const obstacle = {14    x: Math.random() * canvas.width,15    y: 0,16    width: 100,17    height: 20,18    dy: 219};20 21function drawAgent() {22    ctx.beginPath();23    ctx.arc(agent.x, agent.y, agent.radius, 0, Math.PI * 2);24    ctx.fillStyle = "#0095DD";25    ctx.fill();26    ctx.closePath();27}28 29function drawObstacle() {30    ctx.beginPath();31    ctx.rect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);32    ctx.fillStyle = "#FF0000";33    ctx.fill();34    ctx.closePath();35}36 37function moveObstacle() {38    obstacle.y += obstacle.dy;39    if (obstacle.y > canvas.height) {40        obstacle.y = 0;41        obstacle.x = Math.random() * canvas.width;42        agent.score += 1;43    }44}45 46function detectCollision() {47    if (48        agent.x > obstacle.x && agent.x < obstacle.x + obstacle.width &&49        agent.y > obstacle.y && agent.y < obstacle.y + obstacle.height50    ) {51        return true;52    }53    return false;54}55 56function updateAgent(action) {57    if (action === 'left' && agent.x > agent.radius) {58        agent.x -= agent.dx;59    }60    if (action === 'right' && agent.x < canvas.width - agent.radius) {61        agent.x += agent.dx;62    }63}64 65function draw() {66    ctx.clearRect(0, 0, canvas.width, canvas.height);67    drawAgent();68    drawObstacle();69    moveObstacle();70 71    if (detectCollision()) {72        alert("GAME OVER\nScore: " + agent.score);73        document.location.reload();74    } else {75        requestAnimationFrame(draw);76    }77}78 79async function getAction() {80    const model = await tf.loadLayersModel('model.json');81    const input = tf.tensor2d([agent.x, agent.y, obstacle.x, obstacle.y, obstacle.dy], [1, 5]);82    const prediction = model.predict(input);83    const action = (prediction.dataSync()[0] > 0.5) ? 'right' : 'left';84    updateAgent(action);85    setTimeout(getAction, 100);  // Adjust delay for smoother or faster action86}87 88draw();89getAction();90