Skip to content

Instantly share code, notes, and snippets.

@stupeters187
Created April 1, 2016 21:10
Show Gist options
  • Save stupeters187/19e8be9ad96fcbced5a0d1f57bce033b to your computer and use it in GitHub Desktop.
Save stupeters187/19e8be9ad96fcbced5a0d1f57bce033b to your computer and use it in GitHub Desktop.
require 'pry'
class Question
def initialize
@num1 = rand(1...20)
@num2 = rand(1...20)
end
def to_string
puts "What is #{@num1} + #{@num2}"
end
def correct_answer
@answer = @num1 + @num2
end
def is_correct?(user_input)
user_input == @answer
end
end
class Player
attr_accessor :name, :lives, :points
#A player needs to identify themselves
def initialize(name)
@name = name
@lives = 3
@points = 0
end
def answer_correct
@points += 1
end
def answer_incorrect
@lives -= 1
end
end
@turn = 0
puts "Welcome to the Ruby math game"
puts
puts "Please enter your name Player 1"
@input = gets.chomp
player1 = Player.new(@input)
puts "Please enter your name Player 2"
@input = gets.chomp
player2 = Player.new(@input)
puts "Thanks, now we can begin"
while player1.lives > 0 && player2.lives > 0
question = Question.new
case @turn
when 0
puts "Player 1's turn"
when 1
puts "Player 2's turn"
end
question.to_string
question.correct_answer
user_input = gets.chomp.to_i
if @turn == 0 && question.is_correct?(user_input)
puts "Correct!"
player1.answer_correct
puts "Player 1 has #{player1.points} points"
@turn += 1
elsif @turn == 0 && !question.is_correct?(user_input)
puts "Incorrect!"
player1.answer_incorrect
puts "Player 1 has #{player1.lives} lives left"
@turn += 1
elsif @turn == 1 && question.is_correct?(user_input)
puts "Correct!"
player2.answer_correct
puts "Player 2 has #{player2.points} points"
@turn -= 1
elsif @turn == 1 && !question.is_correct?(user_input)
puts "Incorrect!"
player2.answer_incorrect
puts "Player 2 has #{player2.lives} lives left"
@turn -= 1
end
if player1.lives == 0
puts "Game over, Player 2 wins!"
elsif player2.lives == 0
puts "Game over Player 1 wins!"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment