diff --git a/board.rb b/board.rb index 048efe3..4c2c2a7 100644 --- a/board.rb +++ b/board.rb @@ -64,5 +64,16 @@ class Board get_free.empty? end + def is_over? + if any_winner? then + system "clear" + print self.to_s + print "\nSomeone won!\n" + elsif is_full? then + system "clear" + print self.to_s + print "\nGame is done!\n" + end + end end diff --git a/bot.rb b/bot.rb index ce2f242..4bc350f 100644 --- a/bot.rb +++ b/bot.rb @@ -1,17 +1,17 @@ class Bot - attr_reader :best_choice + attr_reader :best_choice, :val def initialize board, piece + @val = piece @piece = piece @opponent = switch piece end def move board + return "\nGame is done!" if board.is_full? return "\nSomeone won!" if board.any_winner? -# move = @board.get_free.sample -# @board.set " O ", move minmax board, @piece board.set @piece, @best_choice end @@ -23,13 +23,12 @@ class Bot scores = {} board.get_free.each do |space| - # Copy board so we don't mess up original - potential_board = board.dup - potential_board.set cur_player, space + # dup and clone only create a shallow clone, so it doesn't clone the array inside the board object. + board.set cur_player, space - - scores[space] = minmax(potential_board, switch(cur_player)) - potential_board.remove space + scores[space] = minmax(board, switch(cur_player)) + + board.remove space end @best_choice, best_score = best_choice cur_player, scores diff --git a/human.rb b/human.rb index ce1f9c3..9f10e3a 100644 --- a/human.rb +++ b/human.rb @@ -1,8 +1,9 @@ class Human - attr_reader :piece + attr_reader :piece, :val def initialize board, piece + @val = piece @board = board @piece = piece end diff --git a/ticcy.rb b/ticcy.rb index aa400c4..7bd0b1f 100644 --- a/ticcy.rb +++ b/ticcy.rb @@ -7,39 +7,34 @@ require './human' @board = Board.new + def is_over? board, cur + if board.any_winner? then + system "clear" + print board.to_s + print "\n#{cur} won!\n" + return true + elsif board.is_full? then + system "clear" + print board.to_s + print "\nGame is done!\n" + return true + end + end + def play_game player, bot while true do system "clear" print @board.to_s + player.move - if @board.is_full? then - print @board.to_s - print "\nGame is done!\n" - break - end - - if @board.any_winner? then - print @board.to_s - print "\nSomeone won!\n" - break - end + if is_over? @board, player.val then break end bot.move @board - if @board.is_full? then - print @board.to_s - print "\nGame is done!\n" - break - end - - if @board.any_winner? then - print @board.to_s - print "\nSomeone won!\n" - break - end - system "clear" + if is_over? @board, bot.val then break end + end end