Created
May 4, 2020 08:49
-
-
Save cindywu/e9f25fc52bedbba5bf6a3c6f323feefe to your computer and use it in GitHub Desktop.
tic-tac-toc
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
# 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