Tic-tac-toe: Difference between revisions

Content deleted Content added
Roryokane (talk | contribs)
→‎{{header|Racket}}: be more specific about the generality of game.rkt
Roryokane (talk | contribs)
→‎{{header|Ruby}}: simplify creation of players and looking up of current player
Line 5,260: Line 5,260:
@free_positions = Set.new(1..9)
@free_positions = Set.new(1..9)
@players = [player_1_class.new(self), player_2_class.new(self)]
@current_player_id = 0
@current_player_id = 0
@players = [player_1_class.new(self, "X"), player_2_class.new(self, "O")]
@players[@current_player_id].marker = "X"
puts "#{current_player} goes first."
@players[other_player_id].marker = "O"
puts "#{@players[@current_player_id]} goes first."
end
end
attr_reader :board, :free_positions, :current_player_id
attr_reader :board, :free_positions, :current_player_id
Line 5,270: Line 5,268:
def play
def play
loop do
loop do
place_player_marker(current_player)
player = @players[@current_player_id]
place_player_marker(player)
if player_has_won?(current_player)
puts "#{current_player} wins!"
if player_has_won?(player)
puts "#{player} wins!"
print_board
print_board
return
return
Line 5,312: Line 5,308:
def switch_players!
def switch_players!
@current_player_id = other_player_id
@current_player_id = other_player_id
end
def current_player
@players[@current_player_id]
end
end
Line 5,334: Line 5,334:
class Player
class Player
def initialize(game)
def initialize(game, marker)
@game = game
@game = game
@marker = nil
@marker = marker
end
end
attr_accessor :marker
attr_reader :marker
end
end