Skip to content

Instantly share code, notes, and snippets.

@manewitz
Created October 14, 2012 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manewitz/3886812 to your computer and use it in GitHub Desktop.
Save manewitz/3886812 to your computer and use it in GitHub Desktop.
Rock Paper Scissors in Ruby
class WrongNumberOfPlayersError < StandardError ; end
class NoSuchStrategyError < StandardError ; end
VALID_MOVES = %w{R P S}
def rps_game_winner(game)
raise WrongNumberOfPlayersError unless game.count == 2
game.each do |move|
unless VALID_MOVES.include?(move[1])
raise NoSuchStrategyError
end
end
p1 = game[0][0]
v1 = game[0][1]
p2 = game[1][0]
v2 = game[1][1]
return [p1, v1] if v1 == v2
if v1 == "R"
return [p1, v1] if v2 == "S"
return [p2, v2] if v2 == "P"
elsif v1 == "P"
return [p1, v1] if v2 == "R"
return [p2, v2] if v2 == "S"
elsif v1 == "S"
return [p1, v1] if v2 == "P"
return [p2, v2] if v2 == "R"
end
end
def rps_tournament_winner(node)
if node.flatten.length == 4
rps_game_winner(node)
elsif node.first.is_a?(Array)
node = [ rps_tournament_winner(node[0]), rps_tournament_winner(node[1]) ]
rps_tournament_winner(node)
end
end
# 2 player game
two = ["Armando", "P"], ["Dave", "S"]
# 4 player game
four = [
[ ["Armando", "P"], ["Dave", "S"] ],
[ ["Richard", "R"], ["Michael", "S"] ],
]
# 8 player game
eight =
[
[
[ ["Armando", "P"], ["Dave", "S"] ],
[ ["Richard", "R"], ["Michael", "S"] ],
],
[
[ ["Allen", "S"], ["Omer", "P"] ],
[ ["David E.", "R"], ["Richard X.", "P"] ]
]
]
sixteen =
[
[[[["Armando", "P"], ["Dave", "S"]], [["Richard", "R"], ["Michael", "S"]]], [[["Allen", "S"], ["Omer", "P"]], [["David E.", "R"], ["Richard X.", "P"]]]],
[[[["Mike", "S"], ["DJ", "P"]], [["Isaiah", "S"], ["Steve", "P"]]], [[["Alan", "P"], ["Mahmoud", "R"]], [["Bill E.", "S"], ["Loraine", "R"]]]]
]
p rps_tournament_winner(two)
p rps_tournament_winner(four)
p rps_tournament_winner(eight)
p rps_tournament_winner(sixteen)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment