Rock-paper-scissors: Difference between revisions

Updated D entry
m (Added the extra weapons extra credit. Discussed in the talk page and people seem to be OK with implementing it.)
(Updated D entry)
Line 806:
=={{header|D}}==
{{trans|Python}}
<lang d>import std.stdio, std.random, std.string, std.array;,
std.typecons, std.traits, std.conv, std.algorithm;
 
enum string[]Choice order{ = ["rock", "paper", "scissors"]; }
immutable order = [EnumMembers!Choice];
int[string] choiceFrequency; // mutable
 
intuint[stringorder.length] choiceFrequency; // mutable
immutable(string[string]) whatBeats;
 
nothrow pure static this() {
Choice whatBeats(in Choice ch) pure /*nothrow*/ {
whatBeats = ["paper": "scissors",
return order[(order.countUntil(ch) + 1) % $];
"scissors": "rock",
"rock": "paper"];
}
 
stringNullable!Choice checkWinner(in stringChoice a, in stringChoice b) pure nothrow {
pure /*nothrow*/ {
if (b == whatBeats[a])
alias TResult = typeof(return b);
 
else if (a == whatBeats[b])
if (b == return whatBeats(a;))
return ""TResult(b);
else if (ba == whatBeats[a](b))
return TResult(a);
return TResult.init;
}
 
stringChoice getRandomChoice() /*nothrow*/ {
//if (choiceFrequency[].emptyreduce!q{a + b} == 0)
return uniform!Choice;
if (choiceFrequency.length == 0)
return order[uniform(0, $)choiceFrequency.dice].whatBeats;
const choices = choiceFrequency.keys;
const probabilities = choiceFrequency.values;
return whatBeats[choices[dice(probabilities)]];
}
 
void main() {
writeln("Rock-paperPaper-scissorsScissors gameGame");
 
while (true) {
write("Your choice (empty to end game): ");
immutable string humanChoicehumanChoiceStr = readln().strip().toLower();
if (humanChoicehumanChoiceStr.empty)
break;
 
if (humanChoice !in whatBeats) {
writeln("Wrong input: ",Choice humanChoice);
try {
humanChoice = humanChoiceStr.to!Choice;
} catch (ConvException e) {
writeln("Wrong input: ", humanChoiceStr);
continue;
}
 
immutable compChoice = getRandomChoice();
write("Computer picked ", compChoice, ", ");
 
Line 855 ⟶ 860:
 
immutable winner = checkWinner(humanChoice, compChoice);
if (winner.emptyisNull)
writeln("nobodyNobody wins!");
else
writeln(winner.get, " wins!");
}
}</lang>
{{out|Output example:}}
<pre>Rock-paperPaper-scissorsScissors gameGame
Your choice (empty to end game): rock
Computer picked scissors, rock wins!
Your choice (empty to end game): scissors
Computer picked paper, scissors wins!
Your choice (empty to end game):</pre>
 
=={{header|Erlang}}==