Skip to content

Commit

Permalink
generate some simple "questions", pass them to the players, and check…
Browse files Browse the repository at this point in the history
… the results
  • Loading branch information
rchatley committed Apr 6, 2011
1 parent 0687684 commit cff4974
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 10 deletions.
2 changes: 1 addition & 1 deletion player_x.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
require 'sinatra'

get '/' do
"hi there #{Time.now}"
"6"
end
2 changes: 1 addition & 1 deletion player_y.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
end

get '/' do
"hi there from Y #{Time.now}"
"4"
end
53 changes: 45 additions & 8 deletions web_server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,63 @@ def initialize
@scores = Hash.new { 0 }
end

def increment_score_for(player_uuid)
@scores[player_uuid] += 1
def increment_score_for(player)
@scores[player.uuid] += 1
end

def new_player(player)
@scores[player.uuid] = 0
end

def leaderboard
@scores.sort{|a,b| a[1]<=>b[1]}.reverse
end
end

class Question
def initialize(text)
@text = text
end

def answered_correctly(answer)
correct_answer = eval(@text)
return correct_answer.to_s.strip == answer.to_s.strip
end

def to_s
return @text
end
end

class QuestionFactory
def next_question
return Question.new("#{rand(5)}+#{rand(5)}")
end
end

class Shopper
def initialize(player, scoreboard)
@player = player
@scoreboard = scoreboard
@question_factory = QuestionFactory.new
end

def start
while true
response = HTTParty.get(@player.url)
@scoreboard.increment_score_for(@player.uuid)
question = @question_factory.next_question
url = @player.url + '?q=' + question.to_s
puts "GET:" + url
response = HTTParty.get(url)
puts "question was " + question.to_s
puts "player #{@player.name} said #{response}"
sleep 5
if (question.answered_correctly(response)) then
puts "player #{@player.name} was correct"
@scoreboard.increment_score_for(@player)
sleep 5
else
puts "player #{@player.name} was wrong"
sleep 10
end
end
end
end
Expand Down Expand Up @@ -75,10 +111,11 @@ def to_s

post '/players' do
player = Player.new(params)
Thread.new { Shopper.new(player, $scoreboard).start }
$scoreboard.new_player(player)
$players[player.uuid] = player

Thread.new { Shopper.new(player, $scoreboard).start }

personal_page = "http://#{local_ip}:#{@env["SERVER_PORT"]}/players/#{player.uuid}"

personal_page = "http://#{local_ip}:#{@env["SERVER_PORT"]}/players/#{player.uuid}"
haml :player_added, :locals => { :url => personal_page }
end

0 comments on commit cff4974

Please sign in to comment.