Skip to content

Instantly share code, notes, and snippets.

@shinobcrc
Created June 25, 2016 21:10
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 shinobcrc/2ddc0124929c859217e2dbc30bc09149 to your computer and use it in GitHub Desktop.
Save shinobcrc/2ddc0124929c859217e2dbc30bc09149 to your computer and use it in GitHub Desktop.
2 Player Math game
require_relative 'two_player'
require_relative 'question'
@repl = true
@turn_number = 0
puts "Welcome to 2 Player Math"
print 'Player 1 name: '
@name = gets.chomp
player1 = Player.new(@name)
print 'Player 2 name: '
@name = gets.chomp
player2 = Player.new(@name)
puts "Let us begin playing!"
while @repl
question = Question.new
case @turn_number
when 0
print "#{player1.name}"
else
print "#{player2.name}"
end
print question.to_string
@input = gets.chomp.to_i
if @turn == 0 && question.is_answer_correct?(@input)
puts "CORRECT!"
player1.add_point
@turn += 1
elsif @turn == 0 && !question.is_answer_correct?(@input)
puts "Wrong!!!!"
player1.lose_life
@turn += 1
elsif @turn == 1 && question_is_answer_correct?(@input)
puts "CORRECT!!"
player2.add_point
@turn += 1
elsif @turn == 1 && !question_is_answer_correct?(@input)
puts "WRONG!"
player2.lose_life
@turn += 1
end
puts
puts "The score is:
#{player1.name}: #{player1.correct_answers}
#{player2.name}: #{player2.correct_answers}"
puts
if player1.lives < 1 || player2.lives < 1
puts "Game over"
if player1.lives < 1
puts "#{player2.name} wins!"
elsif player2.lives <1
puts "#{player1.name} wins!"
end
@repl = false
end
class Question
attr_reader(:answer)
def intialize
@first_number = rand(1..20)
@second_number = rand(1..20)
@operator = rand(1..3)
case @operator
when 1
@answer = @first_number + @second_number
@operator_string = '+'
when 2
@answer = @first_number - @second_number
@operator_string = '-'
else
@answer = @first_number - @second_number
@operator_string = '*'
end
end
def make_string
"What is #{@first_number} #{operator_string} #{second_number}?"
end
def is_answer_correct?(input)
if input == @answer
return true
else
return false
end
end
end
class Player
attr_accessor (:name, :lives, :correct_answers)
def initialize(name, lives = 3)
@name = name
@lives = lives
@correct_answers = 0
end
def add_point
@correct_answers += 1
end
def lose_life
@lives -= 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment