-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.rb
37 lines (30 loc) · 1.2 KB
/
game.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
require 'sinatra'
# before we process a route, we'll set the response as
# plain text and set up an array of viable moves that
# a player (and the computer) can perform
before do
content_type :txt
@defeat = {rock: :scissors, paper: :rock, scissors: :paper}
@throws = @defeat.keys
end
get '/throw/:type' do
# the params[] has stores querystring and form data
player_throw = params[:type].to_sym
# in the case of a player providing a throw that is not valid,
# we halt with a status code of 403 (forbidden) and let them
# know they need to make a valid throw to play
if [email protected]?(player_throw)
halt 403, "You must throw one of the following: #{@throws}"
end
#now we can select a random throw for the computer
computer_throw = @throws.sample
computer_message = "The computer threw #{computer_throw}."
# compare the player and computer throws to determine a winner
if player_throw == computer_throw
"#{computer_message} You tied with the computer. Try again!"
elsif computer_throw == @defeat[player_throw]
"#{computer_message} Nicely done; #{player_throw} beats #{computer_throw}!"
else
"#{computer_message} Ouch; #{computer_throw} beats #{player_throw}. Better luck next time."
end
end