如何在游戏中每一轮只写一次文件?

时间:2017-05-04 18:29:06

标签: java file

背景

我想写一个包含游戏中高分的文件。

问题

每次tick()被调用时,程序都会使用分数写入文件,但是,我只希望每次游戏结束时都写一次分数。

例如,如果我的分数为30,如果我将窗口打开30

,则会打印5ms 5次

如何让我的程序只编写一次而不是每次100ms

代码

游戏循环:

@Override
public void run()
{
    while (isRunning)
    {
        tick();
        //render(); Not important in terms of this question

        try
        {
            Thread.currentThread();
            Thread.sleep(100);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    stop();
}

tick()100ms次调用一次。

private void tick() 
{
     //inGame is just a global variable to determine if still in game
     //move() is a method used to move the player object.
     if (inGame) move();
     else Util.writeScore("scores", 10); 
     //10 is just an example, score would be held in a variable in production.
}

private void writeScore(String fileName, int score)
{
    if (score == 0) 
        return;
    else 
    {
        try (FileWriter fw = new FileWriter(fileName, true);
                BufferedWriter bw = new BufferedWriter(fw);
                PrintWriter out = new PrintWriter(bw))
        {
            out.println(score);
            out.close();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你需要两个标志 - 像这样:

  // Globals
  int inGame=1; // 1 when in game 0 when not
  int scoreDone=0;  // 1 when score written 0 when not.

private void tick() 
{
   //inGame is just a global variable to determine if still in game
   //move() is a method used to move the player object.
   if (inGame == 1) 
     move();
   if ((inGame == 0) && (scoreDone == 0))
   {
     Util.writeScore("scores", 10);
     scoreDone = 1;
   }
}