File size: 2,099 Bytes
7b17fdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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();