A little library to make the rock-paper-scissor logic simpler. Can be used for any number of odd elements (except 1, of course.)
| Author | Cyrus Firheir |
| Website | https://github.com/cyrusfirheir/cycy-wrote-custom-macros/tree/master/rock-paper-scissors |
| Story format | SugarCube 2 |
| Last checked | Wed Oct 07 2020 |
| License | Unlicense |
| Download | rps.zip |
A little library to make the rock-paper-scissor logic simpler. Can be used for any number of odd elements (except 1, of course.)
If using the Twine desktop/web app, copy contents of rock-paper-scissors.js to Story JavaScript.
If using a compiler like Tweego, drop rock-paper-scissors.js to your source folder.
The following example uses the 'extended' version of RPS, rock-paper-scissors-lizard-spock.
<<set _rps to new RPS([
"rock", "spock", "paper", "lizard", "scissors"
])>>
<<set _player to _rps.elements.random()>>
<<set _opponent to _rps.elements.random()>>
You played <<= _player>>.
They played <<= _opponent>>.
<<set _result to _rps.compare(_player, _opponent)>>
<<if _result gt 0>>
You win!
<<elseif _result lt 0>>
You lose...
<<else>>
It's a draw.
<</if>>
The RPS object does the math to calculate the outcome of a match. Takes in the array of elements as an argument (see how to arrange the elements.)
NOTE: The elements do not have to be a string. Internally, a Map object is used, so the elements can be of any type.
Example:
var rpsTest = new RPS([
"rock", "paper", "scissors"
]);
The way any RPS system works is as follows:
To adhere to those principles, the order of the elements has to follow one simple rule:
No element should have its winning and losing brackets interleave.
That statement can be broken down further to these rules:
Of course, an array doesn't go on forever on both sides, nor does it make a closed loop, but for this implementation, arrays are cyclic and the positions can freely change given they stay in the same cyclic order. Which means, ABC, BCA, and CAB are all the same.
Classic rock-paper-scissors:
["rock", "paper", "scissors"].Rock-paper-scissors-lizard-spock:
["rock", "spock", "paper", "lizard", "scissors"].Demo Twee code:
:: Start <<set _rps to new RPS([ "rock", "paper", "scissors" ])>>\ <<set _player to _rps.elements.random()>>\ <<set _opponent to _rps.elements.random()>>\ You played <<= _player>>. They played <<= _opponent>>. <<set _result to _rps.compare(_player, _opponent)>>\ <<if _result gt 0>> You win! <<elseif _result lt 0>> You lose... <<else>> It's a draw. <</if>>\