开发者

trying to count the number of times something comes up on a dice. ruby code

开发者 https://www.devze.com 2023-04-09 01:07 出处:网络
This is my code for a dice that shows a direction. It shows either north, south, east or west when rolled.

This is my code for a dice that shows a direction. It shows either north, south, east or west when rolled. I'm trying to figure out a way to count how many times each one of these appears anytime I roll the dice.

Any one any ideas?

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


Your class should look something like this:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号