Skip to content
Permalink
Browse files

Set up some standard Ruby namespacing and file organization.

By simply dropping our procedure within the TicTacToe::Game module, we can
now interact with it from irb, or from any controller code that we'd like.  This
of course will be more useful when we add other functions to work with, but at
least makes it possible to load the code without running it immediately, and
moves the logic out of the global namespace.
  • Loading branch information...
practicingruby committed Dec 3, 2010
1 parent 7fd72a3 commit 5af96941d74f8014a3276b77fe67c17e0ed5e2df
Showing with 69 additions and 57 deletions.
  1. +3 −0 app.rb
  2. +1 −0 lib/tictactoe.rb
  3. +65 −0 lib/tictactoe/game.rb
  4. +0 −57 tictactoe.rb
3 app.rb
@@ -0,0 +1,3 @@
require_relative "lib/tictactoe"

TicTacToe::Game.play
@@ -0,0 +1 @@
require_relative "tictactoe/game.rb"
@@ -0,0 +1,65 @@
module TicTacToe
module Game
extend self

def play
board = [[nil,nil,nil],
[nil,nil,nil],
[nil,nil,nil]]

left_diagonal = [[0,0],[1,1],[2,2]]
right_diagonal = [[2,0],[1,1],[0,2]]


players = [:X, :O].cycle

current_player = players.next

loop do
puts board.map { |row| row.map { |e| e || " " }.join("|") }.join("\n")
print "\n>> "
row, col = gets.split.map { |e| e.to_i }
puts

begin
cell_contents = board.fetch(row).fetch(col)
rescue IndexError
puts "Out of bounds, try another position"
next
end

if cell_contents
puts "Cell occupied, try another position"
next
end

board[row][col] = current_player

lines = []

[left_diagonal, right_diagonal].each do |line|
lines << line if line.include?([row,col])
end

lines << (0..2).map { |c1| [row, c1] }
lines << (0..2).map { |r1| [r1, col] }

win = lines.any? do |line|
line.all? { |row,col| board[row][col] == current_player }
end

if win
puts "#{current_player} wins!"
exit
end

if board.flatten.compact.length == 9
puts "It's a draw!"
exit
end

current_player = players.next
end
end
end
end

This file was deleted.

Oops, something went wrong.

0 comments on commit 5af9694

Please sign in to comment.
You can’t perform that action at this time.