# By alan snape # All rights reserved. class RockPaperScissors # Exceptions this class can raise: class NoSuchStrategyError < StandardError; end # check strategy is legal or not def self.checkStrategy(stg) if 'P' != stg && 'R' != stg && 'S' != stg then raise NoSuchStrategyError, 'Strategy must be one of R,P,S' end end # a single round game def self.winner(player1, player2) stg1, stg2 = player1[1], player2[1] self.checkStrategy(stg1) self.checkStrategy(stg2) if stg1 == stg2 then return player1 elsif 'P' == stg1 && 'S' == stg2 then return player2 elsif 'S' == stg1 && 'P' == stg2 then return player1 else return stg1 < stg2 ? player1 : player2 end end # if there is a sub game then returns the winner of it # else return this player himself def self.tournament_match(game) if game[0].kind_of?(Array) then return self.tournament_winner(game) else return game end end # tournament game rounds def self.tournament_winner(tournament) player1 = self.tournament_match(tournament[0]) player2 = self.tournament_match(tournament[1]) return self.winner(player1, player2) end end