-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript3.js
More file actions
98 lines (89 loc) · 2.57 KB
/
script3.js
File metadata and controls
98 lines (89 loc) · 2.57 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
// let h1=document.createElement('h1')
// h1.innerHTML="HI"
// let parent = document.getElementsByTagName('body')[0];
// parent.appendChild(h2Tag);
// h2Tag.innerHTML = "Elephant";
const ctx = document.getElementById("example").getContext("2d");
//////////////////////////////////////
const player = new Image();
player.src = "./images/player.png";
const redBall = new Image();
redBall.src = "./images/bb.png";
const ball = new Image();
ball.src = "./images/ball.gif";
const gameOver = new Image();
gameOver.src = "./images/gameover.jpg";
function drawPlayer(u) {
ctx.drawImage(player, u.x, u.y, 70, 50);
}
function drawBall(u, obs) {
if (obs) {
ctx.drawImage(ball, u.x, u.y, 60, 80);
} else {
ctx.drawImage(player, u.x, u.y, 50, 50);
}
}
let spawn = false;
/////////////////////////////
let frames = 0;
function mainLoop() {
if (playGame) {
frames++;
//////////////////////////
theGame.writeScore();
theGame.collisionDetect(theGame.theHero.x, theGame.theHero.y);
ctx.clearRect(0, 0, 400, 400);
// this is where we draw the hero
drawPlayer(theGame.theHero);
if (!spawn) {
ctx.drawImage(ball, 175, 0, 60, 80);
}
// then we draw all the obstacles
obstacleArray.forEach(eachObstacle => {
drawBall(eachObstacle, true);
});
if (theGame.numberOfBalls < 10) {
if (frames % 250 === 0) {
theGame.spawnObstacle();
spawn = true;
}
}
}
requestAnimationFrame(mainLoop);
}
let speed = 20;
document.onkeydown = function(e) {
if (e.keyCode === 32) {
playGame = !playGame;
}
if (e.key === "ArrowUp") {
theGame.collisionDetect(theGame.theHero.x, theGame.theHero.y - speed);
theGame.moveHero(theGame.theHero.x, theGame.theHero.y - speed);
}
if (e.key === "ArrowDown") {
theGame.collisionDetect(theGame.theHero.x, theGame.theHero.y + speed);
theGame.moveHero(theGame.theHero.x, theGame.theHero.y + speed);
}
if (e.key === "ArrowLeft") {
theGame.collisionDetect(theGame.theHero.x - speed, theGame.theHero.y);
theGame.moveHero(theGame.theHero.x - speed, theGame.theHero.y);
}
if (e.key === "ArrowRight") {
theGame.collisionDetect(theGame.theHero.x + speed, theGame.theHero.y);
theGame.moveHero(theGame.theHero.x + speed, theGame.theHero.y);
}
};
const start = document.querySelector(".start");
start.onclick = startGame;
let theGame;
let playGame = false;
function startGame() {
playGame = !playGame;
if (!theGame) {
theGame = new Game();
mainLoop();
}
start.innerHTML === "PLAY"
? (start.innerHTML = "PAUSE")
: (start.innerHTML = "PLAY");
}