Old high school files. Lessson notes/codes/projects etc.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hsf/prog2/coffeemachine/coffeemachine.rb

95 lines
1.7 KiB

3 years ago
#!/usr/bin/ruby
3 years ago
3 years ago
class CoffeMachine
3 years ago
attr_accessor :location, :change, :coffees, :price, :number_served
3 years ago
def initialize(location, change, coffees, price)
@location = location
@change = change
@coffees = coffees
@price = price
@number_served = 0
end
def prompt_for_payment()
if( not self.empty? ) then
puts("Welcome to the #{@location} Coffee Machine.")
puts("Please pay #{@price} SEK for one coffee.")
puts("Total amount served: #{@number_served}")
print("Insert coins: ")
3 years ago
await_payment()
3 years ago
else
puts("Inget kaffe kvar :(")
end
end
def await_payment()
inp = gets().chomp()
coin_types = inp.split(",")
coin_hash = Hash.new(0)
coin_types.each do |t|
x = t.split(":")
coin_hash[x[0].to_i] = x[1].to_i
end
3 years ago
3 years ago
@change = @change.merge(coin_hash)
3 years ago
verify_payment(coin_hash)
3 years ago
end
private def verify_payment(coin_hash)
sum = 0
coin_hash.each do |key, value|
sum += value*key
end
3 years ago
delta = sum - @price
3 years ago
3 years ago
if( delta > 0 ) then
dispense_change(delta)
dispense_coffe()
elsif( delta < 0 ) then
puts("Not enough money")
else
dispense_coffe()
end
3 years ago
end
3 years ago
private def calculate_change(delta)
coin_return = {}
@change.each do |type, count|
puts("adhfio: #{type} #{count}")
amount = delta/type
coin_return[type] = amount
@change[type] -= amount
delta %= type
next
3 years ago
end
3 years ago
return coin_return
3 years ago
end
3 years ago
private def dispense_change(delta)
coin_return = calculate_change(delta)
puts("Här är din change:")
puts("-> #{coin_return}")
3 years ago
end
private def dispense_coffe()
puts("Här är ditt kaffe")
@number_served += 1
@coffees -= 1
end
def empty?
@coffees <= 0
end
end
3 years ago
x = CoffeMachine.new("hej", {10=>2, 1=>100}, 5, 15)
3 years ago
x.prompt_for_payment