2013-10-06 77 views
0

我创建了一个简单的游戏,要求您在一定的转数内(例如10)猜测一个数字。但是,这使得很容易被击败。我需要帮助的是如何跟踪游戏进行的时间。创建一个定时应用程序

这是我至今想起来的(减去游戏逻辑),但它似乎并没有被你不使用开始时间被工作

Random ranNum = new Random(); 
double input; // The input 
long startTime; // The time the game started 
long curTime; // The time the game ended 

    double randNum = ranNum.nextInt(100); 

while (curTime > 1000){ 
      curTime = System.currentTimeMillis(); 
      input = TextIO.getlnDouble(); 

      if (input = Math.abs(randNum)){ 
       System.out.println("You got the correct answer"); 

      } // End if statement 

      else { 
       System.out.println("You did not have the correct answer"); 
       System.out.println("The number was" + randNum + "."); 

      } // End else statement 

     } // End while statement 
+0

你在哪里初始化curTime? –

回答

0

你必须得到当前时间戳的循环开始前:

startTime = System.currentTimeMillis(); //get timestamp 

//the condition is waaaay off, basically equals to while (true) - more on that later 
while (curTime > 1000){ 
     input = TextIO.getlnDouble(); 

     if (input = Math.abs(randNum)){ 
      System.out.println("You got the correct answer"); 

     } // End if statement 

     else { 
      System.out.println("You did not have the correct answer"); 
      System.out.println("The number was" + randNum + "."); 

     } // End else statement 

    } // End while statement 

curTime = System.currentTimeMillis(); //get timestamp again 

System.out.println("Game took " + ((curTime-startTime)/1000) + " seconds"); 

System类的文档:

公共静态长的currentTimeMillis()

返回当前时间以毫秒为单位。请注意,尽管返回值的时间单位是毫秒,但其值的粒度取决于底层操作系统,可能会更大。例如,许多操作系统以几十毫秒为单位来测量时间。

有关讨论“计算机时间”与协调通用时间(UTC)之间可能出现的细微差异的类别的描述,请参阅日期。

返回:

的差,以毫秒为单位,当前时间和午夜,1970年1月1日,UTC之间。

因此,要获得比赛的时间,你必须采取两个时间戳,并从前者usbtract后者...

此外,while循环条件的路要走......这

while (curTime > 1000){ 

基本上true ......它只会是在1970年1月,第一次假,从00:00:00到00:00:01

你也许有这样的事情:

while(curTime-startTime > 10000) { //remember, value is ms! 
    //...loop content 
    curTime = System.currentTimeInMillis(); //update timestamp 
} 

但它不会让游戏在10秒后结束。如果你想限制游戏可以持续多久,这是一种不同类型的cookie - 你必须有另一个线程才能完成这个...

0

long startTime = System.currentTimeMillis(); 

currTime = System.currentTimeMillis() - startTime 

现在currTime会有毫秒的时间差。

相关问题