Created
January 14, 2016 19:57
-
-
Save mindplace/181dab4bc1e6b86bdf47 to your computer and use it in GitHub Desktop.
computer class for tic tac toe
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
class ComputerPlayer | |
def initialize(name, mark=0) | |
@name = name | |
@mark = mark | |
end | |
def name | |
@name | |
end | |
def mark | |
@mark | |
end | |
def board | |
grid | |
end | |
def choose_mark(symbol) | |
move = [] | |
row_set = [] | |
if board.any?{|row| row.count(symbol) == 2} | |
row_set = board.select{|row| row.count(symbol) == 2} | |
row_index = board.index(row_set) | |
column = row_set.index(nil) | |
end | |
move = [row_index, column] | |
return move unless move.empty? | |
first_column = [] | |
second_column = [] | |
third_column = [] | |
board.each do |row| | |
first_column << row[0] | |
second_column << row[1] | |
third_column << row[2] | |
end | |
diagonal_set_backslash = [board[0][0], board[1][1], board[2][2]] | |
diagonal_set_forward = [board[0][2], board[1][1], board[2][0]] | |
if first_column.count(symbol) == 2 | |
move = [0, first_column.index(nil)] | |
elsif second_column.count(symbol) == 2 | |
move = [1, first_column.index(nil)] | |
elsif third_column.count(symbol) == 2 | |
move = [2, first_column.index(nil)] | |
elsif diagonal_set_backslash.count(symbol) == 2 | |
location = diagonal_set_backslash.index(nil) | |
if location == 0 | |
move = [0,0] | |
elsif location == 1 | |
move = [1,1] | |
elsif location == 2 | |
move = [2,2] | |
end | |
elsif diagonal_set_forward.count(symbol) == 2 | |
location = diagonal_set_forward.index(nil) | |
if location == 0 | |
move = [0,2] | |
elsif location == 1 | |
move = [1,1] | |
elsif location == 2 | |
move = [2,0] | |
end | |
end | |
move | |
end | |
def choose_random_move | |
board = display(board) | |
options = [] | |
board.each_with_index do |row, i| | |
row.each_with_index do |column, j| | |
if column.nil? | |
options << [i,j] | |
end | |
end | |
end | |
max = options.length | |
options[rand(0..max)] | |
end | |
def get_move | |
move = choose_mark(mark) | |
move = choose_random_move if move.empty? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment