console.log(scores) output
scores.json
[
{"name":"Hatnix","score": 9},
{"name":"Caysind","score": 8},
{"name":"Ambrosine","score": 7},
{"name":"Kozross","score": 6},
{"name":"Jookia","score": 5},
{"name":"Arthur","score": 4},
{"name":"John Smith","score": 3},
{"name":"Sir Diealot","score": 2},
{"name":"Commander Candy","score": 1},
{"name":"Robert","score": 0}
]
In summary, get_scores():
- Takes in one parameter-- a callback
- Fetched data from scores.json
- fetch() responded with scores.json's data as an HTTP response
- Used JSON.stringify to turn the HTTP request into a JSON string and stored that value in a variable called scores
- Passed scores into the callback function
JSON Data in an HTML List
Next, we will write a function called list_scores that will pass into get_scores. It will take in scores as its only parameter, then loop through the contents to place inside an HTML list element (ul). This function displays the data we fetched from scores.JSON into the high score list seen by players.
Code
const List = document.getElementById("highscores");
var list_scores = function (scores) {
// turn scores JSON to a JavaScript object
let object = JSON.parse(scores);
// Store lowest high score for later
let lowest_score = object[9].score;
document.getElementById('lowscore').value = lowest_score;
// loop through high scores
for (let i=0; i<object.length; i++) {
// console.log(object[i]);
let li = document.createElement("LI");
let text = document.createTextNode(object[i].name + " ... " + object[i].score);
li.appendChild(text);
List.appendChild(li);
if (i===0) {
li.setAttribute('class',"top1");
}
if (i===1) {
li.setAttribute('class',"top2");
}
if (i===2) {
li.setAttribute('class',"top3");
}
}
}
Description
➼ list_scores - Our function is stored in a variable called
list_scores.
➼ let object - We are parsing our JSON string into a
JavaScript object and storing it in a variable named
object
➼ lowest_score - The object at index 9 is the lowest highscore on the highscore list. We are storing that value in a hidden input element with the ID 'lowscore'.
➼ for(){} - A JavaScript for loop is used to loop through the contents of
object. Each element inside
object (i.e., {"name":"Hatnix","score":9}) will run through the code in the block.
➼ li - We are creating a new
list item (<li></li>) and storing it in a variable named
li. The we are creating text (i.e., "Hatnix ... 9") and putting it inside the list item.
➼ append list - We are taking our newly created list item and placing it inside our list element (<ol id="highscores"></ol>).
➼ setAttribute - We are changing the class of the top three high scores.
In summary, list_scores():
- Takes in one parameter-- a JSON string
- Convers the JSON string into a JavaScript object stored in the variable object
- Loops through object to create list items containing the data for each high score, then sticks the list item inside the high score list.
index.html
Now let's take a look at our HTML file. I moved some things around and added a few elements since Dice Game Version 1.
<html>
<!-- Page Head-->
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<title>Dice Roller Durby V2</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="description" content="Play a fun dice game. Try your luck and get on the highscore list!">
</head>
<!-- Page Body: on load execute list_scores()-->
<body onload="get_scores(list_scores)">
<h1 align="center">JavaScript Dice Game Version 2</h1>
<div class="row" align="center">
<!-- Column 1 -->
<div class="col-3">
<h2>Your Dice</h2>
<!-- Player's Dice -->
<img src="images/d1.png" id="mydice1">
<img src="images/d1.png" id="mydice2"><br>
<h2>Enemy"s Dice</h2>
<!-- Enemey's Dice-->
<img src="images/e1.png" id="hisdice1">
<img src="images/e1.png" id="hisdice2">
<div id="enemy_score"></div><br>
</div>
<!-- Column 2 -->
<div class="col-3">
<!-- Play button -->
<button class="greenBut" onClick="throwdice()">Roll Dice</button>
<!-- Game Form (myform)-->
<form id="myform">
Your name:<br>
<!-- Player's name-->
<input name="player_name" maxlength="20" class="greenBut" type="text" id="player_name" placeholder="Type Your Name" required>
<!-- Player's Score -->
<br>Your score:<br>
<input name="player_score" class="greenBut" type="number" value=0 id="score" readonly></input><br></h3>
<!-- Submit Button -->
<button type="submit" class="greenBut">End Game</button>
</form>
</div>
<!-- Column 3 -->
<div class="col-3">
<br><br>
<!-- "message" image-->
<img src="images/good-luck.gif" id="message" alt="Good Luck!"/>
</div>
<!-- Column 4 -->
<div class="col-3" align="center">
<h2>High Scores</h2>
<!-- error container -->
<div id="error"></div>
<!-- High Score Lists -->
<ol id="highscores"></ol>
<!-- lowest high score hidden input -->
<input id="lowscore" type="hidden">
</div>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Reload Data
We are about to write the code to submit After we submit myform, but before we do we will create a function called resetForm. After we submit myform, we want to reload the high score list and the player's score to get back at zero. resetForm will accomplish these tasks.
function resetForm () {
while (List.hasChildNodes()) {
List.removeChild(List.firstChild);
}
get_scores(list_scores);
document.getElementById("score").value = 0;
score=0;
}
In summary, resetForm():
- Loops throgh the HTML high score list and deletes all its <li> elements
- Fetches scores.json and remakes the high score list
- Sets the value of score to 0
Keeping Score
Since resetForm references our score variable, let's take a look at the code that determines the score. We begin by initializing the variable score at 0 (var score = 0;). If the total of the player's dice is higher than the enemy's dice, the player gets one point added to his score. If the enemy's total is greater than the player's total, then one point is subtracted from the player's score. If it is a tie, no points are gained or lost.
// player's score
var score = 0;
// "message" img alt text array
var side_alt = ["roll: 1", "roll: 2", "roll: 3", "roll: 4", "roll: 5", "roll: 6"];
function throwdice(){
//create a random integer between 1 and 6
let rand1 = Math.round(Math.random()*5) + 1;
let rand2 = Math.round(Math.random()*5) + 1;
let rand3 = Math.round(Math.random()*5) + 1;
let rand4 = Math.round(Math.random()*5) + 1;
// Set Image src
document.getElementById("mydice1").src = "images/d" + rand1 + ".png";
document.getElementById("mydice2").src = "images/d" + rand2 + ".png";
document.getElementById("hisdice1").src = "images/e" + rand3 + ".png";
document.getElementById("hisdice2").src = "images/e" + rand4 + ".png";
// Set Image alt
document.getElementById("mydice1").alt = side_alt[rand1];
document.getElementById("mydice2").alt = side_alt[rand2];
document.getElementById("hisdice1").alt = side_alt[rand3];
document.getElementById("hisdice2").alt = side_alt[rand4];
who_won(rand1,rand2,rand3,rand4);
}
function who_won(rand1,rand2,rand3,rand4){
let player_points = rand1 + rand2 + 2;
let enemy_points = rand3 + rand4 + 2;
let giffy = winner(player_points,enemy_points);
document.getElementById("message").src = "images/" + giffy;
document.getElementById("message").alt = giffy;
// set the value of the score input element to the variable score
document.getElementById("score").value = score;
}
function winner(player, enemy) {
if (player < enemy) {
// subtract a point
score = score-1;
return "oof-looser.gif";
}
if (enemy < player) {
// add a point
score = score + 1;
return "twerk-win.gif";
}
if (player == enemy) {
return "equal.gif";
}
}
If you have any questions about the code simulating the dice throws, please watch Make a JavaScript Dice Game (YouTube Video #1).
If you have any questions about the score keeping please watch JavaScript Game Keeping Score - Dice Game (YouTube Video #2)
Fetch API - Submit Form
We are finally ready to submit myform! We use the Fetch API to send a post request back to our PHP script (dice.php).