2013-10-23 80 views
0

我試圖創建一個剪刀石頭布的程序,到目前爲止,該代碼的工作,但參數不扔,我怎麼能解決這個問題?在條件語句引發異常

class RockPaperScissors 

    # Exceptions this class can raise: 
    class NoSuchStrategyError < StandardError ; end 

    def self.winner(player1, player2) 
    p1c = player1.last.downcase 
    p2c = player2.last.downcase 
    p1wins = false 

    case p1c 
     when "p" 
     if (p2c == "p" or p2c == "r") 
      p1wins = true 
     end 
     when "s" 
     if (p2c == "p" or p2c == "s") 
      p1wins = true 
     end 
     when "r" 
     if (p2c == "r" or p2c == "s") 
      p1wins = true 
     end 
     else 
     raise NoSuchStrategyError, "Strategy must be one of R,P,S" 
    end 
    end 

爲什麼錯誤不會丟? 編輯*

這是用來使用RSpec的測試代碼,你可以看到它與一個名稱,然後他們在capse選擇

before(:each) do 
@rock = ['Armando','R'] ; @paper = ['Dave','P'] ; @scissors = ['Sam','S'] 
end 
describe 'game' do 
it 'rock breaks scissors' do 
    RockPaperScissors.winner(@rock, @scissors).should == @rock 
end 
it 'scissors cut paper' do 
    RockPaperScissors.winner(@paper, @scissors).should == @scissors 
end 
it 'paper covers rock' do 
    RockPaperScissors.winner(@rock, @paper).should == @paper 
end 
it 'first player wins if both use same strategy' do 
    RockPaperScissors.winner(@scissors, ['Dave','S']).should == @scissors 
end 
end 
it "should raise NoSuchStrategyError if strategy isn't R, P, or S" do 
lambda { RockPaperScissors.winner(@rock, ['Dave', 'w']) }. 
    should raise_error(RockPaperScissors::NoSuchStrategyError, 
    "Strategy must be one of R,P,S") 
end 
+0

您需要包含顯示如何測試它的代碼。什麼是'player1'有一個'last'方法? 'p1c'的價值是什麼? – Phrogz

+1

順便說一句,在任何遊戲中,石頭,那我打過剪刀也當雙方球員表現出了同樣的策略一位玩家獲勝。 – Phrogz

+0

@Phrogz我知道對不對其從班裏質量要求的一個,我認爲它不公平的地獄但哦。使用RSPEC代碼測試包括現在 – MikaAK

回答

1

編輯一個數組:基於您的外新提供的測試代碼,問題是您只測試代碼中第一個玩家的策略。然而在測試代碼中,第一個玩家(@rock)有一個有效的策略;它是第二個擁有無效戰略的球員。查看我的代碼來測試兩種方法。


它的工作對我來說,當我添加缺少end到您的代碼,這樣的:

Player = Struct.new(:last) 
RockPaperScissors.winner(
    Player.new("cats"), 
    Player.new("dogs") 
) 
#=> /Users/phrogz/Desktop/tmp.rb:24:in `winner': Strategy must be one of R,P,S (RockPaperScissors::NoSuchStrategyError) 

注意,我會重新寫你的方法是這樣的:

class RockPaperScissors 
    class NoSuchStrategyError < StandardError ; end 
    LEGAL_MOVES = %w[r p s] 
    def self.winner(player1, player2) 
    p1c = player1.last.downcase 
    p2c = player2.last.downcase 
    unless LEGAL_MOVES.include?(p1c) && LEGAL_MOVES.include?(p2c) 
     raise NoSuchStrategyError, "Strategy must be one of R,P,S" 
    end 
    if p1c!=p2c then 
     case p1c 
     when "r" then p2c=="s" ? player1 : player2 
     when "p" then p2c=="r" ? player1 : player2 
     when "s" then p2c=="p" ? player1 : player2 
     end 
    end 
    end 
end 

這引發錯誤的無效之舉,返回nil如果兩個球員配合,否則返回的球員之一。你可以通過重寫內部部分來更簡潔,但可以說不那麼明確:

if p1c!=p2c then 
    case p1c 
    when "r" then p2c=="s" 
    when "p" then p2c=="r" 
    when "s" then p2c=="p" 
    end ? player1 : player2 
end 
+0

我已經編輯了我的答案,詳細說明了爲什麼你的測試失敗。 – Phrogz