Rock paper scissors
Rock paper scissors written without conditions
by kontrach
HTML
<h1>Linear algorithm</h1>
<p>action A => action B => action C</p>
<h1>Algotithm with conditions</h1>
<pre>
action B
action A => condition /
\
action C
</pre>
JavaScript
// why do we need this?
// For example we need to set language according to url
// url example: www.domain.com/en
var lang = window.location.pathname; // 'en'
var messages = {
en: 'Hello!',
ru: 'Здоров!'
};
// messages[lang] = 'hello!' or 'Здоров!' according to language.
// this settings are really easy to extend later.
// 0 - tie, 1 - loose , 2 - win
var pattern = [
[0, 1, 2], // rock
[2, 0, 1], // paper
[1, 2, 0] // scissors
];
var weapons = ['rock', 'paper', 'scissors'];
var userChoice = getUserChoice(weapons);
var compChoice = getCompChoice(weapons);
var result = getResult(userChoice, compChoice);
var resultMsg = getResultMessage(result);
alert(resultMsg);
function getUserChoice(weapons){
var userChoice = prompt('Please, type one of: rock paper or scissors');
return weapons.indexOf( userChoice );
}
function getCompChoice(weapons){
var compIndex = Math.round( Math.random() * 2 );
alert('Comp chose ' + weapons[compIndex]);
return compIndex;
}
function getResult(userChoice, compChoice){
return pattern[userChoice][compChoice];
}
function getResultMessage(result){
return ['tie', 'You loose', 'You win!!!'][result];
}