Skip to content

Instantly share code, notes, and snippets.

@kaseybon
Forked from cromwellryan/greed.rb
Last active August 29, 2015 14:14
Show Gist options
  • Save kaseybon/28d5f6239d6ceb4eb595 to your computer and use it in GitHub Desktop.
Save kaseybon/28d5f6239d6ceb4eb595 to your computer and use it in GitHub Desktop.
# My approach for the greed game was to take the values in a roll and sort them into seperate arrays. For example all the ones would be in an array, twos in an array, etc.. To keep these neat and tidy I will organize them into a hash.
# I could create a class called dice with two methods, roll and score:
#The roll method will randomly generate the numbers for the roll (I don't think this project included that but I'll add it anyways) and them store them into their arrays of similar numbers.
# The score method would be responsible for taking the sorted arrays and calculating the score then return the score.
class Dice
def initialize
@roll = {1 => [], 2 => [], 3 => [], 4 => [], 5 => [], 6 => []}
@points = 0
end
def roll(count)
dice = []
# Generate Values
dice = (1..count).map { |_| Random.rand(1..6) }
dice.each do |die|
@roll[die] << die
end
# Output roll to user
puts dice.join(", ")
end
def score
# Split the hash
remain = @roll.reject{ |k| k == 1 || k == 5 }
special = @roll.reject{ |k| k == 2 || k == 3 || k == 4 || k == 6 }
# Handle the specials
special.each do |key, array|
if key == 1
calculate_specials(key, array, 1000, 100)
elsif key == 5
calculate_specials(key, array, 500, 50)
end
end
# Handle the remaining
remain.each do |key, array|
@points = @points + (100 * key) if array.length >= 3
end
puts "#{@points}"
end
def calculate_specials(value, nums = [], high_score, low_score)
if nums.length >= 4
@points = @points + high_score
leftovers = nums.length - 3
@points = @points + (low_score * leftovers)
elsif nums.length == 3
@points = @points + high_score
else
@points = @points + (low_score * nums.length)
end
@points
end
end
# Just testing to make sure everything works...
test = Dice.new
testb = Dice.new
test.roll(5)
testb.roll(5)
test.score
testb.score
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment