Is there a way to make random ticks in a game loop? - java

I need random ticks for a game I'm making. Is there a way I could do that? I don't want it based on the tick rate of my game (average 60 ticks per second) because I need random movement for a character. Maybe I could use some of Notch's code?

Run a javax.swing.Timer at a fixed rate; in the listener, use a random variable to decide if something happens, e.g. nextBoolean() for 50% probability, nextInt(3) for 33%, etc. There's a related example here.

You have two main choices;
You can store a random value, and decrement it (reduce by one) every tick. when it reaches zero; perform your desired action, and assign a new random number to the variable. rinse and repeat.
This effectively gives you a random psudo-tick, entirely within the contraints of the existing timing mechanism.
Disregard the tickrate; randomised actions do not require randomised intervals, only randomised chance.
Basically, each tick you roll a chance of deciding on a new action, if the chance succeeds you choose a new action for the entity.
Its common to modify the chance based on how long they have been doing their current action; so that the longer an entity has been, say, 'sitting down', the more likely they will be to switch to something else.
You probably will also want to look up material on state-machines,
as its a common way of implementing simple AIs for game characters (which seems to be what you are doing).

Related

Repeating a method multiple times per thread loop

To give some background information, I'm currently working on a Java coded pinball game. I'm keeping it in an MVC design model. It has a fairly realistic physics system that allows it to work collisions, gravity, friction etc. The system runs on a 20 FPS system right now.
The problem I'm having is that the physics loop that checks for collisions in the system works by running a method that using the current velocity of the ball calculates the time until the next collision. The most effective way for this to work would obviously be to keep running the check to account for the movement of the ball between checks to get it as accurate as possible, and if the time until collision is less than the time until the next check, then carry out the collision.
However, right now the system I am working with can only run the loop 20 times per second, which does not provide as accurate results as I would like, particularly during times of high acceleration, such as at ball launch.
The timer loop that I use is in the controller section of the MVC, and places a call to the physics section, located within the model. I can pass in the time remaining at the time the method is called in the controller, which the physics system can use, however I don't know how to run the loop multiple times while still tracking the remaining time before the next screen refresh?
Ideally I would like to run this at least 10 times per screen refresh. If anybody needs any more information please just ask.
Thanks for any help.
So the actual problem is that you do not know when the the collision will happen and when the next frame update is?
Shouldnt these be seperate running tasks? One thread that manages the collision detection and one that does the updating? each thread can run on its own interval (Timer.addTask(...)) and they should propebly be synchronized so colission/location updates are not performed when the render thread is executed.
Hope this answers your question.
Regards, Rob.

Handling time in a text-based game (Java)

I'm trying to work up a basic text-based game as I'm learning Java. I'd like to be able to count rounds in the game as a means of managing the pacing of certain events. For instance, changing rooms could be limited to once per round (a second, in the test code.) A small creature might attack or change rooms at a higher rate, whereas a larger one might be more cumbersome. Good so far? Great.
So, I cooked this up and immediately realized that I'd be hitting a block each time the while loop waited for the player to input a command. Code:
private void startPlaying() {
//declare clock/round variables.
int lastRound = 0;
int currentRound = 0;
long lastTime = System.currentTimeMillis();
long currentTime;
while (player.getIsPlaying()){
//Clocking
currentTime = System.currentTimeMillis();
if ((lastTime + 1000) < currentTime) {
lastTime = currentTime;
lastRound = currentRound;
currentRound++;
System.out.println("Current round:\t" + currentRound + "\tCurrent time:\t" + currentTime); //EDIT:NOTE: This is just a test line to observe the loop.
}//end if (Clocking)
Command command = new Command();
String[] commandString = command.setAll(); //Array gets parsed elsewhere.
player.doCommand(commandString);
//Class Player extends Pawn extends Actor; Pawn has most command methods.
}
finishPlaying();
}//END STARTPLAYING()
So, here is my question:
Is there a way I could use a separate method to log time/rounds concurrent to the while loop presenting the player with a command prompt?
If not, is there a different way to make this a non-issue that I'm just not seeing/practiced in yet?
Take a look at Concurrency tutorial. With threads you can wait user input without stopping other processes (and make these other processes execute at the same time - not in parallel, but time-sharing).
It is called "game loop" which allows the game to run smoothly regardless of the input of the user.
The most straightforward solution - create 2 threads, frist will wait for user input and puts it into ConcurrentLinkedQueue with capacity 1. The second thread will run your game loop and takes user input from queue to process it if queue is not empty.
You can use any data structure you want to exchange data between 2 threads, it can be even volatile string variable. The only requirements read write access to this variable should be synchronized somehow.
A real-time text adventure? Sounds interesting. I wouldn't suggest trying to do concurrency for this particular problem, there are easier ways.
Normally you wouldn't mix blocking on input with time in seconds. Unless you have your heart set on this design, I'd suggest either.
1) Don't block on user input. Write your own input handling code by checking for key-presses each frame. Then you can just calculate the time difference between iterations. E.g. a monster moves 1 block second, so if the current loop iteration took 100ms then it moves 0.1 blocks. (store these values as floats internally, even if you draw on a text grid.
2) Increment game time in 'ticks' based on user input. This would be NetHack/Roguelike-style. Monsters can move so many blocks per tick, rather than per second.
Yes there is a way. You would need to put the "Round Counting" code in its own Thread, so it in not blocked by the user waiting to input data. The java.util.concurrency package can help with this.
Look at Java Doc the scheduleAtFixedRate() method will execute a runnable at fixed intervals. The "round counting" code would be moved to a class that implements the runnable interface. And this would be executed at the set time interval. This is reasonably advanced though.

how to Slow down AI?

So i'm writing an app for android where you play a game similar to Dutch Blitz. Its a pretty simple game, and I have it basically finished, I'm mostly looking for advice for how to handle my AI opponents, right now they win the game in about 2 seconds, I was wondering what i should do to get them to "pause" mid loop or how to slow them down some how so that the user has a chance to actually win.
I just don't want my way to slow them down dependent on the processor speed of the phone used...
I'm not familiar with the game Dutch Blitz, but this logic should apply. You can create your turn functionality triggered by a Count Down Timer. That function repeated (think of this as a turn) will eventually equate to a win condition. Causing your AI to prevale eventually, but not right away. You can then set the rate of how often a turn happens, thus controlling the rate at which your AI will win. Also this makes it easy to set difficulty levels by increasing the time it takes your AI to complete a turn.
Your game may work with different rules, but some kind of interval per turn would probably be the simple way to control the speed of your AI.

Create new enemies by Timer or by game loop?

I am creating an android game where enemies are generated randomly and there can be multiple at once.
Is it better to create the enemies at a random time from a timer (so 5s, then 4s, then 6s... etc), or through the game loop (count to 50, create enemy, count to 64, create enemy).
If the phone the person used was slow at rendering the game loop, the timer could create too many enemies, but if it used the game loop, they would not get enemies very quickly. There appear to be pro's and con's for each.
Also, which is better for saving processing power so it can render images faster?
Thanks in advance
Tom
ALSO, if I used a timer for each "group" of enemies, there would be 3 timers running.
I recommend a combination: The engine should be driven by "ticks" that in itself don't represent a specific duration. All engine decisions should be done based on time calculations independent of the ticks (e.g. System.currentTimeMillis subtractions). This way when there is high load on the machine you get lower frames per second but the distance of movements is not influenced. When there is lower load you get smoother graphics and movements. You should check for FPS and if they get to high you should even set the thread to sleep or you can generate more enemies. If it gets too low you can lower graphic details or prevent generation of new enemies to adapt to the situation. So I wouldn't start timers but store times for events that you precalculate to occur in the future and check in the game loop if it is time for them to happen (not with exact comparision, of course, but eventtime < now).

Best way to simulate a server which randomly sends alarms

Here's what I need to do:
I need to simulate a server, which sends alarms at random intervals, i.e. after 2 secs, then after 4, after 10 but always within some sort of range.
What is the best way to achieve this?
Here's my fist idea:
1.) Choose a random value between 0 and 10.
2.) Sleep for that amount of time
3.) Send an alarm to the client
4.) Repeat forever (i.e. while (true))
Your idea doesn't sound so bad. Of course, you could go a more sophisticated path using timers and signals, but it depends on the requirements and using simply sleep() is maybe the fastest and easiest way for your purposes. Go for it :)
For range 4-10 seconds, choose a random value 0..6 (10-4), add 4, sleep this amount of seconds (or get current time, add the value, and loop with a short sleep rechecking the time), send alarm, rinse, repeat.

Categories