Created
November 14, 2014 13:14
-
-
Save b1nary/32ba83b643f535cca12d to your computer and use it in GitHub Desktop.
Ruby dice lib => https://www.reddit.com/r/ProgrammingPrompts/comments/2luobv/game_component_die_and_dicebag/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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