Created
March 10, 2016 10:20
-
-
Save sdorunga/a05084e86f03d4745e5f to your computer and use it in GitHub Desktop.
Rock paper scissors
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
Hand = Struct.new(:name, :trumps) do | |
def beats?(other_hand); trumps.include?(other_hand.name); end | |
def draw?(other_hand); name == other_hand.name; end | |
end | |
class Game | |
def self.rock_paper_scissors | |
new([Hand.new(:rock, [:scissors]), Hand.new(:scissors, [:paper]), Hand.new(:paper, [:rock])]) | |
end | |
def self.rock_paper_scissors_lizards_spock | |
new([Hand.new(:rock, [:scissors, :lizard]), | |
Hand.new(:scissors, [:paper, :lizard]), | |
Hand.new(:paper, [:rock, :spock]), | |
Hand.new(:lizard, [:spock, :paper]), | |
Hand.new(:spock, [:scissors, :rock])]) | |
end | |
def initialize(hands) | |
@hands = hands | |
end | |
def winner(hand_name) | |
player_hand, ai_hand = @hands.find { |hand| hand.name == hand_name }, @hands.sample | |
return "It's a draw" if player_hand.draw?(ai_hand) | |
winner = player_hand.beats?(ai_hand) ? "player" : "ai" | |
"Player #{player_hand.name} vs. Ai #{ai_hand.name}\nWinner is: #{winner}" | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment