Jump to content

Rock-paper-scissors: Difference between revisions

Updated D code
(D version)
(Updated D code)
Line 432:
=={{header|D}}==
{{trans|Python}}
<lang d>import std.stdio, std.algorithmrandom, std.randomstring, std.stringarray;
 
enum string[] order = ["rock", "paper", "scissors"];
int[string] choiceFrequency; // mutable
 
immutable(string[string]) whatBeats;
nothrow pure static this() {
whatBeats = ["paper": "scissors",
"scissors": "rock",
Line 444:
}
 
string checkWinner(in string a, in string b) pure nothrow {
if (b == whatBeats[a])
return b;
Line 464:
while (true) {
write("Your choice: ");
constimmutable string humanChoice = readln().strip().toLower();
if (humanChoice == "")
break;
if (humanChoice !canFind(order,in humanChoice)whatBeats) {
writeln("Wrong input: ", humanChoice);
continue;
}
 
constimmutable compChoice = getRandomChoice();
write("Computer picked ", compChoice, ", ");
 
// Don't register the player choice until after
// the computer has made its choice.
choiceFrequency[humanChoice]++;
 
stringimmutable winner = checkWinner(humanChoice, compChoice);
if (winner == "".empty)
winner = writeln("nobody wins!");
writeln(winner, " wins!");else
writeln(winner, " wins!");
}
}</lang>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.