Skip to content

Instantly share code, notes, and snippets.

@arbianchi
Created June 17, 2017 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arbianchi/881f0c671d7638b13f60482a37b322ce to your computer and use it in GitHub Desktop.
Save arbianchi/881f0c671d7638b13f60482a37b322ce to your computer and use it in GitHub Desktop.
jQuery game feedback
// ADINA: In order to avoid repeating this code, you could use a function like this:
// function crystalNumber() {
// return Math.floor((Math.random() * 12) + 1);
// }
// function targetScore() {
// return Math.floor((Math.random() * 120) + 19);
// }
// var crystals = {
// red: 0,
// blue: 0,
// green: 0,
// yellow: 0
// }
// then you could use a forEach loop to set the values of the crystals:
// for(var crystal in crystals) {
// console.log(crystal);
// crystals[crystal] = crystalNumber();
// }
// But what you did also works :)
// set variables
var targetScore = Math.floor((Math.random() * 120) + 19);
var red = Math.floor((Math.random() * 12) + 1);
var blue = Math.floor((Math.random() * 12) + 1);
var green = Math.floor((Math.random() * 12) + 1);
var yellow = Math.floor((Math.random() * 12) + 1);
var yourScore = 0;
var winCount = 0;
var lossCount = 0;
// insert target
$("#targetScore").text(targetScore)
// set up winner and loser functions
function winner(){
alert("You won!");
winCount++;
$("#wins").text("Wins: " + winCount);
reset();
}
function loser(){
alert ("You lose!");
lossCount++;
$("#losses").text("Losses: " + lossCount);
reset()
}
// crystal click functions
$('#blue').on ('click', function(){
yourScore = yourScore + blue;
console.log("New userTotal= " + yourScore);
$('#yourscore').text(yourScore);
if (yourScore == targetScore){
winner();
}
else if ( yourScore > targetScore){
loser();
}
})
$('#red').on ('click', function(){
yourScore = yourScore + red;
console.log("New userTotal= " + yourScore);
$('#yourscore').text(yourScore);
if (yourScore == targetScore){
winner();
}
else if ( yourScore > targetScore){
loser();
}
})
$('#yellow').on ('click', function(){
yourScore = yourScore + yellow;
console.log("New userTotal= " + yourScore);
$('#yourscore').text(yourScore);
if (yourScore == targetScore){
winner();
}
else if ( yourScore > targetScore){
loser();
}
})
$('#green').on ('click', function(){
yourScore = yourScore + green;
console.log("New userTotal= " + yourScore);
$('#yourscore').text(yourScore);
if (yourScore == targetScore){
winner();
}
else if ( yourScore > targetScore){
loser();
}
})
//reset game
function reset(){
targetScore = Math.floor((Math.random() * 120) + 19);
$("#targetScore").text(targetScore);
red = Math.floor((Math.random() * 12) + 1);
blue = Math.floor((Math.random() * 12) + 1);
green = Math.floor((Math.random() * 12) + 1);
yellow = Math.floor((Math.random() * 12) + 1);
yourScore = 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment