2014-09-27 94 views
0

对于我的CS类,我必须使用多线程编写HiLo游戏。我是多线程的新手,不确定如何最好地实现它。下面的程序工作,但我想知道是否有更好的方法来做到这一点。当它运行时,用户将输入一个int值,这是他们必须猜测正确数字的时间量。如果计时器耗尽,游戏将结束。我不应该使用Timer对象,而是使用System.currentTimeMillis()。Java多线程HiLo游戏

import java.util.Random; 
import java.util.Scanner; 

class Game implements Runnable { 
    private static long time; 
    private long timer; 
    private static long gameTime; 

    public Game(int n){ 
     gameTime=n; 
    } 

    public void run() { 
     time=System.currentTimeMillis(); 
     while(true){ 
      timer=(System.currentTimeMillis()-time)/1000; 
      if(timer>=gameTime){ 
       System.out.println("Oops! Time is up - try again."); 
       break; 
      } 
     } 
    } 
} 

public class Hilo { 

    public static void main(String[] args) { 
     if (args.length!=1){ 
      System.err.println("Must enter time"); 
     } 
     Random rand = new Random(); 
     int max=100; 
     int min=1; 
     int number=rand.nextInt((max-min)+1)+min; 
     int gameTime=Integer.parseInt(args[0]); 
     System.out.println("Welcome to HiLo!"); 
     System.out.println("You have "+gameTime+" seconds to guess a number between 1 and 100."); 
     Thread clock1 = new Thread(new Game(gameTime)); 
     clock1.start(); 

     while(clock1.isAlive()==true){ 
      System.out.println(">"); 
      Scanner sc = new Scanner(System.in); 
      int input = sc.nextInt(); 

      if(clock1.isAlive()==true&&input==number){ 
       System.out.println("You Win!"); 
       break; 
      }else if(clock1.isAlive()==true&&input<number){ 
       System.out.println("Higher!"); 
      }else if(clock1.isAlive()==true&&input>number){ 
       System.out.println("Lower!"); 
      } 
     } 
    } 
} 
+0

这更适合http://codereview.stackexchange.com。这就是说:'booleanExpression == true'是丑陋的。只需使用'booleanExpression'。 'time'和'gameTime'变量不应该是静态的。在操作符周围添加空格,在括号之前等代码可读:'if(clock1.isAlive()&& input == number){' – 2014-09-27 17:03:04

回答

0

您可以使用睡眠T秒的线程,然后退出调用System.exit()。