  | |  | Timers and global variables | Timers and global variables 2004-01-15 - By Chad Armstrong
Back Hello:
I've been working on some new gaming concepts for my own little game. I want to be able to implement a background timer which can slowly increment things like health and mana points (for an example) while the character waits or rests.
Since my game runs on Windows, Linux, and Macintosh (OS 8-X), I want to keep this as platform neutral as possible. My program is written in C/C++. Here is some example code I've written:
#include <time.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h>
extern int health = 10;
int main() { int i = 0; int time_passing = 2; int wTime = time(NULL) + time_passing; int child_proc = 0; char ch = 'y';
child_proc = fork();
if (0 == child_proc) { printf("Timer started: %d\n", time(NULL));
for (i = 0; i < 5; i++) { while (time(NULL) < wTime) { }
health += 2; printf("%d ", health); wTime = time(NULL) + time_passing; } } else if (child_proc > 0) {
while (ch != 'n' && ch != 'N') { printf("Would you like to see your health? (y/n) "); scanf(" %c", &ch); if ('y' == ch || 'Y' == ch) { printf("Your health: %d\n", health); }
}
wait(0); } printf("It's all over: %d\n", health); return 0; }
The good news is that the timer is working just fine for what I need. I don't need a nanosecond precision timer, so just counting by standard seconds works just fine.
What isn't working for me in this example is how I'm trying to create a background job, yet have the information which is modified to remain global. In this example, the health variable is incremented by the child process, but not by the parent process. In my game I'll need a way so there is global data. Yes, I might need to lock some information from time to time (mutexes and such). Is there a better way to handle running a background process than just a simple fork? Should I consider using threads instead? Keep in mind that I'm trying to steer away from system specific APIs such as NSTask or NSThread. Thanks.
Chad Armstrong __ ____ ____ ____ ____ ____ ____ ____ ____ ____ mac-games-dev mailing list | mac-games-dev@(protected) Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/mac -games-dev Do not post admin requests to the list. They will be ignored.
Earn $52 per hosting referral at Lunarpages.
|
|
 |