Skip to content

Commit b66f5cb

Browse files
Commented loads
1 parent 4ce72a1 commit b66f5cb

File tree

3 files changed

+67
-73
lines changed

3 files changed

+67
-73
lines changed

assets/color.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
function color(imgSrc){
1+
function color(imgSrc){ // For given image source, returns eg rgb(20, 30, 40) with average color of image
22
var img = document.createElement('img');
33
img.src = imgSrc;
44
img.width = 1000;

html/game.html

Lines changed: 41 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
<link rel="stylesheet" href="https://bootswatch.com/cyborg/bootstrap.min.css" crossorigin="anonymous">
2222
<!-- Latest compiled and minified JavaScript -->
2323
<script src="color.js"></script>
24-
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
24+
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>
2525
<body style="background-color: transparent;">
2626
<center>
2727
<br>
@@ -47,87 +47,85 @@ <h1 class="win2" style="display: none">
4747
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.8/sweetalert2.min.css">
4848
<script>
4949
var bases = {
50-
lemon: "url('lemons-base.jpg')",
50+
lemon: "url('lemons-base.jpg')", // Links to fruits
5151
bannana: "url('bannana-base.jpg')",
5252
lime: "url('lime-base.jpg')",
5353
orange: "url('orange-base.jpg')"
5454
}
55-
var out = [];
56-
for (key in bases){
57-
if (!bases.hasOwnProperty(key)) continue;
58-
out.push(key)
55+
var out = []; // Initialise array of names of fruits
56+
for (key in bases){ // Go throught fruit objects
57+
if (!bases.hasOwnProperty(key)) continue; // If the current iteration is on a builtin property to a prototype, skip
58+
out.push(key) // Else, add the name of fruit to Array
5959
}
60-
function choose(choices) {
60+
function choose(choices) { // Makes a random choice from Array, eg. [1,2,5] => 1 or 2 or 5
6161
var index = Math.floor(Math.random() * choices.length);
6262
return choices[index];
6363
}
64-
var mappings = {
65-
KeyA: "lemon",
64+
var mappings = { // Mappings of keys to fruits
65+
KeyA: "lemon", // TODO: Move to config?
6666
KeyW: "bannana",
6767
KeyS: "lime",
6868
KeyD: "orange"
6969
}
7070
var current = {};
71-
function initPic(pic, word) {
72-
$("html").css("background-image", pic);
71+
72+
function initPic(pic, word) { // Function that sets the background and word
73+
$("html").css("background-image", pic); // TODO: Random location for word?
7374
$(".words").text(word);
7475
$(".words").css("color", color(pic.replace("url('", "").replace("')", "")))
7576
current.pic = pic;
7677
current.word = word;
7778
}
7879

79-
setTimeout(function () {
80-
// After xyz secs
81-
$("html").css("background-image", "");
82-
$("html").css("background-color", "black");
83-
$(".words").fadeOut()
84-
$(".win2").text("You scored " + rounds + " points.")
85-
$(".win2").fadeIn()
86-
$(".sboard").fadeIn()
87-
swal({
80+
setTimeout(function () { // Below code runs after 60 seconds has passed
81+
$("html").css("background-image", ""); // Remove background image
82+
$("html").css("background-color", "black"); // Set the background black
83+
$(".words").remove() // Remove the current word (ie banana)
84+
$(".win2").text("You scored " + rounds + " points.") // Set winning text
85+
$(".win2").fadeIn() // Fade in the winning text
86+
$(".sboard").fadeIn() // Fade in the scoreboard
87+
swal({ // Create a dialog box:
8888
title: 'What\'s your name?',
89-
input: 'text',
89+
input: 'text', // With an input box
9090
showCancelButton: true,
9191
confirmButtonText: 'Submit',
9292
showLoaderOnConfirm: true,
9393
allowOutsideClick: false
94-
}).then(function (name) {
94+
}).then(function (name) { // Then when user clicks submit
9595
$.ajax({
96-
url: '/add-score/',
96+
url: '/add-score/', // Make a web request to index.js with
9797
type: 'post',
98-
data: {
99-
access_token: 'XXXXXXXXXXXXXXXXXXX'
100-
},
98+
data: {},
10199
headers: {
102-
"XName": name,
100+
"XName": name, // The data name and score, where name is what the user put in the box
103101
"XScore": rounds
104102
},
105103
dataType: 'json',
106-
success: function (data) {
104+
success: function (data) { // Then when that data is successfully sent
107105
console.info(data);
108-
$.get("/get-score/", function (d) {
109-
var arr = JSON.parse(d);
110-
for (var i = 0; i < arr.length ; i++) {
111-
$(".leaderboard").append("<li class='list-group-item'> " + arr[i].name + " - " + arr[i].score + " </li>")
106+
$.get("/get-score/", function (d) { // Download the updated scoreboard
107+
var arr = JSON.parse(d); // Parse what we've been given
108+
for (var i = 0; i < arr.length ; i++) { // Go through all the top 20 scores
109+
$(".leaderboard").append("<li class='list-group-item'> " + arr[i].name + " - " + arr[i].score + " </li>") // And add them to the leaderboard
112110
}
113111
})
114112
}
115113
});
116114
})
117-
document.onkeyup = function () {};
115+
document.onkeyup = function () {}; // Finally, set the "onkeyup" function to empty so that users can't continue playing
118116
}, 60000)
119117

120-
var rounds = 0;
121-
initPic(bases[choose(out)], choose(out))
118+
var rounds = 0; // Start at 0 wins
119+
initPic(bases[choose(out)], choose(out)) // Set a random background and text
122120

123-
document.onkeyup = function (e) {
124-
var mapped = mappings[e.code]
125-
if(mapped == undefined) return;
126-
if (mapped == current.word) {
127-
var key = choose(out)
128-
var key2 = choose(out)
129-
rounds++;
130-
initPic(bases[key2], key)
121+
document.onkeyup = function (e) { // When someone lets go of a key
122+
var mapped = mappings[e.code] // Get the key from "mappings", which was defined earlier
123+
if(mapped == undefined) return; // If the key isn't registered, forget about it
124+
if (mapped == current.word) { // If the key is the correct one TODO: Count incorrect keys
125+
var key = choose(out) // Then pick two random fruits
126+
var key2 = choose(out) // ^
127+
rounds++; // Add 1 to the win counter
128+
initPic(bases[key2], key) // And set the background and text to those random fruits
131129
}
132130
else {
133131
}

index.js

Lines changed: 25 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,47 @@
1-
var app = require('express')();
2-
var http = require('http').Server(app);
3-
const fs = require('fs');
4-
var bodyParser = require('body-parser')
5-
app.use( bodyParser.json() ); // to support JSON-encoded bodies
1+
var app = require('express')(); // Import web framework
2+
var http = require('http').Server(app); // Import HTTP library and init it with web framework
3+
const fs = require('fs'); // Import FileSystem to save leaderboards
64

7-
8-
function getLeaderboard(callback) {
5+
function getLeaderboard(callback) { // This reads in the leaderboard and calls "callback([{name: Jay, score: 10}, {name: Dude, score: 20}])"
96
fs.readFile('storage/leaderboard.json', "utf8", function(err, data) {
107
callback(JSON.parse(data))
118
})
129
}
13-
function saveLeaderboard(data){
10+
function saveLeaderboard(data){ // This saves said json to the disk so it can be read later
1411
fs.writeFileSync("storage/leaderboard.json", JSON.stringify(data))
1512
}
16-
function getTopLeaderboard(callback1){
17-
getLeaderboard(function (data) {
18-
callback1(data.sort(function (a, b) {
13+
function getTopLeaderboard(callback1){ // Will call "callback1" with the top 20 players
14+
getLeaderboard(function (data) { // First it gets the leaderboard
15+
callback1(data.sort(function (a, b) { // Then sorts based on the logic:
1916
if (a.score > b.score) { return -1; };
20-
if (a.score < b.score) { return 1; };
21-
return 0; }).slice(0, 20)
17+
if (a.score < b.score) { return 1; }; // Which puts higher scores earlier in the array
18+
return 0; }).slice(0, 20) // Then returns the first 20 (Can be changed)
2219
)
2320
}
2421
)
2522
}
26-
function saveToLeaderboard(name, score){
27-
getLeaderboard(function(data){
28-
data.push({"name": name, "score": score})
29-
console.log(data)
30-
saveLeaderboard(data)
23+
function saveToLeaderboard(name, score){ // Saves a name and score to leaderboard
24+
getLeaderboard(function(data){ // First gets leaderboard
25+
data.push({"name": name, "score": score}) // Then adds an object with {name: "Jay", score: 69}
26+
console.log(data) // Logs for troubleshooting
27+
saveLeaderboard(data) // Saves the data
3128
})
3229
}
3330

34-
35-
app.get('/', function(req, res){
36-
res.sendFile(__dirname + '/html/game.html');
31+
app.get('/', function(req, res){ // On someone requesting the homepage
32+
res.sendFile(__dirname + '/html/game.html'); // Send them the "game.html" file
3733
});
38-
app.post("/add-score/", function(req, res){
39-
console.log(req.headers.xname, req.headers.xscore)
40-
saveToLeaderboard(req.headers.xname, parseInt(req.headers.xscore));
41-
res.end('{"done": true}')
34+
app.post("/add-score/", function(req, res){ // On someone triggering add-score
35+
console.log(req.headers.xname, req.headers.xscore) // Log their name and score
36+
saveToLeaderboard(req.headers.xname, parseInt(req.headers.xscore)); // Then parse their score and save it
37+
res.end('{"done": true}') // Reply with success
4238
})
43-
app.get("/get-score/", function(req, res) {
44-
getTopLeaderboard(function (data) { res.end( JSON.stringify(data) ) } )
39+
app.get("/get-score/", function(req, res) { // On someone requesting the leaderboard
40+
getTopLeaderboard(function (data) { res.end( JSON.stringify(data) ) } ) // Get the leaderboard then send it to them
4541
})
46-
app.use(require('express').static('assets'));
42+
app.use(require('express').static('assets')); // Finally if none of these rules match, search the "assets" folder, to allow serving images
4743

4844

49-
http.listen(4000, function(){
45+
http.listen(4000, function(){ // Then listen on port 4000 for connections
5046
console.log('listening on *:4000');
5147
});

0 commit comments

Comments
 (0)