Skip to content

Instantly share code, notes, and snippets.

@cindywu
Created May 4, 2020 08:49
Show Gist options
  • Save cindywu/e9f25fc52bedbba5bf6a3c6f323feefe to your computer and use it in GitHub Desktop.
Save cindywu/e9f25fc52bedbba5bf6a3c6f323feefe to your computer and use it in GitHub Desktop.
tic-tac-toc
# new_game = TicTacToe.new
# new_game.play
class TicTacToe
def initialize(board = nil)
@board = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
end
def display_board(board)
puts "|#{board[0]}|#{board[1]}|#{board[2]}|"
puts "|#{board[3]}|#{board[4]}|#{board[5]}|"
puts "|#{board[6]}|#{board[7]}|#{board[8]}|"
end
WIN_COMBOS = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
]
def reset_board
@board = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
end
def input_to_index(user_input)
user_input.to_i - 1
end
def move(index, current_player)
@board[index] = current_player
end
def position_taken?(index)
if (@board[index] == "x" || @board[index] == "o")
true
else
false
end
end
def valid_move?(index)
if position_taken?(index) == false
true
else
false
end
end
def turn
puts current_player
puts "make your move:"
user_input = gets.strip
index = input_to_index(user_input)
if valid_move?(index)
move(index, current_player)
else
puts "something about that i don't like...try again"
display_board(@board)
turn
end
end
def turn_count
@board.count { |current_player| current_player == "x" || current_player =="o"}
end
def current_player
turn_count % 2 == 0 ? "x" : "o"
end
def won?
WIN_COMBOS.detect do |combo|
@board[combo[0]] == @board[combo[1]] && @board[combo[1]] == @board[combo[2]] && position_taken?(combo[0])
end
end
def full?
@board.all? { |index| index == "x" || index == "o"}
end
def draw?
full? && !won?
end
def over?
won? || draw?
end
def winner
if won?
winner = @board[won?[0]]
end
end
def play
until over?
display_board(@board)
turn
end
if won?
display_board(@board)
puts "congrats! #{winner} is the champion!"
elsif draw?
display_board(@board)
puts "its a tie..."
end
puts "play again? y/n"
user_input = gets.strip
if user_input == "y" || user_input == "Y"
reset_board
play
else
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment