Created
July 20, 2016 01:25
-
-
Save bharris62/3e9574aaae4235b3ecd52bfe10aac7d2 to your computer and use it in GitHub Desktop.
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
# Tic Tac toe | |
require 'pry' | |
INITITAL_MARKER = ' ' | |
PLAYER_MARKER = 'X' | |
COMPUTER_MARKER = 'O' | |
def prompt(msg) | |
puts "=>#{msg}" | |
end | |
def display_board(brd) | |
system 'clear' | |
puts "You're a #{PLAYER_MARKER}. Computer is #{COMPUTER_MARKER}." | |
puts "" | |
puts " | |" | |
puts " #{brd[1]} | #{brd[2]} | #{brd[3]}" | |
puts " | |" | |
puts "-----+-----+-----" | |
puts " | |" | |
puts " #{brd[4]} | #{brd[5]} | #{brd[6]}" | |
puts " | |" | |
puts "-----+-----+-----" | |
puts " | |" | |
puts " #{brd[7]} | #{brd[8]} | #{brd[9]}" | |
puts " | |" | |
puts "" | |
end | |
def initialize_board | |
new_board = {} | |
(1..9).each {|num| new_board[num] = INITITAL_MARKER} | |
new_board | |
end | |
def empty_squares(brd) | |
brd.keys.select {|num| brd[num] == INITITAL_MARKER} | |
end | |
def player_places_piece!(brd) | |
square = "" | |
loop do | |
prompt "Choose a square, #{empty_squares(brd).join(',')}:" | |
square = gets.chomp.to_i | |
break if empty_squares(brd).include?(square) | |
prompt 'not a valid choice' | |
end | |
brd[square] = PLAYER_MARKER | |
end | |
def computer_places_piece!(brd) | |
square = empty_squares(brd).sample | |
brd[square] = COMPUTER_MARKER | |
end | |
def board_full?(brd) | |
empty_squares(brd).empty? | |
end | |
def someone_won?(brd) | |
!!detect_winner(brd) | |
end | |
def detect_winner(brd) | |
winning_lines = [[1,2,3], [4,5,6], [7,8,9]] + # rows | |
[[1,4,7], [2,5,8], [3,6,9]] + # columns | |
[[1,5,9], [3,5,7]] # diagonols | |
winning_lines.each do |line| | |
if brd[line[0]] == PLAYER_MARKER && | |
brd[line[1]] == PLAYER_MARKER && | |
brd[line[2]] == PLAYER_MARKER | |
return 'Player' | |
elsif brd[line[0]] == COMPUTER_MARKER && | |
brd[line[1]] == COMPUTER_MARKER && | |
brd[line[2]] == COMPUTER_MARKER | |
return 'computer' | |
end | |
end | |
nil | |
end | |
loop do | |
board = initialize_board | |
loop do | |
display_board(board) | |
player_places_piece!(board) | |
break if someone_won?(board) || board_full?(board) | |
computer_places_piece!(board) | |
break if someone_won?(board) || board_full?(board) | |
end | |
display_board(board) | |
if someone_won?(board) | |
prompt "#{detect_winner(board)} won!" | |
else | |
prompt "It's a tie!" | |
end | |
prompt "Play Again? (y or n)" | |
answer = gets.chomp | |
break unless answer.downcase.start_with?('y') | |
end | |
prompt "thanks for playing tic tac toe!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment