-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathindex.js
More file actions
121 lines (108 loc) · 3.02 KB
/
index.js
File metadata and controls
121 lines (108 loc) · 3.02 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
window.addEventListener("load", function() {
function clear() {
ctx.clearRect(0,0,width,height);
}
function drawRandomShape() {
let top = Math.floor(Math.random() * (height -50));
let left = Math.floor(Math.random() * (width -50));
let pick = Math.floor(Math.random() * 4);
clear();
switch (pick){
case 0: //white0 white triangle = up
expectedKey = 'ArrowUp';
ctx.fillStyle = "white";
ctx.beginPath();
ctx.moveTo(left,top);
ctx.lineTo(left+50, top+50);
ctx.lineTo(left, top+50);
ctx.fill();
ctx.closePath();
break;
case 1: //red1 red square = down
expectedKey = 'ArrowDown';
ctx.fillStyle = 'red';
ctx.fillRect(
top,
left,
50,
50);
break;
case 2: //red0 red triangle = left
expectedKey = 'ArrowLeft';
ctx.fillStyle = "red";
ctx.beginPath();
ctx.moveTo(left,top);
ctx.lineTo(left+50, top+50);
ctx.lineTo(left, top+50);
ctx.fill();
ctx.closePath();
break;
case 3: //white1 white square = right
expectedKey = 'ArrowRight';
ctx.fillStyle = 'white';
ctx.fillRect(
top,
left,
50,
50);
break;
}
}
function drawGameStartText() {
console.log('End Game');
clear();
ctx.font = '2em serif';
ctx.textAlign = 'center';
ctx.fillStyle = 'white';
ctx.fillText('Press the space bar to start the game.',
Math.floor(width/2),
Math.floor(height/2.25));
if(score > 0){
ctx.fillText('Last score is ' + score,
Math.floor(width/2),
Math.floor(height/2));
}
}
function startGame(){
console.log('Starting Game');
scoreSpan.innerText = score = 0;
seconds = 30;
gameOn = true;
clear();
drawRandomShape();
intervalId = setInterval(function(){
timerSpan.innerText = --seconds;
if(seconds <= 0) {
clearInterval(intervalId);
gameOn = false;
drawGameStartText();
}
}, 1000);
}
var canvas = document.getElementById("shapes-game"),
height = canvas.scrollHeight,
width = canvas.scrollWidth,
gameOn = false,
expectedKey = undefined,
ctx = canvas.getContext('2d'),
timerSpan = document.getElementById("time-remaining"),
scoreSpan = document.getElementById("score-val"),
score = 0,
seconds = 0,
intervalId;
canvas.width = width;
canvas.height = height;
document.addEventListener("keyup", function(e) {
if(e.key === ' ' && !gameOn){
startGame();
}else if(gameOn && e.key == expectedKey){ //right key
scoreSpan.innerText = ++score;
drawRandomShape();
}else if(gameOn && 'ArrowUpArrowDownArrowLeftArrowRight'.includes(e.key)){ //wrong key
scoreSpan.innerText = --score;
drawRandomShape();
}
});
//On Load
drawGameStartText();
});