2013-04-01 46 views
-1

我正在創建一個大富翁遊戲。我搜索了一種方法來創建一個take_turn方法(或一個Class),這樣我就可以在player1和player2之間自動切換(以及將來的player3等)。如何從玩家1轉到玩家2並保持代碼DRY

尋找答案here,也發現在OOP開發遊戲this full-on PDF但還沒有找到這個具體問題的答案。

下面是代碼我'TDDed並與其他幾個對象構建。目前所有效果都很好,我只是想自動爲player1和player2自動重複這些步驟,而不必手動(DRY)。

class Engine 

    attr_reader :dice, :player1, :player2, :move, :board 

    def initialize 
    @player1 = Player.new 
    @board = Board.new 
    @player2 = Player.new 
    @dice = Dice.new 
    @move = Move.new 
    end 

    def run 
    3.times do 
     roll_and_move 
     print_current_balance 
     player_action 
    end 
    end 

    def roll_and_move 
    dice.roll 
    move.move(player1, board, dice.value) 
    end 

    def print_current_balance 
    player1.balance 
    end 

    def player_action 
    player1.buy(board.tile(player1.position)) 
    end 
end 

回答

1

好了,我不知道你真正的問題是什麼,但也許這可以幫助:

把你的球員在陣:

@players = [Player.new,Player.new] 

獲取一個與指數之當前玩家

@current_player_indice = 1 
def current_player 
    return @players[@current_player_indice] 
end 

預先用簡單的一轉:

def next_player 
    @current_player_indice = (@current_player_indice+1)%@players.size 
end 

用current_player替換你的調用給player1,你應該不錯。

+0

我會更進一步,甚至沒有'@ player1'和'@ player2'的變量。只需使用'@播放器'即可。我也不會在你的'next_player'方法中硬編碼2,而是使用數組的長度。 – miorel

+0

你是對的,我相應地更新了我的答案,謝謝! – Martin

+0

酷!這真棒傢伙非常感謝:) –