Skip to content

Instantly share code, notes, and snippets.

@sidazhou
Created October 3, 2014 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sidazhou/6ce9e465dc42c063f8ec to your computer and use it in GitHub Desktop.
Save sidazhou/6ce9e465dc42c063f8ec to your computer and use it in GitHub Desktop.
adding 2 numbers correctly and in 5 seconds GAME
require 'colorize'
# # "Player 1: What does 5 plus 3 equal?"
# # Both players start with 3 lives. They lose a life if they mis-answer a question. If a player gets a question wrong, the game should output the new scores for both players, so players know where they stand.
# # The game doesn’t end until one of the players loses all their lives. At this point, the game should announce who won and what the other player’s score is.
def getRandNums
# [ (rand*10-5).round(1), (rand*10-5).round(1) ] # rounding errs
[ rand(100..1000) , rand(-100..100) ]
end
def getRandStr
(0...3).map { (65 + rand(26)).chr }.join #http://stackoverflow.com/questions/88311/how-best-to-generate-a-random-string-in-ruby
end
class Player
attr_reader :player_name, :numLife, :score
def initialize(player_name)
@player_name = player_name
@numLife = 3
@score = 0
end
def loseLife
@numLife -= 1
end
def addScore
@score += 1
end
def dispLife
puts "#{@player_name} has #{@numLife} life left...".red
end
def dispScore
puts "#{@player_name} has #{@score} score!".green
end
end
####### MAIN #########
players = []
2.times do |i| # 2 players
players << Player.new(getRandStr)
end
runningFlag = true
begin
for player in players ## each players ##
start_time = Time.now
x , y = getRandNums
puts "#{player.player_name}: What does #{x} plus #{y} equal?"
guess = gets.chomp.to_f
end_time = Time.now
if guess == x + y && (end_time-start_time < 5) # 3 seconds
puts "==============="
puts "correct!".green
puts "Time spent was: #{end_time-start_time}".green
player.addScore()
player.dispScore()
puts "==============="
else
puts "==============="
puts "incorrect! / You were too slow!".red
puts "correct answer was : #{x+y}.".red
puts "Time spent was: #{end_time-start_time}".red
player.loseLife()
player.dispLife()
puts "==============="
end
end
if players.detect { |player| player.numLife <=0 }
runningFlag = false
break
end
end while runningFlag
puts "======================"
puts "======================"
players.each do |player|
# puts player.numLife.to_s + " is #{player.player_name}'s life in the end"
puts player.score.to_s + " is #{player.player_name}'s score in the end"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment