Skip to content

Instantly share code, notes, and snippets.

@zigen
Created June 26, 2015 16:28
Show Gist options
  • Save zigen/4ae25c75d2089ba9e741 to your computer and use it in GitHub Desktop.
Save zigen/4ae25c75d2089ba9e741 to your computer and use it in GitHub Desktop.
Level2
class Tic
X = "x"
O = "o"
def initialize
puts "Initialized"
@board = [
"-","-","-",
"-","-","-",
"-","-","-",
]
@turn = X
end
def show_board
puts "-------"
@board.each_index do |i|
print " #{@board[i]}"
print "\n" if i % 3 == 2
end
end
def set_board board
@board = board
end
def markable_list
markables = []
@board.each_index do |i|
markables.push(i) if @board[i] == "-"
end
markables
end
def show_board_index
puts "-------"
@board.each_index do |i|
print " #{if @board[i] == "-" then i else "-" end}"
print "\n" if i % 3 == 2
end
end
def markable? i
return false unless i > -1 and i < 9
return false unless @board[i] == "-"
true
end
def mark i
@board[i] = @turn
end
def change_turn
if @turn == X
@turn = O
else
@turn = X
end
end
def read_mark_index
puts "type index of board"
show_board_index
i = gets.to_i
while not markable?(i)
puts "you choosed invalid value"
i = gets.to_i
end
i
end
def start
puts "================="
puts "Tic Tac Toe"
puts "Copyright 2015, Kentaro Teramoto\n Released under the MIT Licenses. \n Date: Sat June 27 2015"
puts "================="
puts "\n 1: play with computer, \n 2: play with friend \n type 1 or 2"
mode = gets.to_i
while true
if @turn == X or mode == 2
index = read_mark_index
else
index = markable_list.sample
end
mark index
show_board
change_turn
maybe_winner = who_is_winner?
unless maybe_winner == nil
puts "#{maybe_winner} won"
break
end
if markable_list.length == 0
puts "Draw"
break
end
end
end
def who_is_winner?
score_board = [0,0,0,0,0,0,0,0,0]
@board.each_index do |i|
if @board[i] == O
score_board[i] = 1
elsif @board[i] == X
score_board[i] = -1
end
end
result = []
3.times do |i|
result.push(score_board[i*3] + score_board[i*3+1] + score_board[i*3+2])
result.push(score_board[i] + score_board[i+3] + score_board[i+6])
end
result.push(score_board[0] + score_board[4] + score_board[8])
result.push(score_board[2] + score_board[4] + score_board[6])
result.each do |i|
return O if i == 3
return X if i == -3
end
return nil
end
end
game = Tic.new
game.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment