Javascript Rock, Paper, Scissors 2
Rock, paper, scissors using the Mediator Pattern.
by Richard Lovell
HTML
<div class="container">
<div class="header">
<h3 class="text-muted">Rock Paper Scissors 2</h3>
</div>
<div class="jumbotron">
<div class="row">
<div class="col-md-6">
<p>Player 1</p>
<p><input id="username1-tb" class="form-control" type="text" placeholder="Enter your username"></p>
<p><a id="create-btn" class="btn btn-lg btn-success" href="#">Create game</a></p>
<p>Choose Rock, Paper or Scissors</p>
<a id="rock-btn1" class="btn btn-lg btn-success" href="#">Rock</a>
<a id="paper-btn1" class="btn btn-lg btn-success" href="#">Paper</a>
<a id="scissors-btn1" class="btn btn-lg btn-success" href="#">Scissors</a></div>
<div class="col-md-6">
<p>Player 2</p>
<p><input id="username2-tb" class="form-control" type="text" placeholder="Enter your username"></p>
<p><a id="join-btn" class="btn btn-lg btn-success" href="#">Join game</a></p>
<p>Choose Rock, Paper or Scissors</p>
<a id="rock-btn2" class="btn btn-lg btn-success" href="#">Rock</a>
<a id="paper-btn2" class="btn btn-lg btn-success" href="#">Paper</a>
<a id="scissors-btn2" class="btn btn-lg btn-success" href="#">Scissors</a></div>
</div>
</div>
<div class="footer">
</div>
</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;
};
};
//behavioural pattern
//MEDIATOR PATTERN
//GameManager class encapsulates how players interact with a game
APP.GameManager = function GameManager() {
this.startGame = function (username) {
var player1 = new APP.Player(username);
//player1 starts game
this.game = new APP.Game(player1);
};
this.joinGame = function (username) {
var player2 = new APP.Player(username);
//player1 starts game
this.game.setPlayer2(player2);
};
this.checkComplete = function (username) {
if (this.game.player1.choice !== null && this.game.player2 != null && this.game.player2.choice !== null) {
this.game.calculateWinner();
this.showResult();
...