迷茫和迷失试图在红宝石中取得前5名的记分牌

时间:2016-05-12 22:39:46

标签: arrays ruby file-io

所以我有这个记分板,它将由一个数字游戏的前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 个答案:

答案 0 :(得分:1)

由于你只保留前5,而不是爆炸你的记忆的前n,最简单的方法是将整个文件加载到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