Jump to content

Tic-tac-toe: Difference between revisions

→‎{{header|Ruby}}: make free_positions a method instead of an instance variable, to reduce state
(→‎{{header|Ruby}}: simplify creation of players and looking up of current player)
(→‎{{header|Ruby}}: make free_positions a method instead of an instance variable, to reduce state)
Line 5,258:
def initialize(player_1_class, player_2_class)
@board = Array.new(10) # we ignore index 0 for convenience
@free_positions = Set.new(1..9)
@current_player_id = 0
Line 5,264 ⟶ 5,263:
puts "#{current_player} goes first."
end
attr_reader :board, :free_positions, :current_player_id
def play
Line 5,282 ⟶ 5,281:
switch_players!
end
end
def @free_positions = Set.new(1..9)
Set.new((1..9).select {|position| @board[position].nil?})
end
Line 5,287 ⟶ 5,290:
position = player.select_position!
puts "#{player} selects #{player.marker} position #{position}"
@board[position] = player.marker
@free_positions.delete(position)
end
Line 5,299 ⟶ 5,300:
def board_full?
@free_positions.empty?
end
Line 5,311 ⟶ 5,312:
def current_player
@players[@current_player_id]
end
Line 5,319 ⟶ 5,320:
def turn_num
10 - @free_positions.size
end
21

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.