class SnakesAndLadders::Game

Attributes

board[R]
player[R]
players[R]
turn[R]
winner[R]

Public Class Methods

new(board:, players: [], turn: 0) click to toggle source
# File lib/snakes_and_ladders/game.rb, line 5
def initialize(board:, players: [], turn: 0)
  @board = board
  @players = players
  @turn = turn
end

Public Instance Methods

add_player(player) click to toggle source
# File lib/snakes_and_ladders/game.rb, line 11
def add_player(player)
  players.push(player)
end
over?() click to toggle source
# File lib/snakes_and_ladders/game.rb, line 29
def over?
  !!winner
end
play_turn() click to toggle source
# File lib/snakes_and_ladders/game.rb, line 15
def play_turn
  return if over?

  init_turn

  puts "#{player} rolls #{player.last_roll}!"

  if board.move(player, player_position, player_destination_after_last_roll)
    self.winner = player if won?
  else
    self.winner = player if will_win?
  end
end
simulate() click to toggle source
# File lib/snakes_and_ladders/game.rb, line 33
def simulate
  play_turn until over?
end

Private Instance Methods

board_size() click to toggle source
# File lib/snakes_and_ladders/game.rb, line 66
def board_size
  board.size
end
init_turn() click to toggle source
# File lib/snakes_and_ladders/game.rb, line 39
def init_turn
  @player = players.at(turn % players.size)
  @player.roll_die
  @turn += 1
end
player_destination_after_last_roll() click to toggle source
# File lib/snakes_and_ladders/game.rb, line 62
def player_destination_after_last_roll
  player.destination_after_last_roll
end
player_position() click to toggle source
# File lib/snakes_and_ladders/game.rb, line 58
def player_position
  player.position
end
will_win?() click to toggle source
# File lib/snakes_and_ladders/game.rb, line 49
def will_win?
  player_destination_after_last_roll >= board_size
end
winner=(player) click to toggle source
# File lib/snakes_and_ladders/game.rb, line 53
def winner=(player)
  @winner = player
  puts "Game over! #{winner} wins in #{winner.turns} turns. Congratulations!"
end
won?() click to toggle source
# File lib/snakes_and_ladders/game.rb, line 45
def won?
  player_position.equal?(board_size)
end