2016-05-12 3 views
1

したがって、数字のゲームから上位5つのスコアで構成されるこのスコアボードを持っています。それとそうルビーでトップ5のスコアボードを作成しようとすると混乱して失われる

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

を私は基本的に私は、ファイルに入れます文字列にそれをシリアル化する必要があります: 事は、私はそうのような別の配列の内だdouble配列にスコアを保持しているということです読み書きする。
私が抱えていた問題は、値の追加とソートを確認することに関連しています。
私はルビーに慣れていないので、役に立つ方法があれば、ルビーでこれを書く方法はわかりません。
私は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は保存しないので、最も簡単な方法はファイル全体を2D配列にロードし、新しいタプルを追加し、配列をソートして最後のタプルを削除します。

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 
関連する問題