-1

I am creating a Monopoly game. I searched for a way to create a take_turn method (or a Class) so I can switch automatically between player1 and player2 (and in the future player3 etc.).

Looked for answers here and also found this full-on PDF on OOP for developing games but haven't found the answer to this specific question.

Here's the code I' TDDed and built with several other objects. All works well at the moment for just player1, I would just like to automatically repeat those steps for player1 then player2 automatically without having to do it manually (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
Community
  • 1
  • 1

1 Answers1

1

Well, I'm not sure what your real problem is, but maybe this could help :

Put your players in an array :

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

Get an indice with the current player

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

Advance a turn with a simple :

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

The replace your calls to player1 by current_player, and you should be pretty good.

Martin
  • 7,634
  • 1
  • 20
  • 23
  • I would go a step further and not even have variables for `@player1` and `@player2`. Just use `@players` for everything. I would also not hardcode the 2 in your `next_player` method but instead use the length of the array. – miorel Apr 01 '13 at 09:46
  • actually, isn't current_player_indice = 0 for this to work in initializer? – Ruben Kostucki Apr 01 '13 at 13:05