forked from jimmynguyc/guess-the-number-sinatra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
74 lines (58 loc) · 1.24 KB
/
app.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
require 'sinatra'
require "sinatra/reloader" if development?
enable :sessions
helpers do
def guessed_number
session['guessed_number']
end
def secret_number
session['secret_number']
end
def guess_description
return "" if guessed_number.nil?
if guessed_number < secret_number
too_what = "too low"
else
too_what = "too high"
end
"Your guess of #{guessed_number} was #{too_what}."
end
def guess_prompt
if no_guess_yet?
"Try to guess it!"
else
["Nope!", "Sorry!", "Try Again!", "Drat!", "Darn it!", "Hah, no!"].sample
end
end
end
get '/' do
File.read(File.join('public', 'index.html'))
end
get '/new' do
set_secret_number
clear_guessed_number
redirect to('/play')
end
[:get, :post].each do |verb|
send verb, '/play' do
session['guessed_number'] = params['guessed_number'].to_i if params['guessed_number']
if guessed_correctly?
erb :win
else
erb :play
end
end
end
private
def guessed_correctly?
session['guessed_number'] == session['secret_number']
end
def no_guess_yet?
session['guessed_number'].nil?
end
def set_secret_number
session['secret_number'] = rand(99) + 1
end
def clear_guessed_number
session['guessed_number'] = nil
end