Spaces:
Running
Running
const canvas = document.getElementById('gameCanvas'); | |
const ctx = canvas.getContext('2d'); | |
const agent = { | |
x: canvas.width / 2, | |
y: canvas.height - 30, | |
dx: 2, | |
dy: -2, | |
radius: 10, | |
score: 0 | |
}; | |
const obstacle = { | |
x: Math.random() * canvas.width, | |
y: 0, | |
width: 100, | |
height: 20, | |
dy: 2 | |
}; | |
function drawAgent() { | |
ctx.beginPath(); | |
ctx.arc(agent.x, agent.y, agent.radius, 0, Math.PI * 2); | |
ctx.fillStyle = "#0095DD"; | |
ctx.fill(); | |
ctx.closePath(); | |
} | |
function drawObstacle() { | |
ctx.beginPath(); | |
ctx.rect(obstacle.x, obstacle.y, obstacle.width, obstacle.height); | |
ctx.fillStyle = "#FF0000"; | |
ctx.fill(); | |
ctx.closePath(); | |
} | |
function moveObstacle() { | |
obstacle.y += obstacle.dy; | |
if (obstacle.y > canvas.height) { | |
obstacle.y = 0; | |
obstacle.x = Math.random() * canvas.width; | |
agent.score += 1; | |
} | |
} | |
function detectCollision() { | |
if ( | |
agent.x > obstacle.x && agent.x < obstacle.x + obstacle.width && | |
agent.y > obstacle.y && agent.y < obstacle.y + obstacle.height | |
) { | |
return true; | |
} | |
return false; | |
} | |
function updateAgent(action) { | |
if (action === 'left' && agent.x > agent.radius) { | |
agent.x -= agent.dx; | |
} | |
if (action === 'right' && agent.x < canvas.width - agent.radius) { | |
agent.x += agent.dx; | |
} | |
} | |
function draw() { | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
drawAgent(); | |
drawObstacle(); | |
moveObstacle(); | |
if (detectCollision()) { | |
alert("GAME OVER\nScore: " + agent.score); | |
document.location.reload(); | |
} else { | |
requestAnimationFrame(draw); | |
} | |
} | |
async function getAction() { | |
const model = await tf.loadLayersModel('model.json'); | |
const input = tf.tensor2d([agent.x, agent.y, obstacle.x, obstacle.y, obstacle.dy], [1, 5]); | |
const prediction = model.predict(input); | |
const action = (prediction.dataSync()[0] > 0.5) ? 'right' : 'left'; | |
updateAgent(action); | |
setTimeout(getAction, 100); // Adjust delay for smoother or faster action | |
} | |
draw(); | |
getAction(); | |