Created
October 30, 2011 22:38
-
-
Save leklund/1326546 to your computer and use it in GitHub Desktop.
Rock, paper, scissors, lizard, spock in Sinatra
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, :lizard], | |
paper: [:rock, :spock], | |
scissors: [:paper, :lizard], | |
lizard: [:paper, :spock], | |
spock: [:rock, :scissors] | |
} | |
#@defeat = {rock: :scissors, paper: :rock, scissors: :paper} | |
@throws = @defeat.keys | |
end | |
get '/throw/:type' do | |
# the params[] hash 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 | |
# compare the player and computer throws to determine a winner | |
if player_throw == computer_throw | |
"You tied with the computer. Try again!" | |
elsif @defeat[player_throw].index(computer_throw) | |
"Nicely done; #{player_throw} beats #{computer_throw}!" | |
else | |
"Ouch; #{computer_throw} beats #{player_throw}. Better luck next time!" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment