Created
March 7, 2014 19:31
-
-
Save jbgo/9418220 to your computer and use it in GitHub Desktop.
Interactive tic tac toe game
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 TicTacToeApp | |
NIL_GAME = [ | |
[nil, nil, nil], | |
[nil, nil, nil], | |
[nil, nil, nil] | |
] | |
def initialize | |
@game = NIL_GAME | |
@turn = 'X' | |
@turn_count = 0 | |
end | |
def run | |
done = false | |
while ! done do | |
print_game | |
print "#{@turn}'s turn. What position would you like to occupy: " | |
pos = gets | |
if quit?(pos) | |
done = true | |
next | |
elsif !valid?(pos) | |
puts "INVALID MOVE! Try again..." | |
next | |
end | |
occupy(pos) | |
done = true if game_over?(pos) | |
if someone_won? | |
puts "We have a winner: #{@turn}!!!" | |
print_game | |
elsif game_over?(pos) | |
puts "CATS!!!!!!!!" | |
print_game | |
end | |
next_turn | |
end | |
end | |
def occupy(pos) | |
a, b = pos.split(',').map(&:to_i) | |
board_pos = @game[a][b] | |
if board_pos.nil? | |
@game[a][b] = @turn | |
else | |
puts "SPACE ALREADY TAKEN! Try again..." | |
end | |
end | |
def valid?(pos) | |
pos =~ /(quit|[0-2],[0-2])/i | |
end | |
def game_over?(pos) | |
@turn_count > 7 || someone_won? | |
end | |
def someone_won? | |
horizontal_winner? || | |
vertical_winner? || | |
diagonal_winner? | |
end | |
def horizontal_winner? | |
@game.map {|row| | |
row.all? {|val| | |
val == @turn | |
} | |
}.any? { |x| x } | |
end | |
def vertical_winner? | |
winning_positions = [ | |
[0,3,6], | |
[1,4,7], | |
[2,5,8] | |
] | |
winning_positions.any? do |wp| | |
chars = [] | |
wp.each do |pos| | |
chars << @game[pos] | |
end | |
chars.uniq.size == 1 | |
end | |
end | |
def diagonal_winner? | |
(@turn == @game[0][0] && @turn == @game[1][1] && @turn == @game[2][2]) || | |
(@turn == @game[2][0] && @turn == @game[1][1] && @turn == @game[0][2]) | |
end | |
def quit?(pos) | |
pos =~ /quit/i | |
end | |
def next_turn | |
@turn = (@turn == 'X' ? 'O' : 'X') | |
@turn_count += 1 | |
end | |
def print_game | |
@game.each_with_index do |row, i| | |
puts row.map { |x| x.nil? ? ' ' : x }.join(" | ") | |
puts '-' * 9 unless i == 2 | |
end | |
return | |
end | |
end | |
game = TicTacToeApp.new | |
game.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is a result of the first experiment in Chaos Driven Development (CDD) with @tehcurtis @scally @skscally and @jyunderwood