2016-05-12 14 views
1

因此,我有這個評分板將由數字遊戲的前5名得分組成。 的事情是,我要保持得分在雙陣列是另一個數組,像這樣的內部:讓困惑和失落試圖在紅寶石上打出排名前5的記分牌

@scoreList= [[1000,"--"],[1000,"--"],[1000,"--"],[1000,"--"],[1000,"--"]] 

所以與我基本上已經把它序列化到,我會放到一個文件中的字符串讀取和寫入。
我一直在遇到的麻煩與檢查添加和排序值有關。
我不習慣紅寶石,所以我不知道如何去寫這個紅寶石,如果有有用的方法等。
我在一個叫做HiScore的課程中擁有所有這些:

class HiScore 
=begin 
    #initialize: determines whether or not the score chart 
    #file exists and uses the read_file method if it does or 
    #uses the build_new method if it doesn't 
=end 
    def initialize 
     if File.exists("hiscore.txt") 
      read_file 
     else 
      build_new 
     end 
    end 

    #show: displays the high score chart ordered lowest to highest 
    def show 

    end 

    #build_new: creates an empty high score chart 
    def build_new 
     @scoreList= [[1000,"--"],[1000,"--"],[1000,"--"],[1000,"--"],[1000,"--"]] 
    end 

=begin 
    #read_file: reads the text file and puts it into a string 
    #reads the file into an instance variable string, 
    #and run the process_data method. 
    #Ex Output: 10,player1,15,player2,20,player3,25,player4,30,player5 
=end 
    def read_file("hiscore.txt") 
     File.open("hiscore.txt").readlines.each do |line| 
      @hiInstance = line.chomp.split(",") 
     end 
     File.close 
     process_data(@hiInstance) 
    end 

=begin 
    #process_data: processes the data from the text the file after 
    #it is read and puts it into a two-dimensional array 
    #should first split the data read from the file 
    #into an array using the 'split' method. 
    #EX output: [[10, 'player1'], [15, 'player2']...[30, 'player5']] 
=end 
    def process_data(instance) 
     instance = @hiInstance 
     @scoreList = instance.each_slice(2).to_a 
    end 

=begin 
    #check: checks to see if the player's score is high enough to be 
    #a high score and if so, where it would go in the list, 
    #then calls the add_name method. 
=end 
    def check(score) 
    end 

    #add_name: adds a name to the high score array 
    def add_name(string) 
    end 


    #write_file: writes the score data to the file 
    def write_file(@scoreList) 
     @scoreList.sort_by{|a| a[0]} #<- fix 
     File.open("hiscore.txt", "a+") 
     File.close 
    end 

end 

這將全部在比賽勝出並且數字被猜測後從實例調用。
*編輯:對於現有的文件檢查不工作了..

回答

1

既然你只保留前5名,而不是爆炸內存前n,最簡單的方法是將整個文件加載到一個二維數組,在其中添加一個新元組,對數組進行排序並刪除最後一個元組。

class HiScore 
    attr_reader :hiscore 

    def initialize 
    @hiscore = if File.exist?('hiscore.txt') 
     File.open('hiscore.txt'){|f| f.lines.map{|l| l.chomp!.split(',')}} 
    else 
     Array.new(5) {[1000, '--']} 
    end 
    end 

    def update(score, name) 
    @hiscore.push([score, name]).sort!{|s1, s2| s2[0] <=> s1[0]}.pop 
    end 

    def persist 
    File.open('hiscore.txt', 'w') do |f| 
     @hiscore.each {|tuple| f.puts tuple.join(',')} 
    end 
    end 
end