[英]How can I use the value from my timer to make a scoring system in my game? - Java
我想要實現的是在我的計時器中檢索時間,以便我可以計算用戶在我的游戲中獲得的分數,但是我是 Java 的新手並且似乎無法使其工作。 我嘗試了各種不同的解決方案,但認為它不適合我的問題。 我真的不知道如何檢索計時器中的時間作為要使用的值,所以我做了以下操作:
public class TimerPanel extends JPanel{
private Timer timer;
private Timer timer2;
private long startTime = -1;
public long duration = 30000;
public boolean paused = false;
public long remainingDuration = 0;
long clockTime;
private JLabel label;
public void stopTimer() {
this.timer.stop();
}
public void startTimer() {
if (!timer.isRunning()) {
if(paused) {
duration = remainingDuration;
paused = false;
}
else {
duration = 30000;
}
startTime = -1;
timer.start();
}
}
public void pauseTimer() {
paused = true;
this.timer.stop();
}
public int getCurrentTime() {
return (int)TimeUnit.MILLISECONDS.toSeconds(remainingDuration);
}
public TimerPanel() {
setLayout(new GridBagLayout());
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (startTime < 0) {
startTime = System.currentTimeMillis();
}
long now = System.currentTimeMillis();
clockTime = now - startTime;
if (clockTime >= duration) {
clockTime = duration;
timer.stop();
duration = 30000;
}
SimpleDateFormat df = new SimpleDateFormat("mm:ss");
remainingDuration = duration - clockTime;
label.setText(df.format(duration - clockTime));
//Below is my attempt at making a score out of the time left
long timeused = remainingDuration - duration;
long equation = timeused / 30;
long equation2 = equation / 2;
long equation3 = 1 - equation2;
long equation4 = equation3 * 1000;
}
});
timer.setInitialDelay(0);
label = new JLabel("00:30");
label.setFont(new Font("Dialog", Font.BOLD, 13));
add(label);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
}
在底部,我嘗試計算點數,但我什至不知道它是否有效,因為這個計時器面板 class 與我的 JFrame 位於不同的 class,所以當我嘗試更改 JLabel 中的文本時,它位於我的 JFrame ,它無法識別 equation4 變量,因為它位於不同的 class 中。這可能非常令人困惑,因此我將嘗試消除任何疑慮。 謝謝!
你能改變這個方法嗎? 我也不熟悉您正在使用的定時器 class,所以我不知道 ActionListener 實際上在監聽什么。
public TimerPanel() {
setLayout(new GridBagLayout());
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (startTime < 0) {
startTime = System.currentTimeMillis();
}
long now = System.currentTimeMillis();
clockTime = now - startTime;
if (clockTime >= duration) {
clockTime = duration;
timer.stop();
duration = 30000;
}
SimpleDateFormat df = new SimpleDateFormat("mm:ss");
remainingDuration = duration - clockTime;
//Below is my attempt at making a score out of the time left
long timeused = remainingDuration - duration;
long equation = timeused / 30;
long equation2 = equation / 2;
long equation3 = 1 - equation2;
long equation4 = equation3 * 1000;
//difference is below
label.setText(""+equation4);
}
});
timer.setInitialDelay(0);
label = new JLabel("00:30");
label.setFont(new Font("Dialog", Font.BOLD, 13));
add(label);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.