开发者

Setting Up Two Players in a Game

Right now I'm trying to create a basic tic tac toe game. Before I start coding the AI, I wan开发者_如何学运维ted to set up the game with two human players, and add in the computer later. I'm not exactly sure the best way to set up asking for multiple players though. (My code's in 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

This works fine for two players, but I don't know how to adjust this for when I want to be able to play against the AI. Can someone help me with the best way to to approach this problem?


Using numbers as suffixes in variable names is usually a sign that you want an array instead.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜