Project: You are a game developer creating a super awesome battle card game. When the game ends, if a player makes the cut, he is added to the high score list. In any case, the high score list is displayed.
Below certain code block, you will find an orange information button. Click the EXAMPLE button.
When you click the button, it will display information about the above code block. This may
include descriptions or links to the appropriate lessons.
Now, click it again to make the information disappear. Happy Coding, my trusted Coding Cadet!
'use strict';
var db = require("../database/db.js"); // connection variable
See my lessons on NodeJS/PostgreSQL connection variable and npm install pg
// Player Object
function Player(name,score){
this.name = name;
this.score = score;
}
This is a JavaScript object type called "Player" with the properties: name and score. See my lesson: JavaScript Objects
// Data Keys
function showKeys(data){
var keys = Object.keys(data);
console.log(keys);
};
Object.keys() is a predefined JavaScript function that
returns an array of keys. More info on arrays, keys, objects: JavaScript Datasets
// is it a high score?
function isHighscore(score,highscores){
var toReturn = 0;
for(var i=0; i<highscores.length; i++){
var hs = highscores[i].score;
if(score > hs){
toReturn++;
}
}
return toReturn;
}
This function loops through the high scores and determines if a the current player's score qualifies to be on the highscorelist. For homework, you are going to alter this function! More info at the bottom of the page!
// Code if player made the high score list
function addChamp(name,score){
var statement = 'insert into high_scores (player,score)
values($1, $2) returning *';
var values = [name,score];
db.query(statement, values, function(err,res){
if(err) throw err;
else {
console.log("Congrats you made the highscore list!");
}
});
}
// Code if player did not make the highscore list
function notChamp(){
console.log("sorry you did not make the high score list");
}
// game over code
function gameOver(name,score){
var statement = "select * from high_scores";
db.query(statement, function(err,res){
if (err) {
throw err;
}
else {
var data = res.rows;
var beats = isHighscore(score,data);
if(beats > 0){
addChamp(name,score);
}
else {
notChamp();
}
}
});
}
This is the code that executes when the game ends.
See my lessons:
NodeJS Query Function
PostgreSQL Queries
// A Player method that executes game over code
Player.prototype.gameover = function (){
var score = this.score;
var name = this.name;
gameOver(name,score);
}
Make the following changes to the code above:
1) Make sure no more than 10 players are on the highscore highscorelist
2) If the player made the highscore list, return a message that tells him
where he placed.