2011-09-07 205 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