how do i sequence methods in libgdx - timer

I am using libgdx and i have several game objects with different methods i want the methods in my timer to happen one after another but in libgdx they happen all at once i dont know how to fix it
timer.scheduleTask( task = new Task(){ public void run(){
rando =rn.nextInt(8);
Gdx.app.log("the num is", Integer.toString(rando));
if(rando == 0){
bush.rustle();
bush2.rustle2();
bush3.dontrustle3();
bush4.dontrustle4();
enemy.shoot();
enemy2.shoot();
enemy3.godown();
enemy4.godown();
}
if(rando == 1){
bush.dontrustle();
bush2.rustle2();
bush3.rustle3();
bush4.dontrustle4();
enemy.godown();
enemy2.shoot();
enemy3.shoot();
enemy4.godown();
}
if(rando == 2){
bush.rustle();
bush2.dontrustle2();
bush3.rustle3();
bush4.rustle4();
enemy2.godown();
enemy.shoot();
enemy4.shoot();
enemy3.shoot();
}
if(rando == 3){
bush.rustle();
bush2.rustle2();
bush3.rustle3();
bush4.rustle4();
enemy.shoot();
enemy2.goup();
enemy4.goup();
enemy3.shoot();
}
if(rando == 4){
bush.rustle();
bush2.rustle2();
bush3.rustle3();
bush4.rustle4();
enemy2.godown();
enemy.godown();
enemy4.shoot();
enemy3.shoot();
}
how it works is that everytime a number is called a set of methods run but they run all at once i want them to run one after the other

You might look at the libgdx-ai extension. It has some utilities for building up and reacting to events. The state machine is probably overkill for what you want, but might have ideas you can crib from.
See also https://gamedev.stackexchange.com/questions/14568/integrating-an-ai-state-machine-with-actions-that-take-more-than-1-tick
A lighter-weight approach might be something like this: http://vanillajava.blogspot.com/2011/06/java-secret-using-enum-as-state-machine.html (though I recommend doing this mostly as a way to understand the more complex AI library state machine).

Related

How to reduce the number of else if in paho mqtt callback function with c?

I am using the PAHO mqtt asynchronous function to subscribe to topics, but I found a problem. When I receive and parse topics in the callback function messageArrived, I need to write a lot of else if to judge whether it is the corresponding topic. If so, I subscribe to many topics, then the topics written after else if will be implemented relatively slowly because they need to be compared one by one. And because topicname is char type, so I can't use switch... Case..., what's your good idea
rc = MQTTAsync_setCallbacks(MqttClient, (VOID*)MqttClient, connlost, messageArrived,
deliveryComplete);
...
INT32 messageArrived(VOID *context, CHAR *topicName, INT32 topicLen, MQTTAsync_message *message)
{
if (strcmp(topicName, TOPIC1) == 0)
{
//do something
}
else if (strcmp(topicName, TOPIC2) == 0)
{
//do something
}
...
// many 'else if'
...
else if (strcmp(topicName, TOPICn) == 0)
{
//do something
}
}
If you have a large amount of possible strings to check for, you need to change the whole algorithm if you want it to become more efficient. There's two common ways to implement this efficiently:
either through a sorted table of constant strings which you can binary search through, or
as a hash table of strings
The binary search will outperform the hash table up to a certain amount of strings, after which the hash table will become the more efficient.

Force an error or give a warning in one of the if conditions in C

I want to write a function in C and to put a condition in it. If the condition isn't met the program gives and error and prevents the user (developer) from compiling the code.
For example:
void func(int x)
{
if (x > 0)
{
//do stuff
}
else
{
//give an error and stops the code from compiling
}
}
prevents the user (developer) from compiling the code.
There's a problem there. You can decide on the user's behaviour, but you can't decide on the compilation of the program. If the code is right (right in the language sense, so it makes sense to the compiler), it will compile, else it won't. You can't make up new arbitrary rules for the compiler.
Before you can even run a program written in C, the compilation needs to be fulfilled.
Functions are called at run-time and so are the parameter values determined at run-time, too.
You can't make the compilation of your code dependent upon the variable x in C.
What you're trying to achieve is basically completely impossible.
Let's take an example. Assume that you want to manufacture an elevator, and you set the weight limit to 800 kilograms. You could build in something that makes the elevator stop if the weight exceeds the limit.
So take the scenario where we program the elevator so that it does not move if the weight limit is exceeded. That would typically be done with an assert() or something like that.
You could also in various way try to prevent this from happening, like making the elevator very small so that you cannot fit too many people. But that is not a fail safe option. We have restricted the volume, but nothing prevents a person from bringing a big chunk of solid gold into the elevator.
The point here is that you can measure the weight before moving the elevator, since this is done at runtime. But preventing someone from even trying to exceed the limit is virtually impossible.
In the general case, what you're asking for is completely impossible. What you can do is something like this:
void func(int x)
{
assert(x>0);
/* Do stuff */
}
And a slightly related thing that is possible is to create a test that is a part of the build process. You cannot prevent compilation the way you want, but you can use it to fail the whole build process. An example.
// main.c
int add(int x, int y)
{
return x+y;
}
bool test()
{
if(add(4,5) != 9) return false;
return true;
}
int main(int argc, char **argv)
{
if(strcmp(argv[1], "--test") == 0) {
if(!test()) {
printf("Test failed\n");
exit(EXIT_FAILURE);
}
// More tests
printf("All tests passed\n");
exit(EXIT_SUCCESS);
/* Rest of the main function */
}
Then you create a Makefile that compiles main.c and then calls ./a.out --test as a part of the build process. The above example is a very simple case, and for a more realistic case I would have made it a bit more sophisticated, but it shows how it can be done. Also, there are libraries that can take care of this kind of stuff, but this is a way to do it without having to use that.

When is it acceptable to break prematurely out of a loop/method?

This is a question I've been facing for a while in my college class that I've been thinking about, and I need to get other people's point of views. I searched and couldn't find another question very similar to this one in terms of coding practices.
(Examples are written in Java)
When I write my code, I will generally write methods like this:
public void myMethod(int one, int two) {
if (one >= two) return;
// do things
if (two != one) return;
// do other things
}
Instead of writing methods like this:
public void myMethod(int one, int two) {
if (one < two) {
// do things
if (two != one) {
// do other things
}
}
}
Similarly, I will write my loops like this:
for (int i = 0; i < x.length; i++) {
if (x[i].getValue() > 4) continue;
// do things
if (!xConditionTwo) continue;
// do other things
}
Instead of like this:
for (int i = 0; i < x.length; i++) {
if (x[i].getValue() <= 4) {
// do things
if (xConditionTwo) {
// do other things
}
}
}
As seen here, I look at things sequentially (from top line to bottom line), and it makes sense to me to exit out of the method/loop if that something is not what we're looking for, and we don't require an else statement.
However, when I spoke to my college instructors, they all agreed that if somebody were to write code like this, they would not be hired because said person cannot figure out an algorithm that wouldn't require the use of a continue/return.
My question to everyone is: When is it acceptable to use continue/return to break like this, if at all? Why is this considered bad practice, and how can I avoid using if statements without an else to avoid extra indentation?
This is going to be a question mostly dealing with opinions, but for both of your examples I'd use the continue/return in the first line like you have it, but use an if statement for the other.
public void myMethod(int one, int two) {
if (two >= one) {
return;
}
// do things
if (two != one) {
// do other things
}
}
To me, this reads better and limits the nested if statements

threads in c, how to use them to move a player?

Update my code
So i am working on a 2d game in c, now i am using threads to do different stuff in the same time, to move the player, cars etc.
But somehow i don't get it how can i move my player just one step, i know that the problem lays in my global variable movement. But can figure it how to do it the right way. So i hope someone can help me.
The code is huge so i will not passt all of it but the parts that are interesting for the player movement.
void moveFroggy() {
// froggy.y = SCREEN_HEIGHT - OUTER_BORDER;
if((movement == 'a') && (froggy.x > OUTER_BORDER))
froggy.x--;
if((movement == 'd') && (froggy.x < (SCREEN_WIDTH - OUTER_BORDER)))
froggy.x++;
if ((movement == 'w') && (froggy.y >= (SCREEN_HEIGHT - NUM_LANES - OUTER_BORDER - GRASS_BORDER)))
froggy.y--;
if ((movement == 's') && (froggy.y < (SCREEN_HEIGHT - OUTER_BORDER)))
froggy.y++;
if(movement == 'q')
quit = 1;
if(froggy.y <= (SCREEN_HEIGHT - NUM_LANES - OUTER_BORDER - GRASS_BORDER))
player_won = 1;
movement = '0';
}
Now inside the main we have a while loop that runs all the time, till the player complete the game or quit it.
pthread_create(&input_t, NULL, input_runner, NULL);
while(!quit && !error && !player_lost && !player_won) {
moveFroggy();
moveCarsOnMotorway();
startCar((SCREEN_WIDTH - OUTER_BORDER));
drawScreen();
usleep(GAME_SPEED);
}
pthread_join(input_t, NULL);
So my input_t thread is calling the input_runner function inside that function i get the user input.
void *input_runner(void* arg) {
char input;
if(!player_lost || !player_won){
while((input = getchar()) != EOF){
movement = input;
}
}
pthread_exit(0);
}
Just to know movement is a global variable so i can use it for moveFroggy function. but that is the problem to because it stores "w" and it just repeat itself till the user hit any other command. But it should move the player just one step ahead, so how can i reset the value and how to do proper clean up for threads if one is needed.
I am new in using thread,
Well, it seems the simple way to only move one step would be, at the bottom of moveFroggy() to clear movement value.
As an aside, it looks like you're creating an input-processing thread on every iteration of your game loop; is that really what you intend? If you want an input-processing thread, why not have it run its own loop to constantly read input until the game is over?
I'm also not sure of this overall multithreading strategy, but perhaps it will work for you...
This is not a good use of threads, and will be prone to synchronization errors.
Variables that are accessed by multiple threads must be protected by a mutex or accessed using atomic methods. Failing to do so will result in unpredictable behavior.
In any case, you don't need threads for this. If you want to read from the keyboard without blocking, there are a number of ways of doing that, including:
If on Linux, use the ncurses library, which natively provides non-blocking keyboard input through getch().
If on Windows, use kbhit().
Use fcntl() with F_SETFL to set standard input as non-blocking.
Use select() or poll() to check for input before trying to read.
Avoid the console entirely, and use a graphics library such as SDL.

Synchronize Threads - C

I have a C++ wrapper class that uses C code. reading_function is running in a thread, and the function only returns when write_is_finished. This function should read data when a new segment is wrote. writing_function is called when a new segment is available. So, my objective is to do write-read-write-etc. To make that possible I use an infinite loop, with if else statements (pseudo-code):
int reading_function([parameters]){
//....
for(;;){
sleep(_few_ms);
if(is_writing == false){
is_reading == true;
//..read
is_reading == false;
}
if(write_is_finished == true){
return check_state;
}
}
}
int writing_function([parameters]){
//...
for(;;){
sleep(_few_ms-2);
if(is_reading == false){
is_writing = true;
//...write
is_writing = false;
}
return check_state;
}
}
The program is running good. But I want a more elegant solution. Since this is C code, called from a C++ class. I don't know how can I synchronize the read and write threads.
It may depend on the environment that the code will run. If it is going to run on Windows, you may use thread synchronization objects like Semaphore or Mutex, and WIn32API provides such function to create, control and release, e.g. CreateSemaphore, CreateMutex.
If it is going to run on Unix environment, you may use posix-supported synchronization objects, e.g. pthread_mutex_, or pthread_semaphore.. The usage of these are pretty much well documented so that you may write your code without meeting race conditions.

Resources