试图计算骰子出现的次数。红宝石代码

时间:2011-09-29 09:46:35

标签: ruby if-statement dice

这是我的骰子代码,显示方向。 滚动时显示北,南,东或西。 我试图找出一种方法来计算每次掷骰子时每次出现的次数。

任何一个想法?

class Dice

  #def initialize()
  #end 


  def roll 
    @dice = Array['north','south','east','west'] # makes dice with four sides (directions)
    @dice_index = 0 + rand(4)                    # gets the random index of the array
    puts @dice[@dice_index]                      # prints random direction like a dice
  end

  def stats
    puts @dice_index
    north_count =0;
    south_count =0;
    east_count=0;
    west_count=0;
  end
end


game_dice = Dice.new
game_dice.roll
game_dice.stats

1 个答案:

答案 0 :(得分:1)

你的课应该是这样的:

class Dice
  SIDES = [:north, :south, :east, :west]
  def initialize
    @rolls = Hash.new(0)
    @num_of_sides = SIDES.count
  end
  def roll
    roll = SIDES[rand(@num_of_sides)]
    @rolls[roll] += 1
    roll
  end
  def stats
    puts @rolls.inspect
  end
end