Created
May 16, 2015 21:51
-
-
Save ak8824/8fcf8fc469d49b479729 to your computer and use it in GitHub Desktop.
Tic Tac Toe Winner Check
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
game = [["x","x", "o"],["x", "o", "x"], ["x", "o", "x"]] | |
def game_winner?(game, player_sign) | |
result = get_winning_sign(game) | |
if result.nil? | |
return game.flatten.include?(nil) ? "Game in Progress" : "Draw" | |
else | |
return result == player_sign ? "Player #{player_sign} is the winner" : "Player #{player_sign} is the loser" | |
end | |
end | |
def get_winning_sign(game) | |
x_val = check_x(game) | |
y_val = check_y(game) | |
z_val = check_z(game) | |
[x_val, y_val, z_val].compact.first | |
end | |
def check_z(game) | |
check1 = [game[0][0], game[1][1], game[2][2]].uniq | |
check2 = [game[0][2], game[1][1], game[2][0]].uniq | |
if check1.count == 1 | |
return check1.first | |
elsif check2.count == 1 | |
return check2.first | |
end | |
end | |
def check_y(game) | |
3.times do |x| | |
values = [game[0][x], game[1][x], game[2][x]].uniq | |
return values.first if values.count == 1 | |
end | |
nil | |
end | |
def check_x(game) | |
row = game[0].uniq.count == 1 | |
row1 = game[1].uniq.count == 1 | |
row2 = game[2].uniq.count == 1 | |
if row || row1 || row2 | |
winning_index = [row, row1, row2].index(true) | |
return game[winning_index].uniq.first | |
else | |
return nil | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment