Skip to content

Instantly share code, notes, and snippets.

@joeainsworth
Created January 7, 2016 21:30
Show Gist options
  • Save joeainsworth/fc2e12e4fdac894c280f to your computer and use it in GitHub Desktop.
Save joeainsworth/fc2e12e4fdac894c280f to your computer and use it in GitHub Desktop.
require 'pry'
class Board
attr_accessor :square
def initialize
create_board
end
def create_board
square = {}
1.upto(9) { |n| square[n] = Square.new }
self.square = square
end
def empty_squares
square.select { |_,v| v.mark == ' ' }.keys
end
end
class Square
attr_accessor :mark
def initialize
@mark = ' '
end
def to_s
mark
end
end
class Player
attr_accessor :name
def initialize
set_name
end
end
class Human < Player
HUMAN_MARKER = 'X'
def set_name
puts 'Please enter your name:'
answer = nil
loop do
answer = gets.chomp
break unless answer.empty?
puts 'Please enter a valid name.'
end
self.name = name
end
def turn!(board)
puts "Choose a square from either #{board.empty_squares.join(', ')}:"
answer = nil
loop do
answer = gets.chomp.to_i
break if board.empty_squares.include?(answer)
puts 'Please enter a valid number.'
end
board.square[answer] = HUMAN_MARKER
end
end
class Computer < Player
COMPUTER_MARKER = 'O'
def set_name
self.name = %w(Alex Cathrine Greg Rachel)
end
def turn!(board)
# logic for computer to select a square
end
end
class GameEngine
attr_accessor :board, :human, :computer
def initialize
clear_screen
@board = Board.new
@human = Human.new
@computer = Computer.new
end
def clear_screen
system 'clear'
end
def display_board
puts ' | | '
puts " #{board.square[1]} | #{board.square[2]} | #{board.square[3]} "
puts ' | | '
puts '-----------------'
puts ' | | '
puts " #{board.square[4]} | #{board.square[5]} | #{board.square[6]} "
puts ' | | '
puts '-----------------'
puts ' | | '
puts " #{board.square[7]} | #{board.square[8]} | #{board.square[9]} "
puts ' | | '
puts ''
end
def play
clear_screen
loop do
display_board
human.turn!(board)
end
display_board
end
end
GameEngine.new.play
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment