-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtic-tac-toe.rb
105 lines (88 loc) · 1.96 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
103
104
105
# frozen_string_literal: true
require 'sinatra'
require 'sinatra/reloader' if development?
require 'tilt/erubis'
require_relative 'lib/game'
configure do
enable :sessions
set :session_key, 'secret'
end
before do
session[:game] ||= Game.new
@game = session[:game]
@board = @game.board
@human_score = @game.human.score
@computer_score = @game.computer.score
end
helpers do
def first_row
@board.squares.values[0...3].each_with_index do |square, idx|
yield square.marker, idx + 1
end
end
def middle_row
@board.squares.values[3...6].each_with_index do |square, idx|
yield square.marker, idx + 4
end
end
def last_row
@board.squares.values[6...9].each_with_index do |square, idx|
yield square.marker, idx + 7
end
end
end
def flash(message, mode = :neutral)
session[:flash] = { message: message, mode: mode }
end
def give_encouragement(winner)
message = case winner
when :human then Game::WIN_MESSAGES.sample
when :computer then Game::LOSE_MESSAGES.sample
when :draw then Game::DRAW_MESSAGES.sample
end
flash(message)
end
def handle_logic
if @game.someone_won_round?
@game.give_point
give_encouragement(@game.round_winner)
@game.reset_round
redirect '/play'
elsif @game.draw?
give_encouragement(@game.round_winner)
@game.reset_round
redirect '/play'
end
end
def play_round(box)
if @board.unmarked_keys.include? box
@game.human_moves(box)
handle_logic
@game.computer_moves
handle_logic
else
flash('Sorry, you must choose an empty square.', :error)
end
end
def reset
@game.reset_game
end
get '/' do
redirect '/play'
end
get '/play' do
erb :play
end
post '/play' do
play_round(params[:box].to_i)
erb :play
end
get '/reset' do
flash('Are you sure you want to reset? (This cannot be undone!)', :error)
erb :reset
end
post '/reset' do
flash('Game successfully reset!', :success)
reset
redirect '/play'
end