summaryrefslogtreecommitdiff
path: root/resources/js/scene.js
blob: 194a77b1d8667b3153e296b0c231e29f8e040bb0 (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
class Scene {

    constructor(component_size, no_of_components) {
        this.component_size = component_size;
        this.no_of_components = no_of_components;
        this.components = new Array;
        this.gameArea = {};
        this.initGameArea();
        this.initComponents();
        this.started = false;
    }

    initComponents() {
        for (let i = 0; i < this.no_of_components; i++) {
            let new_component = new Component(
                this.component_size,
                "black",
                Math.random() * this.gameArea.canvas.width,
                Math.random() * this.gameArea.canvas.height,
                Math.random() * 360
            );
            this.components.push(new_component);
        }
    }

    initGameArea() {
        this.gameArea = new GameArea(600, 600);
        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, 5);
        this.started = true;
    }

    update() {
        this.gameArea.clear();
        for (let i = 0; i < this.no_of_components; i++) {
            this.components[i].move(this.gameArea.context);
        }
    }

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

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

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

}