Skip to content

Instantly share code, notes, and snippets.

@j0ni
Created April 1, 2016 22:02
Show Gist options
  • Save j0ni/67fbdbb3020474f66c1a712823a39cb7 to your computer and use it in GitHub Desktop.
Save j0ni/67fbdbb3020474f66c1a712823a39cb7 to your computer and use it in GitHub Desktop.
module Constants
InitialLives = 3
InitialScore = 0
InitialRecord = 0
RandUpper = 20
RandLower = 1
end
class Question
include Constants
attr_accessor :first_num, :second_num
def to_s
"What's #{first_num} + #{second_num}?"
end
def initialize
self.first_num = rand_num
self.second_num = rand_num
end
def sum
first_num + second_num
end
def correct_guess?(guess)
guess == sum
end
private
def rand_num
rand(RandLower..RandUpper)
end
end
class Player
include Constants
attr_accessor :lives, :score, :name
def no_more_lives?
lives <= 0
end
def initialize(name)
@name = name
@lives = InitialLives
@score = InitialScore
end
def status
"Player #{name} has #{lives} lives and #{score} points"
end
def to_s
name
end
end
class Game
include Constants
attr_reader :players
def initialize(players)
@players = players
@turn = 0
end
def current_player
@players[@turn % 2]
end
def next_turn!
@turn += 1
end
def over?
@players.any? { |p| p.no_more_lives? }
end
class << self
def input(prompt)
print "#{prompt} "
gets.chomp
end
def setup_player(number)
Player.new(input("Player #{number}, please enter your name:"))
end
def play
game = Game.new([1, 2].map{ |n| setup_player(n) })
until game.over?
question = Question.new
puts "Player #{game.current_player}'s turn"
answer = input("Player #{game.current_player}, #{question}")
if question.correct_guess?(answer.to_i)
game.current_player.score += 1
puts "Correct!"
else
game.current_player.lives -= 1
puts "Wrong!"
end
puts game.current_player.status
game.next_turn!
end
puts "Game over!"
game.players.each do |player|
puts "Player #{player} has #{player.lives} lives and #{player.score} points"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment