How to detect button press in a timed loop - java

I am a beginner in Java and am trying to practice my skills. I am trying to create a game that requires the player to hit a button repeatedly for a certain amount of time. I want to do something like this to generate a number of how many times a specific key, like the space bar, has been pressed in a specific time, for instance, 30 seconds
while(time!=0){
//amount of time
if (isPressing("w")){
buttonPressed ++;
}
//decrements amount of time
}
Ultimately once the time runs out I want to exit the loop and return the number of times the button has been pressed. I am unsure of how to actually accomplish this as the timers I have found are looped to repeat an action on an interval. Can anyone help give me some direction?

You can get the time in milliseconds with:
Following your example of 30 seconds,you would do something like this:
long time = System.currentTimeMillis();
while(System.currentTimeMillis() - time < 30000){//30000 is 30 seconds in milliseconds
if (isPressing("w")){
buttonPressed ++;
}
}
It would work by comparing the start time with the time after every iteration.

Related

AnyLogic: How to check the availability of a process depending on the time and a probability?

I need a way to check the availability of a delay block depending on the current time in the model. In the end I want to check for a suitable time window to perform a process.
For this I have a table (MS Excel) with the month, the day, the hour and an associated probability (e.g. 8; 5; 2; 0,9134 represents a probability of 91,34 % at 2 AM on the 5th of august).
Now I want to check the time window as if I would toss a coin with the given probability.
Since the time window is longer than 1 hour I need to check the probability in the next hour(s) too.
Example:
My process (delay block) has a delay of 5 hours. When the agent enters I want to "toss a coin" for the first, second, third, fourth and fifth hour since the time stamps have different probabilitys. When all five tosses are successful, the agent enters the process and the process is performed.
I hope I made my point clear enough. I tried to implement an excelFile but I have no clue how to proceed further.
Thank you in advance!
Edit: I'm using the Personal Learning Edition.

Java Handler Post Delayed task is not accurate timer

I have created two Handlers, which each have Runnable Tasks which run in a loop through:
// do it again 1 hundeth of a sec later
QuestionHandler.postDelayed(QuestionHandlerTask, 10);
And through:
// and do it again 1 sec later
GameHandler.postDelayed(GameHandlerTask, 1000);
Both the tasks start at 10 and count downwards and their results are displayed in labels. The reason i have used 2 handler's is because i want 1 timer to count down by milleseconds and 1 to count down by seconds.
However, the GameHandlerTask that runs once per second runs significantly faster than the other. By the time it reaches 1 the QuestionHandlerTask is still at 4 seconds:
Is this a commonly known problem or have i done something seriously wrong? Is there some way i can make it so my timers run at the same speed? Is there other methods that i can use that would be better in this circumstance (where i want precise timing)?
This is because the screen cannot refresh 100 times per second, which is what is happening with the 10 millisecond timer. So the screen tries to show every single value that you told it to show, but can only do so at its maximum refresh rate.
It is not the timer that is slow, it is the screen that can't keep up with the timer.
To solve this, try to calculate how much does the number need to go down by in 40 milliseconds, and you start a timer of 40ms. This will update the screen 25 times a second, which the screen should be able to handle.

How to change variable every x second without stopping the program in Java?

Iam new here, like week ago I started learning to program and Iam working on my text based strategic game in which I would like to make resources gather every x seconds passively.
basicaly my game is based on while (true) loop in which are switch cases and the game keeps waiting for keys to press to gather resources.
I would like the game to gather resources passively every x seconds.
example : every 10 seconds you will receive +1 wood.
I will welcome in help :)
Iam programming in java using NetBeansIDE
Just get the current time in every loop run with this
and check whether the 10 seconds passed since last time you gave +1 wood.
Note the time unit.
I am not sure how you are storing gathered resources, but if you could call a method to look it up based on when the game began. You could store the following variable as part of your game class:
private long startTime = System.currentTimeMillis();
And then get current resources by using the following method:
public int getWood() {
long diffMilliseconds = System.currentTimeMillis() - startTime;
int numSeconds = (int)diffMilliseconds / 1000;
int amtWood = numSeconds/10;
return amtWood + <any other wood gathering/calculating parameters>;
}
This does not account for using your wood. If you want a variable to update every ten seconds, you could use something like the solution here: Print "hello world" every X seconds. This solution uses the TimeTask class. Rather than printing, you could update a amtWood variable.
If there are no restrictions on what classes you can use, try Timer class available as part of Java Swing. You can also look at java.util.Timer class for scheduling your updates.

How to change schedule to a certain time every day insted of every X time

iam trying to make a task to be executed EVERYDAY at 8am (example).
Currently what i have done is make a task, execute it automatically but only for a period of time (in this case 50 seconds) i want it to be executed every day at 8am.
my current code :
Timer time = new Timer();
certif_envia_notificacion st = new certif_envia_notificacion();
time.schedule(st, 0, 50000);
where certif_envia_notificacion is the task that i want to execute, and it does execute every 50 seconds.
Currently the only way i can figure this out is in the task certif_envia_notificacion ask for the time and execute if its 8am, but that seems like a huge waste of server resources, since ill have to execute the task at least 24 times a day.
Thanks in advance.
This is kind of a hack solution that I thought up, but feel free to give comments/feedback based on your requirements.
Basically, from my understanding you have a Java program that runs automatically when the computer starts up (if it restarts), and will then check every hour to see if it is the correct time to run the application. Why not keep it running this way, but instead of running every hour, calculate the time required to get to the next time required (e.g. 8PM the next day).
So for example, lets say you restart it at 3:15PM. When the java program runs, get it to get the current time (System.currentTimeMil...) and then calculate the time required to get to 8PM. You can do some simple math on this (e.g. 20 - current time = time required to wait) and if its negative, simply add 24 to it (e.g. if its 20 - 23, the answer is 24 - 3 = 21, thus wait 21 hours for the next 8PM).
This process can be used every time you run the code, or on startup. I'd recommend just creating a simple function to calculate the required sleep time.
What i finally did was execute the procedure every one hour and make a question of the hour and select the hour that i wanted, i know its not the best way but i needed to finish it fast....
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
if(hour == DesiredHour){
//do stuff
}else if(hour == DesiredHour2){
//do stuff 2
}
Thanks for the comments.

Detect screen press at certain times

So, I am fairly new to java and android programming and I am having an issue coming up with the code for a project I am working on. Basically, there is a list of times, which I assume need to be stored as an array. Once the game has started, it needs to do one of two things:
If the user presses the screen within a few milliseconds of a time in the array, it will register as a hit and increase count.
If the user presses the screen outside of the "hit" time, it will register as a miss and reset count to 0.
Now, I have all the elements in place to make everything work (increasing count on screen press, etc). My issue is with the code to detect if the user pressed the screen on time or not. I have tried doing some searches, but I can't figure it out. Here is a small list of the times that are "good" hits:
0.25
0.84
1.03
1.60
2.3
2.6
2.9
These times can change a little and some can be removed if its not working correctly. The biggest issue I can think of is making sure that it starts the timer when the game starts so the times match up. The current timer starts at 100 and counts down 1 second at a time and when it reaches zero it takes the user to the game over screen. This of course can change if there is a better way to do it or a different way that it has to happen to make the screen press detection code work.
Any idea how to make this work?
Really, all you need to do is log the current system time at the time the game starts. Then, it's just:
long startTime = System.currentTimeMillis();
//...
System.currentTimeMillis() - startTime;
Then, to check if you're within the bounds set at any point in the array (which I will assume is an array of doubles):
public final static int THRESHOLD_MSEC = 100;
public boolean isHit(double time) {
int time = System.currentTimeMillis - startTime;
for(double d : array)
if(Math.abs(d-time) < THRESHOLD_MSEC) return true;
return false;
}
Then, elsewhere in your application, you can handle what happens when isHit returns either true or false. I'm not going to write that part for you. A point of note: a few milliseconds is nothing in comparison to human reflexes, and nobody will be able to make that time.

Categories