/
tic_tac_toe.rb
102 lines (85 loc) · 1.87 KB
/
tic_tac_toe.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
class TicTacToe
def initialize(board = nil)
@board = board || Array.new(9, " ")
end
def display_board
puts " #{@board[0]} | #{@board[1]} | #{@board[2]} "
puts "-----------"
puts " #{@board[3]} | #{@board[4]} | #{@board[5]} "
puts "-----------"
puts " #{@board[6]} | #{@board[7]} | #{@board[8]} "
end
def input_to_index(user_input)
user_input.to_i - 1
end
def move( index, token)
#current_player = "X"
@board[index] = token
end
def valid_move?( index)
index.between?(0,8) && !position_taken?( index)
end
def turn
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?( index)
move(index, current_player)
display_board
else
turn
end
end
def turn_count
@board.count("O") + @board.count("X")
end
def current_player
turn_count.odd? ? "O" : "X"
end
def position_taken?( index) #Helper Method
!(@board[index].nil? || @board[index] == " ")
end
WIN_COMBINATIONS = [
[0,1,2], # Top row
[3,4,5], # Middle row
[6,7,8], # Bottom row
[0,3,6], # 1st column
[1,4,7], # 2nd column
[2,5,8], # 3rd column
[0,4,8], # diagonal one
[2,4,6] # diagonal two
]
def won?
WIN_COMBINATIONS.find do |win_combination|
# win_combination is a 3 element array of indexes that compose a win, [0,1,2]
# grab each index from the win_combination that composes a win.
@board[win_combination[0]] == @board[win_combination[1]] &&
@board[win_combination[1]] == @board[win_combination[2]] &&
position_taken?(win_combination[0])
end
end
def full?
@board.all? {|token| token== "X"|| token== "O"}
end
def draw?
full? && !won?
end
def over?
won? || full?
end
def winner
if win_row = won?
@board[win_row[0]]
end
end
def play
until over?|| draw?
turn
end
if won?
puts "Congratulations #{winner}!"
elsif draw?
puts "Cat's Game!"
end
end
end