Changed interface slightly

This commit is contained in:
Alexander Munch-Hansen 2018-01-25 20:37:24 +01:00
parent df1d3f59ae
commit b714741e26
4 changed files with 39 additions and 33 deletions

View File

@ -64,5 +64,16 @@ class Board
get_free.empty? get_free.empty?
end 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 end

15
bot.rb
View File

@ -1,17 +1,17 @@
class Bot class Bot
attr_reader :best_choice attr_reader :best_choice, :val
def initialize board, piece def initialize board, piece
@val = piece
@piece = piece @piece = piece
@opponent = switch piece @opponent = switch piece
end end
def move board def move board
return "\nGame is done!" if board.is_full? return "\nGame is done!" if board.is_full?
return "\nSomeone won!" if board.any_winner? return "\nSomeone won!" if board.any_winner?
# move = @board.get_free.sample
# @board.set " O ", move
minmax board, @piece minmax board, @piece
board.set @piece, @best_choice board.set @piece, @best_choice
end end
@ -23,13 +23,12 @@ class Bot
scores = {} scores = {}
board.get_free.each do |space| board.get_free.each do |space|
# Copy board so we don't mess up original # dup and clone only create a shallow clone, so it doesn't clone the array inside the board object.
potential_board = board.dup board.set cur_player, space
potential_board.set cur_player, space
scores[space] = minmax(board, switch(cur_player))
scores[space] = minmax(potential_board, switch(cur_player)) board.remove space
potential_board.remove space
end end
@best_choice, best_score = best_choice cur_player, scores @best_choice, best_score = best_choice cur_player, scores

View File

@ -1,8 +1,9 @@
class Human class Human
attr_reader :piece attr_reader :piece, :val
def initialize board, piece def initialize board, piece
@val = piece
@board = board @board = board
@piece = piece @piece = piece
end end

View File

@ -7,39 +7,34 @@ require './human'
@board = Board.new @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 def play_game player, bot
while true do while true do
system "clear" system "clear"
print @board.to_s print @board.to_s
player.move player.move
if @board.is_full? then if is_over? @board, player.val then break end
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
bot.move @board bot.move @board
if @board.is_full? then if is_over? @board, bot.val then break end
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"
end end
end end