forked from Mercer01/hackTheGame
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
83 lines (71 loc) · 2.09 KB
/
main.js
File metadata and controls
83 lines (71 loc) · 2.09 KB
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
'use strict';
/**
* A screen is a polymorphic object
* It refers to the current state of the game
* Each screen has an update and redraw function
*/
let screen = null;
/**
* Allows the screens to switch between eachother
* Passes in a number (these are in lib.js)
* This will then reset the screen object to the new screen
* @param {function} switchTo This function
*/
function switchScreen(switchTo) {
//Removes event listens and then resets the screen
function destroyAndSwitch(to) {
//Remove event listeners by clearing the nodes and that
const newCanvas = canvas.cloneNode(true);
canvas.parentNode.replaceChild(newCanvas, canvas);
//reinit
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
//Clear
context.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
//And reset
to.init(switchScreen);
screen = to;
}
if (switchTo === MAIN_MENU_SCREEN) {
destroyAndSwitch(new MainMenuScreen());
} else if (switchTo === REGISTR_SCREEN) {
destroyAndSwitch(new RegistrationScreen());
} else if (switchTo === PRESENT_SCREEN) {
destroyAndSwitch(new PresentationScreen());
} else if (switchTo === DEV_SCREEN) {
destroyAndSwitch(new DevelopementScreen());
}
}
/**
* Main entry point of the program
*/
function init() {
canvas.width = GAME_WIDTH;
canvas.height = GAME_HEIGHT;
//Init the first screen
switchScreen(MAIN_MENU_SCREEN);
//Begin the main loop
window.requestAnimationFrame(loop);
}
/**
* Sleeps the thread so it doesn't run too fast
* @param ms Milliseconds to sleep for
*/
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* MAIN GAME LOOP
* Loops throughout the game
* INPUT -> CLEAR -> DRAW -> REPEAT
* A screen refers to the current stage of the game
* EG: Main menu, presentation, or dev stage
*/
function loop() {
screen.update();
context.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
screen.redraw();
window.requestAnimationFrame(loop);
sleep(10);
}
init();