2011-09-07 135 views
0

現在我正在嘗試創建一個基本的tic tac toe遊戲。在我開始編寫人工智能之前,我想用兩名人類玩家設置遊戲,並在稍後添加到計算機中。我不完全確定要設立多個玩家的最佳方式。 (我的代碼是用Ruby)在遊戲中設置兩個玩家

num_of_users = 2 

player1 = User.new 
player2 = User.new 
cpu = AI.new 

if turn 
    # player1 stuff 
    turn = !turn 
else 
    # player2 stuff 
    turn = !turn 
end 

這工作得很好了兩名球員,但我不知道如何調整這個時,我希望能夠對AI打。有人能幫助我解決這個問題的最佳方法嗎?

回答

3

在變量名稱中使用數字作爲後綴通常表示您需要數組。

players = [] 
players[0] = User.new 
players[1] = User.new # or AI.new 

current_player = 0 
game_over = false 

while !game_over do 
    # the User#make_move and AI#make_move method are where you 
    # differentiate between the two - checking for game rules 
    # etc. should be the same for either. 
    players[current_player].make_move 

    if check_for_game_over 
    game_over = true 
    else 
    # general method to cycle the current turn among 
    # n players, and wrap around to 0 when the round 
    # ends (here n=2, of course) 
    current_player = (current_player + 1) % 2 
    end 
end 
+7

你可以使用['E = players.cycle'](http://www.ruby-doc.org/core/classes/Enumerable.html#M001522),'e.next'和' e.peek'而不是索引技巧。 –

+0

好點 - 這是一個很好的,紅寶石的方式來做到這一點! –

+0

我沒有想過使用數組!謝謝你的幫助。 – Max