In a few weeks I need to give a workshop about JavaScript to colleagues. They do not have much experience with JavaScript so I will explain the basics of JavaScript. At the end of the day I want them to make a small game with the aspects learned during the day.
I was thinking of Rock Paper Scissors. Below you can find the final code for this game:
var RockPaperScissors = (function () {
var t = 'Tie',
c = 'Computer wins',
p = 'Player wins',
winningMap = [
[t, c, p],
[p, t, c],
[c, p, t]
],
choices = ["Rock", "Paper", "Scissors"];
var getComputerChoice = function () {
return Math.floor(Math.random() * 3);
};
var getWinner = function (playerChoice, computerChoice) {
return winningMap[playerChoice][computerChoice];
};
function RockPaperScissors(playerChoice) {
this.playerChoice = playerChoice;
this.computerChoice = getComputerChoice();
this.winner = getWinner(this.playerChoice, this.computerChoice);
}
RockPaperScissors.prototype.toString = function () {
return this.winner + " [Computer: " + choices[this.computerChoice] + ", Player: " + choices[this.playerChoice] + "]";
};
return RockPaperScissors;
})();
This code is executed everytime a select input box changes (see this as the user input):
$('#choice').on('change', function () {
var $input = $(this);
if ($input.val() === '-1') return;
var rockPaperScissors = new RockPaperScissors($input.val());
$('#message').html(rockPaperScissors.toString());
});
I've also set up a Fiddle.
Do you think this code is clear for beginners? Is this too advanced? I'm not sure if I should introduce them to prototyping or not.
var winningMap = {"Rock": "Scissors", Paper: "Rock", Scissors: "Paper"};
. It defines which choice can be beaten by a specific selection. If both inputs are the same, it's obvious a tie. \$\endgroup\$var RockPaperScissors = new function(){ ... };
\$\endgroup\$$input.val()
vsinput.value
? If I knew nothing of javascript, I would pick option 2... \$\endgroup\$