
require 'yaml'

class SaveLoadScores
  #to output class variables use accessors
  attr_accessor :scores

  #constructor for the class
  def initialize
    #declare variable currentYear as a class variable (hence @ sign)
    @scores = []
   
  end

    
def bubble_sort(list)
  return list if list.size <= 1 # already sorted

  loop do
    swapped = false
    0.upto(list.size-2) do |i|
      if list[i][:score] < list[i+1][:score]
        list[i][:score], list[i+1][:score] = list[i+1][:score], list[i][:score] # swap values
        list[i][:name], list[i+1][:name] = list[i+1][:name], list[i][:name]
        swapped = true
      end
    end
    break unless swapped
  end

  list
end

def savefirstrun(score,name)
   t = SaveLoadScores.new
   t.scores << { :score =>score, :name => name}
   
   file = File.open('scores.txt','w')
   file.write(t.to_yaml)
   file.close
end
  
  def save(score,name)
    t = SaveLoadScores.new
    file = File.open('scores.txt','r')
   
    t = YAML::load(file)
    
    
    t.scores << { :score =>score, :name => name}
    t.scores = bubble_sort(t.scores)
    
    file = File.open('scores.txt','w')
    #serialize to a yaml file
    file.write(t.to_yaml)
    file.close
    
  end
  
  def load
    t = SaveLoadScores.new
    file = File.open('scores.txt','r')
   
    t = YAML::load(file)
    t.scores 
   
  end

  
  

end






















