Thread: Time function for game in C

  1. #1
    Registered User
    Join Date
    Mar 2019
    Posts
    2

    Time function for game in C

    Hi,
    Im developing a game in which the user puts some value of time between 5 and 15 seconds for each play. The game should run until the time reaches its end (value inserted by the user). Iíve not been able to code thi, Iíve tried wait(), diff_time, sleep() but those didnít work out since sleep() actually stops the processes entirely. What Iím trying to say is, is there a function of time that can run in ďbackgroundĒ and when the time ends return some value that I can use for... letís say an if statement, run the game until that value is returned.
    Thank you everyone.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,408
    Which OS and Compiler are you using?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Feb 2019
    Posts
    494
    Maybe what you are looking for is something like this:

    Code:
    #include <time.h>
    
    // 15 seconds...
    #define DELTA_TIME 15
    
    extern void scheduled_task( void );
    extern void game_logic( void );
    
    void main( void )
    {
      time_t start, current;
    
      // Game Main Loop.
      start = time(NULL);
      for (;;)
      {
        current = time(NULL);
        if ( current - start >= DELTA_TIME )
        {
          scheduled_task();
          start = current;
        }
    
        game_logic();
      }
    }

  4. #4
    Registered User
    Join Date
    Mar 2019
    Posts
    2
    I’m using Mac OS X and XCODE

  5. #5
    Registered User
    Join Date
    Feb 2019
    Posts
    494
    If you want to use a callback, you can always use SIGALRM signal. But SIGALRM can be used by sleep() in cerain Unix implementations (I don't know about OS/X).. And you may have problems with some libc functions that aren't "signal safe" (take a look at glibc documenation).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 01-12-2013, 10:11 AM
  2. Replies: 1
    Last Post: 03-18-2011, 02:29 PM
  3. time reaction game
    By fatcecil in forum C++ Programming
    Replies: 3
    Last Post: 05-12-2003, 06:25 PM
  4. Best Game of all time
    By face_master in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 12-11-2002, 09:36 AM
  5. Using time.h in an F1 manager game.
    By marCplusplus in forum C++ Programming
    Replies: 9
    Last Post: 02-08-2002, 05:39 PM

Tags for this Thread