Skip to content

Instantly share code, notes, and snippets.

@juicedM3
Last active October 17, 2019 03:40
Show Gist options
  • Select an option

  • Save juicedM3/d79bd5b57dc987b345850d37ed7cd9e6 to your computer and use it in GitHub Desktop.

Select an option

Save juicedM3/d79bd5b57dc987b345850d37ed7cd9e6 to your computer and use it in GitHub Desktop.
!/usr/bin/env ruby
#
# My 6 year old has a home work assignment where he has to roll 2 dice and perform addition.
# I doubt we can find any dice in this house (thanks to him), so I wrote a quick script and
# probably took it too far. So based on the concept of "rolling 2 dice", but you can add,
# subtract, multiple and divide if you wish and pick the number of "sides" (default is 6).
# The division isn't as fun and my Ruby is super rusty so it's good practice.
#
class DiceMath
attr_accessor :d1
attr_accessor :d2
attr_accessor :answer
attr_accessor :max
attr_accessor :mod
def initialize(m=6)
self.max = m
self.roll
end
def self.for(f="addition",m=6)
case f
when "subtraction"
DiceMathSubtract.new(m)
when "multiplication"
DiceMathMultiply.new(m)
when "division"
DiceMathDivide.new(m)
else
DiceMathAdd.new(m)
end
end
def roll
self.d1 = rand(1..self.max)
self.d2 = rand(1..self.max)
self.perform_arithmetic
end
def perform_arithmetic
raise "Must be implemented in child class."
end
def to_s
printf "%i %s %i = ", self.d1, self.mod, self.d2
end
def is_answer_correct?(ans)
return self.answer == ans
end
end
class DiceMathAdd < DiceMath
def initialize(m)
self.mod = "+"
super
end
def perform_arithmetic
self.answer = self.d1 + self.d2
end
end
class DiceMathSubtract < DiceMath
def initialize(m)
self.mod = "-"
super
end
def perform_arithmetic
# only want positive answers; the kid is 6!
_switch_if_larger
self.answer = self.d1 - self.d2
end
private
def _switch_if_larger
if self.d2 > self.d1
tmp = self.d1
self.d1 = self.d2
self.d2 = tmp
end
end
end
class DiceMathMultiply < DiceMath
def initialize(m)
self.mod = "*"
super
end
def perform_arithmetic
self.answer = self.d1 * self.d2
end
end
class DiceMathDivide < DiceMath
def initialize(m)
self.mod = "/"
super
end
def perform_arithmetic
self.answer = self.d1 / self.d2
end
end
def ask(d)
d.to_s
u_ans = gets.chomp.to_i
return u_ans
end
def user_wants_to_exit?(ans)
return ans == 0 || ans.nil?
end
# dice = DiceMath.for("subtraction")
# dice = DiceMath.for("multiplication",10)
# Addition is default.
dice = DiceMath.for
loop do
user_answer = ask(dice)
if dice.is_answer_correct?(user_answer)
puts "Correct!"
dice.roll
elsif user_wants_to_exit?(user_answer)
puts "Exiting."
break
else
puts "Incorrect."
end
end
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment