Tic-tac-toe: Difference between revisions
Content added Content deleted
(→{{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: | Line 5,258: | ||
def initialize(player_1_class, player_2_class) |
def initialize(player_1_class, player_2_class) |
||
@board = Array.new(10) # we ignore index 0 for convenience |
@board = Array.new(10) # we ignore index 0 for convenience |
||
⚫ | |||
@current_player_id = 0 |
@current_player_id = 0 |
||
Line 5,264: | Line 5,263: | ||
puts "#{current_player} goes first." |
puts "#{current_player} goes first." |
||
end |
end |
||
attr_reader :board |
attr_reader :board, :current_player_id |
||
def play |
def play |
||
Line 5,282: | Line 5,281: | ||
switch_players! |
switch_players! |
||
end |
end |
||
⚫ | |||
⚫ | |||
Set.new((1..9).select {|position| @board[position].nil?}) |
|||
end |
end |
||
Line 5,287: | Line 5,290: | ||
position = player.select_position! |
position = player.select_position! |
||
puts "#{player} selects #{player.marker} position #{position}" |
puts "#{player} selects #{player.marker} position #{position}" |
||
⚫ | |||
@board[position] = player.marker |
@board[position] = player.marker |
||
@free_positions.delete(position) |
|||
end |
end |
||
Line 5,299: | Line 5,300: | ||
def board_full? |
def board_full? |
||
free_positions.empty? |
|||
end |
end |
||
Line 5,311: | Line 5,312: | ||
def current_player |
def current_player |
||
@players[ |
@players[current_player_id] |
||
end |
end |
||
Line 5,319: | Line 5,320: | ||
def turn_num |
def turn_num |
||
10 - |
10 - free_positions.size |
||
end |
end |
||