Very basic game programming help and advices

I’m not asking advices about what language or environment is better to start with because my current plan is to play with a roguelike project and I already decided I’ll try doing it in Python and libtcud (a sort of advanced console library that is becoming the standard for not barebone RLs). Though I’ll also put some time into C++ so I’ll probably end up arbitrarily mixing Python and C++ if it can be done without major headaches.

But before I get there I have some unfinished businesses from more than 15 years ago. As my first approach to C I decided to write a kind of RPG engine tile-based similar to the SNES Final Fantasy. I was on MSDOS and using DJGPP with the Allegro library. Some ANCIENT stuff!

Because the Allegro only gave you the barebones to draw bitmaps and so on, I ended up wasting all my time trying to build a sort of GUI, so building functions to make buttons work, get input string for the character’s name using a custom bitmap font (which remains the most complex function I ever wrote, and that worked at the first try) and so on. And finally I was able to have an animated sprite in the center of the screen walking around with the background scrolling (with step sounds!).

The major roadblock that I was never able to overcome (I had no internet to figure out stuff) was that the program ran great on my PC, but when I tried it on a friend’s PC suddenly the sprite was running around at BLAZING speeds. The reason is quite obvious looking at the source code now, since I “paced” the whole program through frequent use of the rest() command. That obviously was custom tailored for my own PC but that wouldn’t have worked on different hardware.

At the time I tried to fix it but the only text I had about interrupts and timer seemed to call some assembly functions that messed with a timer that would either crash my PC or make the computer clock go insane. In the end I never figured out how to fix it, and the project died right there.

I STILL have no idea how you deal with those problems. I still have my mind stuck with the fact that a program cycle runs as fast as it can, following a precise order, and I don’t understand how you can run some parts so that they have a consistent output that doesn’t change with the hardware power. I GUESS that a solution was to bind my sprite animation routine so that each frame was drawn at a sort of regular “tick” (and so keep the timer active only when animations happen, then simply idle and wait for player’s input, but that implies that the world freezes if the players doesn’t give a command), but I remember that at the time my attempt was to run the ENTIRE game loop on a timer, but I was never able to compile it without errors.

So, at a very basic level, how do you deal with those problems nowadays? Say that I want to write a Hello World program with the standard I/O compiled with Code::Blocks and MinGW (so it goes on a windows console), how do I print the string if I want to delay it exactly by one second? How do you set those sort of things when you want in a game that certain things happen at a precise time or pace?

Also, where the f*ck I tell Code::Block to compile with -llallegro library (I suspect that including Allegro.h isn’t enough to call it automatically)? And how can I let it show me the output of the command line it gives, since it only seems to show me errors and such? I mean I want to SEE it call “gcc.exe -c rpg.c -lallegro” so that I can see what it is doing, or something like that…

From a fairly high level, the basic single threaded game loop should be something like


That Delta? That can be as simple as saving the last time you were called, and noting the difference in milleseconds between the two. Most every language has an api for grabbing the latest time.

Then any of your functions that are like
MyChar.x += 10;

should instead be rewritten as MyChar.x += 10 * delta.
(you may need to muck with your 10, as before it was 10 whatever your units are per time called, so if you were running at 60 fps, you’re getting called twice as often as on a machine that can only manage 30 fps, and therefore moving twice as fast)

Note that was shite code, but I wanted to give you a rough idea what the timing is about and how it’s relatively easy to put into your code. Though you end up having to fudge all your numbers over again, if you had been doing everything frame rate independent before.

The code I have (though I’m wondering if it’s a good version since it crashes both in DosBox and VirtualBox) is this:

    case UP:
        for (frame=0; frame<16; frame++)
            if(frame<=3 || frame>=13)

so I suspect that the tile is 16 pixels, that the animation is 2 different sprites, and so that it moves by 1 pixel sixteen times to complete “one step”.

I don’t think in my program the refresh is ever used. My idea was to replace “rest(6);” with a timer delay. If the hardware is powerful (which I’m guessing it is, after 15 years) then the timer would make the cycle idle, if the hardware is slow then it would simply continue to animate as fast as possible.

Otherwise I’d want to have things in the background to move even if the player isn’t giving commands. Tho, I think this would be more an issue about asynch input more than timers (the game would loop on its own, but every cycle reading input from a “buffer” and acting appropriately only if it finds something in it). And in this case? I guess I use a timer at the end of the loop so it once again updates the screen only if the timer conditions are met?

Also, input buffers. Do interrupts still exist? I only know ISA stuff and hex adresses hardcoded into BIOS. How the hell is this being handled under windows?

I’m not sure about your example. It seems to me the the character movement (distance walked) would be constant, but you would get non-smooth movement if a cycle takes too long. Is that right?

Zowie, HRose, you’re like the Rumpelstiltskin of game developers.

Most game libraries give you access to a “render loop” of some kind, which calls you N times per second. Some just call you as fast as you can render. If you want to do less work, you time how long it took you to render, and then you sleep for however many milliseconds it is until the next time you want to render.

Your “rest(6);” idea is more or less correct, except you want to do that OUTSIDE that entire switch statement. Update the world (your “character=…” and “y++” logic); then re-render (your “update_screen();” call); then sleep.

As for input, often that’s handled on another thread these days. Some Windows games handle all their rendering on the main Windows UI thread, rather like GUI applications. Most, though, handle rendering on a separate thread, and just do input processing / world update on the GUI thread.

Also, for your sanity’s sake, learn something about object-oriented programming. In your case here, I’d have the character be its own object with a “target location” that it’s moving towards. On each frame the “character.update()” method moves it one step closer to that target. Then your “switch (direction)” loop just sets the character’s target location, and your “update_screen()” method calls “update()” on each character before actually redrawing the screen.

If you want to see an example of how a typical scene graph / update cycle looks in C# with XNA (soon to be on SharpDX – working on that port now), check out my CodePlex open source project. Happy to answer any questions you have after looking at that code. It’s not exactly a game (more of a musical toy), but it has all the typical real-time game structure because it’s such a frame-by-frame real-time app.

That’s all very good advice from Repo. +1 to all of it.

The switch statement does the whole animation. There’s a FOR that goes through 16 steps, every time moving the screen by 1 pixel and then redrawing. on a “rest(6);” timer between frames so that it’s not too fast.

When the movement is complete it returns, waiting for input.

And while I won’t do anything with that ancient program, I kinda want to fix it because those issues will come up again. BUT, I won’t have ANY framework to do the job. I can’t rely on XNA, Unity, Windows (I’ll code platform-independent) or whatever.

I will use a sort of NCurses (the libtcud), which is the console, and I guess the standard library. So more than using game-specific libraries that do the work on their own, I want to understand how to actually handle it at a lower level, and so handle interrupts or timers on my own.

Isn’t there a goddamn timer usable in the standard C++ library? I want the program to wait a second, or a millisecond, how can I do this?

“rest(6);” rests depending on processing speeds. I want it to rest for a fixed measurable amount.

Oh, and I understand now that you told me to do the waiting outside that loop because ideally one would move everything, wait the right amount, then draw (if you draw and then wait don’t you risk the the rest of the program logic delays it?).

But in my case the player’s sprite was the only thing being moved, so it made sense calling update_screen() from within it ;)

Well, after quite some time recompiling libraries and similar stuff I was able to compile successfully the code for MSDOS that I wrote some 16 years ago!

Had to disable all sound because I used a SEAL sound library that I can’t find. I guess converting to libvorbis and ogg shouldn’t be hard.

But the problem is that the actual sprite movement either crashes or doesn’t work. I’ll have to see how the function have changed in the latest version of Allegro.

I’m quite surprised I got this working for the most part. The code was really ancient.

It’s fun because I fix everything and the problem comes up again in another guise. Now everything works exactly as I left it 15 years ago.

The problem is that this sound library I’m using to play music (I tried to use FMOD, but it was too complex and only gives documentation for C++, and I’m not good enough to be able to translate it to C), but to do it it requires to call a function often, but not too often:

You will also need to pass it to al_poll_duh() at regular intervals; if the sound is choppy, try calling al_poll_duh() more often.

‘bufsize’ is the number of samples that will be rendered at once. 1024 is a suitable value for most purposes. The greater this is, the less often you will have to call al_poll_duh() - but when al_poll_duh() decides to fill the buffer, it will take longer doing so.

So if I want to have background music I NEED some kind of threaded thing, especially if I want the music to continue outside a main loop.

This is where I surrender again. I just don’t know how to tell C to run a function in a sort of threaded mode so that it checks it every “x” amount of time, WHILE the rest of the program goes in a complete different direction.

I only know that a program is executed in a sequence, and that it can loop. HOW THE HELL can I split it? It’s not even a thing that can be done with timers since timers only allow you to measure how much time elapsed.

SO WHAT? How is this done in plain C?

So honestly, your method is totally not the way to go, but the function you’re looking for is Sleep( milliseconds ). Games should basically never need to Sleep inside functions or loops like that, and you shouldn’t be doing it for your next project, but that will get the job done to get your old thing working.

And it still might end up with funkiness, as I don’t think it’s a guaranteed amount of time that the computer will sleep the process for.

Starting a thread is easy, you call (assuming Windows) _beginthread with a pointer to the function that will be the starting point of the thread, and off it goes. The hard part is communicating and synchronizing with that thread, and that can get ugly fast…

There are so many potential gotchas once you’ve got multiple threads going that I’d be reluctant to throw one in just as a quick-n-dirty solution. Even if all you do is loop and call al_poll_duh(), the library might crash if you call that and some other al_* function at the same time, so now your game suddenly starts randomly crashing on you, so now you have to introduce synchronization calls, and it starts getting more complex.

#include <disclaimer.h> // I’m not a games programmer. I haven’t even programmed in 2 years.

Assuming that you can’t spawn threads, you need to structure you game’s main loop like this (stolen from the Wikipedia article on Game programming (!!!):

while( user doesn't exit )
  check for user input
  run AI
  move enemies
  resolve collisions
  draw graphics
  play sounds
end while

I would stick an additional line “pause” as the real LAST item in the loop, which will calculate the correct time to rest() so that the loop itself takes 1/60 seconds to execute.
I would then have to check the codes in the other lines to make sure they can fully execute in less (or even WAY LESS) than 1/60 seconds. I have no idea how to do this, but I would know that any debug code I insert here to figure this out will have additional time impact. (For example, printf() would introduce disastrous delays.)

I’ll also point you to the Event Loop article,to show you how different OS can implement different ways to doing an Event Loop. Essentially, such a loop infrastructure is not provided by C++, C or its standard libraries, but rather by the OS.

Since you mention python, you might want to have a look at this…
It handles a lot of that stuff for you.

One of the awesome things about game programming, is that it is system programming. Code and systems looks more like a OS than a business application.

Perhaps this make creating games a tiny bit more dificult than normal programming, but also more fun. In a game you are building somewhat like a small “scheduler”, the core of a OS. You are emulating a small world that run in small portions of time (quanta).

Theres only one way to write bussines apps ( 3 layers, relational database, OOP, yadda yadda), but theres infinite ways to design a OS. So game design can be more fun and diverse than bussines programming.

HRose, I have to question your goals. Do you want to write a game? Or do you want to learn low-level unmanaged multithreaded programming?

Because if you want to write a game, writing multithreaded C is one of the most technically challenging ways to do it. C (and C++, to an extent) are like building a house one brick, conduit, pipe, and shingle at a time. You can do it, but you’d damn well better know what you’re doing or you’ll electrocute and crush yourself repeatedly.

Whereas using a Python (for example) library, like that one jellyfish cited, is basically getting a prefab house and moving right in.

It’s up to you – and you will definitely learn how this shit really works if you go full C – but you must be prepared for a much longer and more painful debugging and development experience.

The first advice I can give you is start out simple. A good exercise is to rewrite the simplest game that has the design already in place (pong, snake, tetris) before trying your own game.

Here’s a very quick game I made in javascript using the html5 canvas.

And a simple particle test I made using the same code base.

Since it’s in a browser, you can freely view the source.

The problem is that because of how my mind is built I handle prefabs badly if I don’t know how they work.

I WILL use Python and go through reimplementing all the basic functions of a roguelike that are available in tutorials. My goal is: get to a point where I don’t have to write just the game structure, but where I can finally have fun coding the combat and build the content. Build the actual game. I hope that using Ncurses or libtcod I’ll get really quick to the heart of matters since I don’t have to set up complex UIs, event handlers or make the graphic and so on.

In the case of that old RPG engine it would have taken me YEARS to get to the point where the engine is done and works, and I could actually begin to code the damn game and mechanics. That’s what I want to avoid.

Trying to get this 15 years old code is just about settling an old matter and grasp a few ideas that I wasn’t able to. I think it can help and is helping me right now to get back into programming mentality (because I’ve programmed nothing in that time span, and I’m restarting from zero).

I found this page that gives an easy example. It uses: #include <process.h>

It actually works. Even if I’m sure I’m NOT using orthodox ways to make it work.

I noticed that if I called the thread to put the poll function for the music, it works. But it kinda maxes the CPU usage for no real reason.

So I put in it this wonderful piece of code, see my raw talent:

void threadm( void* pParams )
        int     rinon;
        for (;;) {
            if (al_poll_duh(dp) || closed)

            rinon = rand()%(101);
            if (rinon < 80)

(YIELD is a function I copied from an example) So essentially I put a check that makes the process idle 80% of the times the thread runs.

Because otherwise it happened that the main thread was sort of locked out, for example not registering keypresses, since I think this thread was monopolizing the attention.

Now this thing works in practice. It doesn’t crash, uses almost zero processing power and plays both music and main thread. But I STILL have no idea how you code this in more sane and consistent ways.

Example: say that I need the game to do something exactly every ten seconds. If I put in a thread that checks if 10 seconds have passed I have the risk that the CPU keeps incessantly CHECKING millions times every second that “ten seconds have passed”.

This kinda defies the purpose of doing something every ten seconds (so taking away almost nothing from a main thread).

I’d ideally create a thread, that checks if 10 seconds have passed, and then call another thread that does its work. But it’s kind of THE SAME. The checking thread would then go on obsessively checking, monopolizing everything.

I wonder if my code up here does something like this:

  • I spawn a new thread, that for 20% of a second polls the music, then for the remaining 80% gives control to the main thread.

It’s as if the main thread becomes a SUB THREAD of the one I spawned, so that I can keep polling the music (which needs just a simple and lazy loop, but that needs to be stable) while the rest of the program can go on in the “spare” amount of time.

Like i said, you basically should totally redo your main game loop, that is the only thing that should be looping, and you really shouldn’t mess with multithreading yet, it’s not doing you any favors until you understand singlethreading.

So some pseudocode

lastTime = GetTimeInMilliseconds();
currTime = GetTimeInMilliseconds();

elapsedTime = currTime - lastTime;

Sleep(1); //or whatever, not entirely neccesary


Handle Input would just poll to see if keys were pressed, and map them to inputs like MoveLeft, or MoveRight, Jump, Shoot, etc.

UpdateGame(elapsedTime) is your workhorse. Basically, that elapsed time tells you how much time has passed since the last time this function was called, so if your user had designated that they wanted their character to move to some tile, you’d have it incrementally move towards that tile in that function, just interpolate to that new position until the character is there. (multiple ways to do this, if you want the character to animate over there and take 5 seconds to do so, then just do a simple linear interpolation, (charOrigin + charDestination * T ) increasing T every time that UpdateGame is called by elapsedTime until it hits 5 seconds or more. (never do equals comparisons with floats or time if you can avoid it)

Now, some folks want a game to only update at set intervals, which makes sense for multiplayer, and then it makes sense to stick that in another thread, that just polls for the time and if it’s equal or to or greater than the time elapsed, do the update function, then sleep for the set interval. You would still have to check for the time elapsed though. As you will run into issues when the cpu can’t actually manage to run as fast as you’d like. (or just scorn the nubs with crap computers, but not recommended.)


            rinon = rand()%(101);
            if (rinon < 80)

another way to write this, withouth randomness.

            rinon++;//it must be defined somewhere as static
            if (! (rinon%8) )


@Teiman: The math is a bit off. (rinon < 80) is true 80% of the time; !(x%8) is true 87.5% of the time.

@HRose: See if there’s a YIELD function which can take a time. What I am looking for is a YIELD(10 seconds) which will block the thread for 10 or more seconds. What I’d do then is to yield in 1 second interval in its own loop to check if the 10 seconds is over or any other interesting condition like user input, etc. Another place I’d look for such a wait function is in the user input library. Perhaps the get key function has a timeout parameter? I can use that function in the same way as a yield(time).

The basic premise of the above is that such a method does not do active CPU polling or busy waiting, but instead can park the thread into idle waiting for a timer or other I/O interrupt. This is usually how single thread event loops works.