我正在编写一个简单的轮盘游戏,用户可以在其中添加玩家、下注和旋转轮盘(表示为JLabel,它更新文本以显示轮盘号码(
public void spin(int wheelSize, int initialDelay, int finalDelay,
int delayIncrement, WheelCallback callback) {
Random rand = new Random();
int curNo = rand.nextInt(wheelSize) + 1;
int finalNo = 0;
int count = 10;
assert (curNo >= 1);
Listener myListener = new Listener(callback, this, curNo);
myListener.start(finalDelay);
类别Listener
:
package model;
import java.awt.event.*;
import javax.swing.*;
import model.interfaces.*;
import model.GameEngineImpl;
import model.WheelCallbackImpl;
public class Listener implements ActionListener {
WheelCallbackImpl callback;
GameEngineImpl engine;
Timer timer;
int delay, curNo, finalNo;
int count = 10;
public Listener(WheelCallbackImpl wheelcall, GameEngineImpl newEngine, int number) {
callback = wheelcall;
engine = newEngine;
curNo = number;
}
public void actionPerformed(ActionEvent e) {
if (count == 0) {
engine.calculateResult(finalNo);
callback.result(finalNo, engine);
callback.playback();
timer.stop();
} else {
callback.nextNumber(curNo, engine);
curNo++;
finalNo = curNo;
count--;
}
}
public void start(int delay) {
timer = new Timer(delay, this);
timer.start();
}
}
Listener
与助手类WheelCallbackImpl
通信,后者处理用户反馈并与我的View:通信
public class WheelCallbackImpl implements WheelCallback {
Wheel wcWheel = Wheel.myWheel;
public void nextNumber(int nextNumber, GameEngine engine) {
String strNo = Integer.toString(nextNumber);
assert (nextNumber >= 1);
System.out.println(nextNumber);
wcWheel.setCounter(strNo);
}
public void result(int result, GameEngine engine) {
System.out.println("callback.Result is running!");
Collection<Player> players = engine.getAllPlayers();
Player[] playerList = players.toArray(new Player[0]);
System.out.println("Player list length is " + playerList.length);
for (int i=0; i < playerList.length; i++) {
if (playerList[i].getNumberPick() == result)
wcWheel.storeResults(playerList[i].getPlayerName(), playerList[i].getPoints(), " won!", i);
else
wcWheel.storeResults(playerList[i].getPlayerName(), playerList[i].getPoints(), " lost!", i);
}
System.out.println("callback.result finished!");
}
/*
Called by the controller - calls the GUI display/replay prompts
*/
public void playback() {
System.out.println("Playback called!");
int n = 0;
while (n == 0)
wcWheel.playAgain();
}
}
我的Timer
能够成功地更新我的JLabel,但是当它执行if (count == 0)
块时,它似乎只调用前两个方法,剩下的输出是:
6
7
8
9
10
11
12
13
14
15
Calculate result called!
callback.Result is running!
Player list length is 1
callback.result finished!
知道这里发生了什么吗?
如果一切都如您所发布的,那么在我看来这是一个不可能的结果:
callback.result(finalNo, engine);
callback.playback();
您说调用了callback.result()
,其最后一条语句是在控制台上可见的System.out.println()
,但是callback.playback();
的第一条System.out.println()
语句在控制台上不可见。
要么您修改了代码但没有重新编译,要么callback.playback()
的结果是可见的,但您需要滚动控制台窗口才能看到它。