fork download
  1. require 'test/unit'
  2.  
  3. class WrongNumberOfPlayersError < StandardError ; end
  4. class NoSuchStrategyError < StandardError ; end
  5.  
  6. STRATS = ['R','P','S']
  7. PLAYER2_WINS = [['R','P'], ['P','S'],['S','R']]
  8.  
  9. def rps_game_winner(game)
  10. raise WrongNumberOfPlayersError unless game.length == 2
  11.  
  12. # strategy error checking
  13. raise NoSuchStrategyError unless game[0].length == 2 && game[1].length == 2
  14. strat1 = game[0][1].upcase
  15. strat2 = game[1][1].upcase
  16. raise NoSuchStrategyError unless STRATS.include?(strat1) && STRATS.include?(strat2)
  17.  
  18. matchup = [strat1, strat2]
  19. return PLAYER2_WINS.include?(matchup) ? game[1] : game[0] # player1 wins if 2 doesn't
  20. end
  21.  
  22.  
  23. class RpsWinner < Test::Unit::TestCase
  24.  
  25. def test_examples
  26. expected = ['John', 'P']
  27. actual = rps_game_winner([['John', 'P'], ['Rick', 'R']])
  28. assert_equal(expected, actual)
  29.  
  30. expected = ['John', 'P']
  31. actual = rps_game_winner([['John', 'P'], ['Rick', 'R']])
  32. assert_equal(expected, actual)
  33. end
  34.  
  35. def test_num_of_players_errors
  36. assert_raise WrongNumberOfPlayersError do
  37. rps_game_winner([['John', 'P'], ['Rick', 'R'], ['Rick', 'R']])
  38. end
  39. assert_raise WrongNumberOfPlayersError do
  40. rps_game_winner([['John', 'P']])
  41. end
  42. assert_raise WrongNumberOfPlayersError do
  43. rps_game_winner("Hello")
  44. end
  45. assert_raise WrongNumberOfPlayersError do
  46. rps_game_winner([])
  47. end
  48. assert_raise WrongNumberOfPlayersError do
  49. rps_game_winner([[]])
  50. end
  51. end
  52.  
  53. def test_num_of_players_errors
  54. assert_raise NoSuchStrategyError do
  55. rps_game_winner([['John', 'Q'], ['Rick', 'R']])
  56. end
  57. assert_raise NoSuchStrategyError do
  58. rps_game_winner([['John', 'R'], ['Rick', 'X']])
  59. end
  60. assert_nothing_raised NoSuchStrategyError do
  61. rps_game_winner([['John', 'p'], ['Rick', 'r']])
  62. end
  63. end
  64. end
  65.  
Success #stdin #stdout 0.03s 5712KB
stdin
Standard input is empty
stdout
Loaded suite prog
Started
..
Finished in 0.000726 seconds.

2 tests, 5 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 27843