Skip to content

Instantly share code, notes, and snippets.

@surmistry
Last active April 10, 2017 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save surmistry/6a978a209938bcd7e57f4bc1c6fc88dd to your computer and use it in GitHub Desktop.
Save surmistry/6a978a209938bcd7e57f4bc1c6fc88dd to your computer and use it in GitHub Desktop.
Ruby Math game
class Game
@@rightwrong = ['Seriously? NO!', 'ZOMG no nNOOOO!', 'Are you blind? WRONG', 'Maybe math isn\'t your thing']
def challenge(ans)
ans == $stdin.gets.chomp.to_i
end
def new_turn
return "----- NEW TURN -----"
end
def game_over (name, score)
str = "#{name} wins with a score of #{score}\n----- GAME OVER -----\nGood Bye!"
end
def response(right)
str = ''
right ? str = "CORRECT" : str = @@rightwrong[rand(4)-1]
return str
end
end
require './player.rb'
require './question.rb'
require './game.rb'
play1 = Player.new
play2 = Player.new
game = Game.new
player = play1
begin
q = Question.new
puts "#{play1.name}: #{q.ques}"
right = game.challenge(q.answer)
puts "#{play1.name}: #{game.response(right)}"
right ? play1.right : play1.lose
puts "P1: #{play1.lives}/3 vs P2: #{play2.lives}/3"
if play1.lives == 0
winner = play2
break
end
puts game.new_turn
q = Question.new
puts "#{play2.name}: #{q.ques}"
right = game.challenge(q.answer)
puts "#{play2.name}: #{game.response(right)}"
right ? play2.right : play2.lose
puts "P1: #{play1.lives}/3 vs P2: #{play2.lives}/3"
if play2.lives == 0
winner = play1
break
end
end while play1.lives > 0 && play2.lives > 0
puts game.game_over(winner.name, winner.score)
class Player
attr_reader :name, :lives, :score
attr_writer :name, :lives
@@count = 0
def initialize
@@count += 1
puts "Enter a name for Player #{@@count}"
@score = 0
@lives = 3
@name = $stdin.gets.chomp
puts "#{@name} has #{@lives} lives with a score of #{@score}"
end
def lose
@lives -= 1
end
def right
@score += 1
end
end
class Question
attr_reader :ques, :answer
def initialize
first = rand(10)
last = rand(10)
@ques = "What does #{first} plus #{last} equal?"
@answer = first + last
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment