2016-04-26 97 views
0

我是Java編程新手,剛剛做出簡單的猜數字遊戲,現在我需要製作GUI。我只是從一些簡單的showMessage和其他的東西開始,但我有一個問題。我怎樣才能定義我的人類玩家的結果,它會接受它,遊戲會繼續玩。遊戲介於人與機器人之間。問題在我輸入我的號碼答案時開始,遊戲剛剛停止。我現在知道代碼已經破解,但是你能給我一些建議或提示怎麼辦?由於Java,Swing!接受結果並繼續遊戲

**public class Human extends Player {** 
private Player guesser; 
private final PrintStream printer; 
private final Scanner scanner; 
private final String name; 

Human(String name, PrintStream printer, Scanner scanner) { 
    this.name = name; 
    this.printer = printer; 
    this.scanner = scanner; 
} 

@Override 
public String getName() { 
    return name; 
} 

@Override 
public int guess(int n) { 
JOptionPane.showInputDialog(String.format ("What do you think about %d?")); 
    char result = scanner.nextLine().trim().charAt(0); 
    return result == '=' ? 0 : result == '<' ? -1 : 1; 
} 

@Override 
public int play() { 
    JOptionPane.showMessageDialog(null, String.format("%s wants your guess:", guesser.getName()), null, JOptionPane.PLAIN_MESSAGE); 
    int n = Integer.parseInt(scanner.nextLine().trim()); 
    return guesser.guess(n); 
} 

@Override 
public void setGuesser(Player player) { 
    this.guesser = player; 
} 

}

**public class Robot extends Player {** 


private static final Random RANDOM = new Random(); 

    private final String name; 
    private Player guesser; 
    private final PrintStream printer; 

    private int min = 0; 
    private int max = Integer.MAX_VALUE; 
    private int last = 1 + RANDOM.nextInt(1); 


    private final int guessedNumber; 

    public Robot(String name, PrintStream printer, int min, int max) { 
     this.name = name; 
     this.printer = printer; 
     this.guessedNumber = min + RANDOM.nextInt(max - min); 
    } 


    @Override 
    public String getName() { 
     return name; 
    } 


    @Override 
    public int guess(int n) { 
     int result = Integer.compare(guessedNumber, n); 
     printer.printf("%s says that %d is %s.%n", getName(), n, 
       result < 0 ? "too much" : result > 0 ? "not enough" : "just fine" 
       ); 
     return result; 
    } 

    @Override 
    public int play() { 
     JOptionPane.showMessageDialog(null,"Robot thinks that Human guessed " + last,"aaa", JOptionPane.PLAIN_MESSAGE); 
     int guessResult = guesser.guess(last); 
     if (guessResult != 0) { 
      if (max - min <= 0) { 
       throw new IllegalStateException("YOU BLOODY CHEATER! SCREW YOU."); 
      } 
      if (guessResult == -1) { 
       max = last - 1; 
      } else { 
       min = last + 1; 
      } 
     } 
     last = min + (max - min)/2; 
     return guessResult; 
    } 

    @Override 
    public void setGuesser(Player player) { 
     this.guesser = player; 
    } 
} 
+1

'人類(字符串名稱,PrintStream打印機,掃描儀掃描儀){'看起來這個遊戲需要大幅改變才能成爲基於GUI的應用程序。 –

+1

對於[示例](http://stackoverflow.com/a/3072979/230513)。 – trashgod

回答

0

更改

PrintStream.print方法

到JOptionPane.showMessageDialog,甚至更好的放像一個文本框或標籤GUI元素和改變文本。