Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the feature to display the timer in seconds #3

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"files.autoSave": "afterDelay"
}
Empty file added 1
Empty file.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -17,11 +17,11 @@ Here's a walkthrough of implemented user stories.

- [x] The user can move their character with the arrow keys.
- [x] The user can see a monster.
- [ ] The monster is placed at a random location within the game boundaries.
- [x] The monster is placed at a random location within the game boundaries.
- [x] The user can catch a monster by moving their character to the same location as a monster.
- [ ] When the user catches a monster, a new monster is placed randomly upon the screen.
- [ ] The user can see the numbers of monsters she has caught. Every time she catches a monster, the number should increment by one.
- [ ] The game ends when the user has caught 20 monsters. The total time elapsed is displayed upon game completion, in seconds.
- [x] When the user catches a monster, a new monster is placed randomly upon the screen.
- [x] The user can see the numbers of monsters she has caught. Every time she catches a monster, the number should increment by one.
- [x] The game ends when the user has caught 20 monsters. The total time elapsed is displayed upon game completion, in seconds.
- [ ] The user can access this game from the internet (e.g. using Netlify).
- [ ] The code has been reviewed by at least one other person, using Pull Requests on GitHub.

177 changes: 95 additions & 82 deletions game.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
/*
Code modified from:
http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/
using graphics purchased from vectorstock.com
*/

/* Initialization.
Here, we create and add our "canvas" to the page.
We also load all of our images.
*/


let canvas;
let ctx;
let timeStart;
let timeEnd;
let totalTime;

canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
@@ -24,101 +15,118 @@ let bgImage, heroImage, monsterImage;

function loadImages() {
bgImage = new Image();
bgImage.onload = function () {
bgImage.onload = function() {
// show the background image
bgReady = true;
};
bgImage.src = "images/background.png";

heroImage = new Image();
heroImage.onload = function () {
heroImage.onload = function() {
// show the hero image
heroReady = true;
};
heroImage.src = "images/hero.png";

monsterImage = new Image();
monsterImage.onload = function () {
monsterImage.onload = function() {
// show the monster image
monsterReady = true;
};
monsterImage.src = "images/monster.png";
}

/**
* Setting up our characters.
*
* Note that heroX represents the X position of our hero.
* heroY represents the Y position.
* We'll need these values to know where to "draw" the hero.
*
* The same applies to the monster.
*/

let heroX = canvas.width / 2;
let heroY = canvas.height / 2;

generateLocation = canvas => {
let x = Math.random() * canvas.width + 1;
let y = Math.random() * canvas.height + 1;
return { x, y };
};

let monsterX = 100;
let monsterY = 100;
let countMonsterCaught = 0;

// Keyboard Listeners

/**
* Keyboard Listeners
* You can safely ignore this part, for now.
*
* This is just to let JavaScript know when the user has pressed a key.
*/
let keysDown = {};
function setupKeyboardListeners() {
// Check for keys pressed where key represents the keycode captured
// For now, do not worry too much about what's happening here.
addEventListener("keydown", function (key) {
keysDown[key.keyCode] = true;
}, false);

addEventListener("keyup", function (key) {
delete keysDown[key.keyCode];
}, false);
addEventListener(
"keydown",
function(key) {
if (!timeStart) {
timeStart = performance.now();
console.log(timeStart);
}
keysDown[key.keyCode] = true;
},
false
);

addEventListener(
"keyup",
function(key) {
delete keysDown[key.keyCode];
},
false
);
}


/**
* Update game objects - change player position based on key pressed
* and check to see if the monster has been caught!
*
* If you change the value of 5, the player will move at a different rate.
*/
let update = function () {
if (38 in keysDown) { // Player is holding up key
heroY -= 5;
const update = () => {
if (38 in keysDown) {
//UP
heroY -= 2;
}
if (40 in keysDown) { // Player is holding down key
heroY += 5;
if (40 in keysDown) {
//DOWN
heroY += 2;
}
if (37 in keysDown) { // Player is holding left key
heroX -= 5;
if (37 in keysDown) {
//LEFT
heroX -= 2;
}
if (39 in keysDown) { // Player is holding right key
heroX += 5;
if (39 in keysDown) {
//RIGHT
heroX += 2;
}

// Check if player and monster collided. Our images
// are about 32 pixels big.
// Check if player and monster collided
if (
heroX <= (monsterX + 32)
&& monsterX <= (heroX + 32)
&& heroY <= (monsterY + 32)
&& monsterY <= (heroY + 32)
heroX <= monsterX + 32 &&
monsterX <= heroX + 32 &&
heroY <= monsterY + 32 &&
monsterY <= heroY + 32
) {
// Pick a new location for the monster.
// Note: Change this to place the monster at a new, random location.
monsterX = monsterX + 50;
monsterY = monsterY + 70;
if (countMonsterCaught >= 3) {
timeEnd = performance.now();
totalTime = timeEnd - timeStart;
console.log(`Total Time ${totalTime}`);
gameOver();
} else {
countMonsterCaught++;
let { x, y } = generateLocation(canvas); // destructuring
monsterX = x; //generate new location for Monster
monsterY = y;
}
if (totalTime) {
document.getElementById("timer").innerHTML = `${(totalTime/1000).toFixed(2)} seconds`;
}
document.getElementById("score").innerHTML = countMonsterCaught;
}
};

/**
* This function, render, runs as often as possible.
*/
var render = function () {
const gameOver = () => {
heroX = canvas.width / 2;
heroY = canvas.height / 2;
startGame();
document.getElementById("score").innerHTML = countMonsterCaught;
countMonsterCaught = 0;
};

const render = function() {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
@@ -131,24 +139,29 @@ var render = function () {
};

/**
* The main game loop. Most every game will have two distinct parts:
* update (updates the state of the game, in this case our hero and monster)
* render (based on the state of our game, draw the right things)
*/
var main = function () {
update();
* The main game loop.
* update + render */

let main = function() {
update();
render();
// Request to do this again ASAP. This is a special method
// for web browsers.
requestAnimationFrame(main);
requestAnimationFrame(main); // Request to do this again ASAP.
};

// Cross-browser support for requestAnimationFrame.
// Safely ignore this line. It's mostly here for people with old web browsers.
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
requestAnimationFrame =
w.requestAnimationFrame ||
w.webkitRequestAnimationFrame ||
w.msRequestAnimationFrame ||
w.mozRequestAnimationFrame;

// Let's play this game!
loadImages();
setupKeyboardListeners();
main();
const startGame = () => {
loadImages();
setupKeyboardListeners();
main();
};

startGame();
9 changes: 8 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
@@ -5,6 +5,13 @@
<title>Best Game Ever!</title>
</head>
<body>
<div>
<p>Score: </p><span id='score'></span>
<p>Timer: </p><span id='timer'></span>

</div>


<script src="game.js"></script>
</body>
</html>
</html>