Javascript Rock, Paper, Scissors
by Richard Lovell
HTML
<div id="result"></div>
JavaScript
//app class/namespace
var APP = APP || {};
//game class
APP.Game = function Game(player1) {
this.ROCK = "rock";
this.PAPER = "paper";
this.SCISSORS = "scissors";
this.player1 = player1;
this.setPlayer2 = function (player2) {
this.player2 = player2;
};
this.setPlayer1 = function (player2) {
this.player2 = player2;
};
this.calculateWinner = function () {
if (this.player1.choice !== this.player2.choice) {
this.winner = this.player1;
if (this.player1.choice === this.ROCK) {
if (this.player2.choice === this.PAPER) {
this.winner = this.player2;
}
} else if (this.player1.choice === this.PAPER) {
if (this.player2.choice === this.SCISSORS) {
this.winner = this.player2;
}
} else if (this.player1.choice === this.SCISSORS) {
if (this.player2.choice === this.ROCK) {
this.winner = this.player2;
}
}
}
};
};
//player class
APP.Player = function Player(username) {
this.username = username;
this.setChoice = function (choice) {
this.choice = choice;
};
};
var s = "";
//players
var player1 = new APP.Player("bob123");
var player2 = new APP.Player("mary123");
s+="Player1 is: " + player1.username + "<br>";
//player1 starts game
var game = new APP.Game(player1);
//player2 joins game
game.setPlayer2(player2);
s+="Player2 is: " + game.player2.username + "<br>";
//player1 chooses rock
player1.setChoice(game.ROCK);
s+="Player1 chooses: " + game.player1.choice + "<br>";
//player1 chooses paper
player2.setChoice(game.PAPER);
s+="Player2 chooses: " + game.player2.choice + "<br>";
//calculate winner
game.calculateWinner();
s+="Winner is: " + game.winner.username + "<br>";
var resultDiv = document.getElementById("result");
resultDiv.innerHTML = s;