I'm trying to make a class called timer. The timer class is supposed to be called upon when my character enters the enemy's area. And the timer class is supposed to remove the characters health by 10-health points every 5 seconds. Ive tried multiple different timers but i cant seem to get any of them right. When i tried it removed health but it didn't do it only once, it kept repeating it until the health bar was out of the screen. here is my code:
class Timer {
g = new gubbe();
gubbe g;
Timer timer = new Timer(3000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
g.RemoveHealth();
}
});
timer.setRepeats(false);
timer.start();
}
That is what I've come up with so far.
If any more code is needed just ask.
Here's a class which you can use to time your events:
class Delay {
protected int limit;
public Delay() {limit = millis();}
public Delay (int l) {
limit = millis() + l;
}
public boolean expired () {
if (millis() > limit) { return true; }
return false;
}
}
To check on something every 5 seconds, you would have to initialize it like this:
Delay _delay;
void setup() {
_delay = new Delay(5000);
}
void draw() {
if (_delay.expired()) {
//do something
_delay = new Delay(5000);
}
}
The 5000 is in milliseconds, so it means 5 seconds. If you want to check for a 1 second delay, it would be 1000 instead. We re-initialize it when the delay is finished so it triggers again in 5 more seconds.
Have fun!
Related
I'm trying to program a game where I output the time (in milliseconds) the player has been alive. I thought I can just use a timer and gets it value pretty easily.
public class InvaderPanel extends JPanel implements KeyListener,ActionListener {
private int timealive; //in ms, max value 2147483647 --->3.5 weeks
private Timer timer=new Timer(30,this); //I think it(30) should be 1 right ?
/**
* Create the panel.
*/
public InvaderPanel() {
addKeyListener(this);
setFocusable(true);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if(playerdead){
timer.stop;
timealive=timer.value; // <--- That's what I'm looking for.
}
}
}
But here lies my problem: timer.value doesn't exist, so how do I get the value of my timer in milliseconds ?
Here is my solution for you. You need to create timer which exactly ticks 1 time per second. And each tick when player is alive increase the value of timealive variable. I have another solution for you, but I think this should be enough.
public class InvaderPanel extends JPanel implements KeyListener,ActionListener {
private int timealive; //in ms, max value 2147483647 --->3.5 weeks
private Timer timer=new Timer(1000,this); // 1000ms = 1 second, but you
// can also set it to 30ms.
/**
* Create the panel.
*/
public InvaderPanel() {
addKeyListener(this);
setFocusable(true);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if(playerdead){
timer.stop();
// here we can use timealive value
} else {
// timealive++; if you want to get the value in seconds
// in this case the timer delay must be 1000ms
timealive += timer.getDelay(); // if you want to get the value in milliseconds
}
}
public void counter(){
new CountDownTimer(20000, 1000){
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(Integer.parseInt(String.valueOf(millisUntilFinished/1000)));
}
#Override
public void onFinish() {
gameOver();
}
}.start();
}
I am trying to write a game in which player gets 20 seconds to play. A timer starts at start of the game and if timer reaches 0, player looses. If player presses button with correct answer, i want time to increase by 3 seconds. But I don't know how to add time in the count down timer whenever player hits correct answer. I tried everything but couldn't find a way. If there is another method to achieve this, please tell me. Thank you
Change your code like this:
private int globalCount = 0; // Initialize this in Global scope of class.
public void counter(int timeCount){
globalCount = 0;
new CountDownTimer(timeCount, 1000){
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(Integer.parseInt(String.valueOf(millisUntilFinished/1000)));
}
#Override
public void onFinish() {
if (globalCount == 0) {
gameOver();
} else {
conter(globalCount);
}
}
}.start();
}
One last thing you have to do is:
globalCount += 3000;
every time when user pressed the right answer button. Hope this will help!
In Android normal countdown timer is used for decrease order. so you can use logic using normal if-else condition.
if (sec==59){
sec = 0;
min = min+1;
String text = String.format(Locale.getDefault(),"%02d min: %02d sec",min,sec);
editText.setText(text);
}else {
sec = sec+1;
String text = String.format(Locale.getDefault(),"%02d min: %02d sec",min,sec);
editText.setText(text);
}
}
You can get complete code using this blog
I want to use the method javax.swing.Timer to create a timer that will start at 3:00, then go down to 0:00. I have no idea how to use this method and how to proceed. From now on, I have this code, but I have no idea if it is good. One thing sure is that it doesn't work.
private javax.swing.Timer timer = new javax.swing.Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
int minute = 3;
int seconde = 60;
do {
lblTimer.setText(Integer.toString(seconde));
seconde--;
} while (seconde != 0);
}
});
In this example, a TimerButton responds after the delay passed to the constructor, e.g.
new TimerButton("Back in three minutes", 3 * 60 * 1000));
Your StopListener would take the desired action when the Timer expires, e.g.
private class StopListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
// further actions here
}
}
See How to Use Swing Timers for additional details.
I have a JTextField that is cleared if it has invalid content. I would like the background to flash red one or two times to indicate to the user that this has happened. I have tried:
field.setBackground(Color.RED);
field.setBackground(Color.WHITE);
But it is red for such a brief time that it cannot possibly be seen. Any tips?
The correct solution, almost arrive at by just eric, is to use a Swing Timer, since all the code in the Timer's ActionListener will be called on the Swing event thread, and this can prevent intermittent and frustrating errors from occurring. For example:
public void flashMyField(final JTextField field, Color flashColor,
final int timerDelay, int totalTime) {
final int totalCount = totalTime / timerDelay;
javax.swing.Timer timer = new javax.swing.Timer(timerDelay, new ActionListener(){
int count = 0;
public void actionPerformed(ActionEvent evt) {
if (count % 2 == 0) {
field.setBackground(flashColor);
} else {
field.setBackground(null);
if (count >= totalCount) {
((Timer)evt.getSource()).stop();
}
}
count++;
}
});
timer.start();
}
And it would be called via flashMyField(someTextField, Color.RED, 500, 2000);
Caveat: code has been neither compiled nor tested.
You need to extend public class Timer
Do it like so:
private class FlashTask extends TimerTask{
public void run(){
// set colors here
}
}
You can set Timer to execute in whatever intervals you prefer to create the flashing effect
From documentation:
public void scheduleAtFixedRate(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.
I want to create a countdown clock in GWT but I cannot find the right function that waits for one second. I tried with Thread.Sleep() but I think it is for another purpose.
Can you help me? This is my code.
int count=45;
RootPanel.get("countdownLabelContainer").add(countdown);
for(int i=count; i>=0; i--)
{
countdown.setText(Integer.toString(i));
// Place here the wait-for-one-second function
}
Give Timer a try (See Here).
Changing the example code real quick to something close to what you want, you'll want to buff this up for your purposes though:
public class TimerExample implements EntryPoint, ClickListener {
int count = 45;
public void onModuleLoad() {
Button b = new Button("Click to start Clock Updating");
b.addClickListener(this);
RootPanel.get().add(b);
}
public void onClick(Widget sender) {
// Create a new timer that updates the countdown every second.
Timer t = new Timer() {
public void run() {
countdown.setText(Integer.toString(count));
count--;
}
};
// Schedule the timer to run once every second, 1000 ms.
t.schedule(1000);
}
}
This sounds like something in the general area of what your looking for. Note that you can use timer.cancel() to stop the timer. You'll want to tie this in with your count (when 45 hits 0).
The following snippet showing the use of the timer works too. It shows how to schedule the timer properly and how to cancel it.
// Create a new timer that updates the countdown every second.
Timer t = new Timer() {
int count = 60; //60 seconds
public void run() {
countdown.setText("Time remaining: " + Integer.toString(count) + "s.");
count--;
if(count==0) {
countdown.setText("Time is up!");
this.cancel(); //cancel the timer -- important!
}
}
};
// Schedule the timer to run once every second, 1000 ms.
t.scheduleRepeating(1000); //scheduleRepeating(), not just schedule().