Created
June 26, 2015 14:19
-
-
Save zigen/e38bb7f75e8bcb6fabae to your computer and use it in GitHub Desktop.
tic tac toe
This file contains 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 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 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 get_mark_index_and_mark | |
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 | |
mark i | |
puts "-----------" | |
show_board | |
end | |
def start | |
puts "=================" | |
puts "Start Tic Tac Toe" | |
puts "=================" | |
while true | |
get_mark_index_and_mark | |
change_turn | |
maybe_winner = who_is_winner? | |
unless maybe_winner == nil | |
puts "#{maybe_winner} won" | |
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] + score_board[i+1] + score_board[i+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