rock-paper-scissors-lizard-spock
by Dmytro Tsiniavskyi
HTML
<p class="title">
Rock Paper Scissors Lizard Spock
</p>
<p>
Chose your destiny
</p>
<div class="item" id="rock" data-val="0">
<img src="https://dl.dropboxusercontent.com/u/765818/rock_paper_scissors_lizard_spock/rock.png" alt="rock"/>
</div>
<div class="item" id="paper" data-val="1">
<img src="https://dl.dropboxusercontent.com/u/765818/rock_paper_scissors_lizard_spock/paper.png" alt="paper"/>
</div>
<div class="item" id="scissors" data-val="2">
<img src="https://dl.dropboxusercontent.com/u/765818/rock_paper_scissors_lizard_spock/scissors.png" alt="scissors"/>
</div>
<div class="item" id="lizard" data-val="3">
<img src="https://dl.dropboxusercontent.com/u/765818/rock_paper_scissors_lizard_spock/lizard.png" alt="lizard"/>
</div>
<div class="item" id="spock" data-val="4">
<img src="https://dl.dropboxusercontent.com/u/765818/rock_paper_scissors_lizard_spock/spock.png" alt="spock"/>
</div>
<p>
<input type="button" value="Rules" id="rules"/>
</p>
<div id="rules-dialog" style="display: none;">
<img src="https://dl.dropboxusercontent.com/u/765818/rock_paper_scissors_lizard_spock/rules.jpg" alt="rules">
</div>
CSS
p {
margin-bottom: 10px;
}
p.title {
font-weight: bold;
}
input[type=button]{
cursor: pointer;
}
.item{
width: 131px;
height: 131px;
display: inline-block;
margin: 5px;
cursor: pointer;
}
JavaScript
$.fn.play = function() {
var you = $(this).data('val');
var oponent = getRandomInt(0, 4);
// Instead of using a lot if/else stuff
// we can use some kind of versus result matrix
// where rows are your selection (first index)
// and columns are your oponent's selection (second index)
// 0 : you win
// 1 : you lose
// 2 : tie
var versusMatrix = [
// 0 1 2 3 4
// r p s l sp
[ 2, 1, 0, 0, 1 ], //0. rock
[ 0, 2, 1, 1, 0 ], //1. paper
[ 1, 0, 2, 0, 1 ], //2. scissors
[ 1, 0, 1, 2, 0 ], //3. lizard
[ 0, 1, 0, 1, 2 ] //4. spock
];
var result = versusMatrix[you][oponent];
return getResultMessage(you, oponent, result);
}
function getRandomInt(bottom, top) {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
function getResultMessage(you, oponent, result) {
var items = ["rock", "paper", "scissors", "lizard", "spock"];
var results = ["You won!", "You lost!", "It's a tie!"]
return 'You: ' + items[you] + '\nOponent: ' + items[oponent] + '\n\n' + results[result];
}
$(document).ready(function(){
initGame();
});
function initGame() {
var items = $('.item');
items.click(function(){
alert($(this).play());
});
// Init rules dialog and behavior
$('#rules-dialog').dialog({
title: "Rules",
autoOpen: false,
width: 420,
buttons: [
{
text: "OK",
click: function() {
$( this ).dialog( "close" );
}
}
]
});
$('#rules').click(function(){
$('#rules-dialog').dialog('open');
});
}