Created
August 7, 2017 22:48
-
-
Save dustMason/ee768589d9507294d193f03752f76122 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'io/console' | |
class TicTacToe | |
attr_reader :state | |
def initialize *players | |
@players = players | |
@state = players.map { Array.new(9) } | |
@marks = ['X','O'] | |
end | |
def print | |
# system 'clear' | |
board = Array.new(9,'-') | |
@state.each_with_index do |state, player_index| | |
state.each_with_index do |cell, i| | |
board[i] = @marks[player_index] if cell == 1 | |
end | |
end | |
puts board.each_slice(3).map { |row| row.join("|") }.join("\n") | |
end | |
def mark x, y, player_index | |
cursor = (y*3) + x | |
@state[player_index][cursor] = 1 | |
end | |
def full? | |
@state.reduce(0) { |acc, s| acc + s.reduce(0) { |tacc, t| tacc + 1 if t == 1 }} | |
end | |
end | |
class AI | |
def self.move state | |
index = available_squares(state)[0] | |
y = index / 3 | |
x = index % 3 | |
return [x, y] | |
end | |
private | |
def self.available_squares state | |
available = (0..8).to_a | |
state.each do |_state| | |
_state.each_with_index do |s, i| | |
available -= [i] if s == 1 | |
end | |
end | |
available | |
end | |
end | |
game = TicTacToe.new "Jordan", "Nitin" | |
game.mark 1, 0, 0 | |
game.print | |
5.times do | |
ai_move = AI.move game.state | |
game.mark ai_move[0], ai_move[1], 1 | |
end | |
game.print |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment