Created
October 1, 2009 16:42
-
-
Save ryankuykendall/199089 to your computer and use it in GitHub Desktop.
three-d-tic-tac-toe.rb
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
module ThreeDTicTacToe | |
class Game | |
attr_reader :length_to_win | |
def initialize(length_to_win = 3) | |
@length_to_win = length_to_win | |
@board = {} | |
end | |
def place_piece(color, x, y, z) | |
if space_empty?(x, y, z) | |
@board[coords_to_board_key(x, y, z)] = color | |
return true | |
end | |
false | |
end | |
def space_empty?(x, y, z) | |
[email protected]_key?(coords_to_board_key(x, y, z)) | |
end | |
def score_space(color, x, y, z) | |
[ | |
score_for_x(color, x, y, z), | |
score_for_y(color, x, y, z), | |
score_for_z(color, x, y, z), | |
score_for_xyz_diag(color, x, y, z), | |
score_for_nxyz_diag(color, x, y, z), | |
score_for_nxnyz_diag(color, x, y, z), | |
score_for_xnyz_diag(color, x, y, z) | |
].sort {|x,y| y <=> x}.first | |
end | |
private | |
def coords_to_board_key(x, y, z) | |
[x, y, z].map {|coord| coord.to_s}.join(',') | |
end | |
def score_for(color, x, y, z, positive_proc, negative_proc) | |
length = counter = 1 | |
search_positive_direction = search_negative_direction = true | |
while search_positive_direction || search_negative_direction | |
if search_positive_direction && @board[coords_to_board_key(*(positive_proc.call(counter, x, y, z)))] == color | |
length += 1 | |
else | |
search_positive_direction = false | |
end | |
if search_negative_direction && @board[coords_to_board_key(*(negative_proc.call(counter, x, y, z)))] == color | |
length += 1 | |
else | |
search_negative_direction = false | |
end | |
counter += 1 | |
end | |
length | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment