summaryrefslogtreecommitdiff
path: root/resources/js/scene.js
blob: f8858b67ff4d6e9bc25dd57ca7857977386cb45c (plain)
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
91
92
93
94
class Scene {

    // boid radius
    // no of boids
    // scene width
    // scene height
    constructor(boid_radius, no_of_boids) {
        this.boid_radius = boid_radius;
        this.no_of_boids = no_of_boids;
        this.boids = [];
        this.gameArea = {};
        this.started = false;
        this.width = 600;
        this.height = 600;

        this.initGameArea();
        this.initBoids();
    }

    initBoids() {
        let boids = [];

        for (let i = 0; i < this.no_of_boids; i++) {
            boids.push(new Boid(
                this.boid_radius,
                "black",
                // 300, 300, 90,
                parseFloat(Number(Math.random() * (this.gameArea.canvas.width - 100) + 50).toFixed(1)),
                parseFloat(Number(Math.random() * (this.gameArea.canvas.height - 100) + 50).toFixed(1)),
                parseFloat(Number(Math.random() * 360).toFixed(2)),
                i,
                this.width,
                this.height
            ));
        }

        this.boids = boids;
    }

    initGameArea() {
        this.gameArea = new GameArea(this.width, this.height);
        this.gameArea.init()
    }

    start() {
        if (this.started) {
            return;
        }

        // Kinda annoying, setInterval is a piece of shite and is always run from global scope
        // Therefore "this.update" will be undefined unless we bind it
        const updateMe = this.update.bind(this);
        this.interval = setInterval(updateMe, 20);
        // updateMe();
        this.started = true;
    }

    update() {
        if (!this.started) {
            return;
        }
        this.gameArea.clear();
        for (let i = 0; i < this.boids.length; i++) {
            let result = this.boids[i].move(this.boids);
            this.boids[i].draw(this.gameArea.context);
            if (!result) {
                continue;
            }

        }
        return true;
    }

    stop() {
        if (!this.started) {
            return;
        }

        clearInterval(this.interval);
        this.interval = null;
        this.started = false;
    }

    reset() {
        if (this.started) {
            this.stop();
        }
        this.boids = new Array;
        this.initBoids();
        this.gameArea.clear();
        this.started = false;
    }

}