-
Notifications
You must be signed in to change notification settings - Fork 0
/
tictactoe.rb
90 lines (80 loc) · 1.98 KB
/
tictactoe.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
require './models.rb'
require './views.rb'
# require 'pry'
class Game
def initialize
puts 'Enter board size (3 to 8): '
size = gets.chomp
@board = GameBoard.new(size.to_i)
@game_ended = false
@whose_turn = 'X'
end
def start_game
system "clear"
Hashtag.draw(@board)
until @board.winner || @game_ended
display_info
next_move = get_input
system "clear"
do_move(next_move) if next_move
Hashtag.draw(@board)
end
if @game_ended
puts "Game ended by user"
else
puts "Winner: #{@board.winner}"
end
puts "Thanks for playing!"
end
def display_info
puts "Current turn: #{@whose_turn}"
if [email protected]_to_win?(@whose_turn)
puts "Sadly, it's no longer possible for #{@whose_turn} to win."
end
# puts @board.possible_moves.map { |m| format_input(m) }.inspect
puts "Best move: ", format_input(@board.best_move(@whose_turn)).inspect
puts "Enter move (row, col); C = accept choice; R = random move; Q = quit:"
end
def get_input
user_input = gets.chomp.split(',')
return false if !user_input[0]
case user_input[0].upcase
when "C"
move = @board.best_move(@whose_turn)
move = format_input(move)
when "P"
# pry
when "Q"
self.end_game
return false
when "R"
move = @board.possible_moves.sample
move = format_input(move)
else
row = user_input[0].to_i
col = user_input[1].to_i
move ? move : [row, col]
end
end
def format_input(move) #turns 0-indexed coords into 1-indexed coords
if move
[move[0] + 1, move[1] + 1]
end
end
def do_move(next_move)
row = next_move[0]
col = next_move[1]
if @board.move(@whose_turn, row, col)
next_player
else
puts "Square (#{row}, #{col}): invalid move"
end
end
def next_player
@whose_turn == 'X' ? @whose_turn = 'O' : @whose_turn = 'X'
end
def end_game
@game_ended = true
end
end
Game.new.start_game