Skip to content

Instantly share code, notes, and snippets.

@maxjacobson
Created December 11, 2012 03:34
Show Gist options
  • Save maxjacobson/37063b67b6e7c42d65a4 to your computer and use it in GitHub Desktop.
Save maxjacobson/37063b67b6e7c42d65a4 to your computer and use it in GitHub Desktop.
command line tic tac toe
###### some methods #######
def print_board
puts
for i in 0..8
if @the_board[i].nil?
print "#{i+1}"
else
print "#{@the_board[i]}"
end
if (i + 1) % 3 == 0 # if it's the end of a row
print "\n"
else
print " "
end
end
puts
end
def change_turns
if @current_player == "X"
@current_player = "O"
else
@current_player = "X"
end
end
def update_game_over
# first let's check if someone has won
[[0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 4, 8], [2, 4, 6]].each do |winner| # these are all 8 winners
if @the_board[winner[0]].nil? == false and @the_board[winner[0]] == @the_board[winner[1]] and @the_board[winner[0]] == @the_board[winner[2]]
return "Player #{@current_player} wins!"
end
end
# if no one has yet won, let's check if the board is full
if @the_board.include?(nil) == false
return "Welp, another tie game."
end
# this game ain't over til it's over
return false
end
######## let's get started ########
@the_board = [
nil, nil, nil,
nil, nil, nil,
nil, nil, nil
]
puts "Welcome to tic tac toe by Max Jacobson"
puts
puts "One or two player mode? (1/2)"
print "> "
mode = gets.chomp.to_i
if mode == 1
puts "Prepare to test your wits against a SUPER smart AI"
# joking. a good AI would make every game a tie, no?
# lets let the computer go first half the time
if rand(0..1) == 0
@current_player = "X"
else
@current_player = "O"
puts "Let's let the computer go first..."
end
sleep 1
else
@current_player = "X"
end
game_over = false
while game_over == false
if @current_player == "O" and mode == 1 # if it's time for the computer to move
# we'll find a random spot on the board that isn't already taken
thinking = true
while thinking == true
new_move = rand(0..8)
if @the_board[new_move].nil?
thinking = false
end
end
else # if it's time for a human to move
# display the board and get their move
print_board
puts "#{@current_player}'s move (1-9)"
print "> "
new_move = gets.chomp.to_i - 1
end
if @the_board[new_move].nil? # if that spot isn't already taken
@the_board[new_move] = @current_player # update the board
game_over = update_game_over # check if the game is over
if game_over == false
change_turns
end
else # if that spot WAS already taken (good try!)
puts "Sorry, that spot is already taken, try again?"
sleep 1
end
end # game over
# once the game is over, display the board one more time and then the results
print_board
puts "#{game_over}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment