Created with <3 with dartpad.dev.
Last active
May 25, 2023 15:46
-
-
Save nikclayton/8ed3329ea21dbfcc617378276dd1417f to your computer and use it in GitHub Desktop.
powerful-ritual-9413
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:math'; | |
enum GameResult { win, lose, draw } | |
enum Move { | |
rock, | |
paper, | |
scissors; | |
/// Create a [Move] from the string [s]. Returns [null] if [s] | |
/// does not refer to a valid move. | |
static Move? from(String s) { | |
return switch (s.toLowerCase()) { | |
"r" => Move.rock, | |
"p" => Move.paper, | |
"s" => Move.scissors, | |
_ => null | |
}; | |
} | |
/// Play this move against [other], returns the result from | |
/// this move's perspective. | |
GameResult play(Move other) { | |
if (this == other) return GameResult.draw; | |
return switch ((this, other)) { | |
(paper, rock) => GameResult.win, | |
(scissors, paper) => GameResult.win, | |
(rock, paper) => GameResult.win, | |
_ => GameResult.lose | |
}; | |
} | |
String emoji() { | |
return switch (this) { | |
rock => "🪨", | |
paper => "📃", | |
scissors => "✂️" | |
}; | |
} | |
} | |
void main() { | |
final rng = Random(); | |
print("R, P, S?"); | |
// Swap the comments on the next two lines if you are running | |
// this in an environment with stdin support. | |
// final input = stdin.readLineSync(); | |
final input = "r"; | |
final move = Move.from(input); | |
if (move == null) { | |
print("Invalid move"); | |
return; | |
} | |
final computerMove = Move.values[rng.nextInt(3)]; | |
print("Your move: ${move.emoji()}"); | |
print("Computer move: ${computerMove.emoji()}"); | |
final result = move.play(computerMove); | |
switch (result) { | |
case GameResult.win: | |
print("You win, ${move.emoji()} beats ${computerMove.emoji()}"); | |
case GameResult.lose: | |
print("You lose, ${computerMove.emoji()} beats ${move.emoji()}"); | |
case GameResult.draw: | |
print("It's a draw"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment