Skip to content

Instantly share code, notes, and snippets.

@Ebonkuab
Created January 12, 2016 20:56
Show Gist options
  • Save Ebonkuab/3640ea9b496b50bc449c to your computer and use it in GitHub Desktop.
Save Ebonkuab/3640ea9b496b50bc449c to your computer and use it in GitHub Desktop.
two player guesing game using OOP ruby ( LIGHTHOUSE WEB DEV BOOTCAMP)
#two player maths game using objects
# defining the player class
class Player
attr_accessor :name, :number_of_lives
def initialize (name)
@name = name
@number_of_lives= 3
end
def increaseNoOfLives()
@number_of_lives += 1
end
def reduceNoOfLives()
@number_of_lives -= 1
end
#method to get the player answer to the question
def prompt_player_for_answer()
@playerAnswer=gets.chomp.to_i
end
#method for verifying answer and giving increasing or reducing the number of lives
def verify_answer
if @@result == @playerAnswer
puts " the answer #{@playerAnswer} is correct"
increaseNoOfLives
puts " the number of lives is now #{@number_of_lives}"
else
puts " the answer #{@playerAnswer} is NOT correct"
reduceNoOfLives
puts " the number of lives is now #{@number_of_lives}"
end
end
#defining the random generated addition questions via a class method/
def self.generate_question
num1 = rand(20)
num2 = rand(20)
@@result = num1 + num2
puts "what is the value of #{num1} + #{num2}"
end
end
player1= Player.new("player1")
player2= Player.new("player2")
while ((player1.number_of_lives > 0) && (player2.number_of_lives > 0)) #logic needs some twerking to end game when one player reaches 0 lives
Player.generate_question
player1.prompt_player_for_answer
player1.verify_answer
Player.generate_question
player2.prompt_player_for_answer
player2.verify_answer
puts player1.number_of_lives > 0
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment