2014-09-27 83 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()。