Ruby Dice

G'day,

Playing around with ruby I decided to re-create the Petals Around the Rose game.

 I have completed this however to protect the logic behind the game I'm only going to post the code that create the dice here.

 I'm new to Ruby and OO so please if you have any ideas let me know them.

Here is a screenshot of the script in action:

And here is the code:

 

#!/usr/local/bin/ruby

row1 = row2 = row3 = ""

edge = "+------+"


top = {

  "1" => "|      |",

  "2" => "|    []|",

  "3" => "|    []|",

  "4" => "|[]  []|",

  "5" => "|[]  []|",

  "6" => "|[][][]|",

}


middle = {

  "1" => "|  []  |",

  "2" => "|      |",

  "3" => "|  []  |",

  "4" => "|      |",

  "5" => "|  []  |",

  "6" => "|[][][]|",

}


bottom = {

  "1" => "|      |",

  "2" => "|[]    |",

  "3" => "|[]    |",

  "4" => "|[]  []|",

  "5" => "|[]  []|",

  "6" => "|[][][]|",

}


$set = Array.new


def roll(times)

  count = 0

  while count < times

    temp = rand(7)

    $set.push(temp.to_s) if temp != 0

    count += 1 if temp != 0

  end

end


times = 1


while times != 0

  puts "Please enter the number of times to roll."

  puts "Type \"0\" and press enter to quit."

  times = gets.chomp.to_i


  roll(times)

  rolled = $set.length

  $set.each do |index|

    row1 += top.fetch(index) + " "

    row2 += middle.fetch(index) + " "

    row3 += bottom.fetch(index) + " "

  end


  rolled.times{ print edge + " " }

  print "\n"

  puts row1 + "\n" + row2 + "\n" + row3 + "\n"

  rolled.times{ print edge + " " }

  print "\n"


  $set.clear

  row1 = row2 = row3 = ""

end

I'm aware of the redundancy in the top, middle and bottom arrays, just made it easier to understand the layout of the die...

Regards, Bawdo

tags: Ruby

Mon 06 Nov 2006, 12:00

1 comments

Thought it was fun playing around with. Here's the code to render the dice i ended up with. Dice = Module.new class << Dice def roll; rand(6)+1 end end module DiceOutput Top, Mdl, Btm = {}, {}, {} Top[1]="| |" Mdl[1]="| [] |" Btm[1]="| |" Top[2]="| [] |" Mdl[2]="| |" Btm[2]="| [] |" Top[3]="| [] |" Mdl[3]="| [] |" Btm[3]="| [] |" Top[4]="| [] [] |" Mdl[4]="| |" Btm[4]="| [] [] |" Top[5]="| [] [] |" Mdl[5]="| [] |" Btm[5]="| [] [] |" Top[6]="| [] [] |" Mdl[6]="| [] [] |" Btm[6]="| [] [] |" Edge = "+--------+" end class Object def puts_as_dice *numbers edge, top, middle, bottom = '', '', '', '' numbers.each do |num| edge << DiceOutput::Edge + " " top << DiceOutput::Top[num] + " " middle << DiceOutput::Mdl[num] + " " bottom << DiceOutput::Btm[num] + " " end puts edge, top, middle, bottom, edge end end puts_as_dice 1, 2, 3 puts_as_dice Dice.roll, Dice.roll, Dice.roll

Boo

Back