Home > Mobile >  Prevent a function which executes itself after 1 second from being executed every 1 second one by on
Prevent a function which executes itself after 1 second from being executed every 1 second one by on

Time:12-04

I have a function which makes players die after 1 second. But if I have 2 players, first player will die after 1 second and then the second will die in 1 second. I want them both to die in the same time in the first second (together)

dieAfter1Second() {
   for (int players = 0; players  < maxPlayers; players   ) {
      dieAfter1Second(); // executes itself after 1 second
   }
}

How can i execute dieAfter1Second() for all players?

CodePudding user response:

One way to execute the function for all players in the same time would be to use a timer, such as std::chrono::steady_clock. This would allow you to wait for 1 second before calling the function for each player.

Here is an example of how you could do this:

#include <chrono> // for std::chrono::steady_clock
#include <iostream> // for std::cout

// Function to make a player die after 1 second
void dieAfter1Second() {
std::cout << "Player died" << std::endl;
}

int main() {
// Set the number of maximum players
const int maxPlayers = 2;

// Wait for 1 second before calling the function for each player
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
while (std::chrono::duration_caststd::chrono::seconds(std::chrono::steady_clock::now() - start).count() < 1) { }
for (int players = 0; players < maxPlayers; players   ) {
dieAfter1Second();
}

return 0;
}

This code will wait for 1 second before calling the dieAfter1Second() function for each player. It will print "Player died" for each player, and they will all die in the same time in the first second.

Note: This code uses the C 11 standard. If you are using an older version of C , you may need to use a different timer, such as std::clock_t or std::time().

  •  Tags:  
  • c
  • Related