Skip to content

Instantly share code, notes, and snippets.

@b1nary
Created November 14, 2014 13:14
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 b1nary/32ba83b643f535cca12d to your computer and use it in GitHub Desktop.
Save b1nary/32ba83b643f535cca12d to your computer and use it in GitHub Desktop.
module DiceLib
class Dice
attr_accessor :hold, :current, :last
def initialize sides = 6
@dice = (0 .. (sides-1)).to_a
@hold = false
@current = @last = rand(@dice.length)
end
def roll
@last = @current
@current = rand(@dice.length) if !@hold
@current
end
end
class DiceBag
attr_accessor :dices
def initialize dices = nil; @dices = dices || []; end
def add dice; @dices << dice; end
def delete dice; @dices.delete(dice); end
def hold_all; @dices.each { |dice| dice.hold = true }; end
def release_all; @dices.each { |dice| dice.hold = false }; end
def roll_all
@dices.each { |dice| dice.roll }
@dices.collect { |dice| dice.current }
end
end
module Display
@dice = "+----+\n"
@dice += "| XX |\n"
@dice += "+----+\n"
def self.render val
if val.is_a? Integer
return @dice.gsub("XX", "%02d" % val)
elsif val.is_a? Array
out = ""
val.each do |value|
out += @dice.dup.gsub("XX", "%02d" % value)
end
out
end
end
end
end
dice = DiceLib::Dice.new
puts dice.roll # number between 0-5
dice2 = DiceLib::Dice.new 8
dice3 = DiceLib::Dice.new 22
dicebag = DiceLib::DiceBag.new [dice, dice2]
dicebag.add dice3
dicebag.delete dice
p dicebag.roll_all
dicebag.hold_all
p dicebag.roll_all
dicebag.release_all
p dicebag.roll_all
puts "Graphical dicebag:"
puts DiceLib::Display.render dicebag.roll_all
puts "Graphical single:"
puts DiceLib::Display.render dice.current
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment