Very basic game programming help and advices

Yes, that’s correct: “sleeping” the thread is something that you have to ask the operating system to do. It’s not a concept that exists in the C language; it’s an operating system scheduler function. Since the OS controls which threads are doing what when, you need to tell it “this thread has nothing to do, let it sleep.”

After you get that sort of thing figured out, you then get into synchronization functions, which are additional OS functions that you call. For example, you can create an “event” object by calling one OS function, and you can then call a different OS function from a thread that needs to wait for something to happen – something like WaitForSingleObject() in Windows, for instance, or select() when waiting for a network connection. The thread that calls that function will stall until some other thread calls SignalWaiters(eventObject) (or whatever) on that event object, at which point the original thread will resume. So, in other words, a thread waits for something to happen by calling a function that will block (e.g. not return) until that interesting something has happened.

Is this making more sense now, in terms of how the language interacts with the operating system to handle thread synchronization and scheduling?

I don’t have time right now for the previous discussion, but I have another question: is it natural that the program becomes an endless queue of if…else checks that get nested really deep?

Is there some other, better organized practice that doesn’t look horrid?

For example: right now when my character moves a step, in order to produce a step sound, I make a check about whether or not sound is enabled (otherwise it crashes if it tries playing a sound that doesn’t exist). That’s the first check. Then I roll a random number, so that the two sounds I use for steps are randomized. That’s a second check. Now say I want to use different sets of sounds for different terrains. I’d have to check for every terrain type (would you do this with “switch”?) and then redirect to the pertinent play_sound command.

I could imagine that in a actual game that main loop ends up having hundreds of nested checks…

Is this a correct practice that just needs to reduce the complexity by breaking that main loop into sub-functions (for example I do all that in the main loop, while I could just send all the sounds check in a sub-function)?

Complex logic can result in complex code. You normally divide problems in repeatable task that are functions. Stuff being done by functions is very good because is reusable.

But even good programming habits may still have somewhere a function that have 6 levels of indentation.
This is not great problem, because your IDE will help you identity where a block end or start, and warn you if you miss a }. Also you can always comment the } in a pascal style:


for(players=0;players<p->max;players++){
  updates = nts[players];
  while(updates--){      
      packetlen = calculatePacketLen(packets[update]);
      for (t=0;t<packetlen;t++){
           packets[t] = bin2net(packets,t);
      } // for all packets
      sendUpdate(packets[update]);      
  } //  while all updates
} //for all players

In a ginormious code block with lots of indentation, these comments in } may help you.
Anyway most of the help come from a good IDE.

If you really want to cut down the complexity, you can search a blocks that can be turn into functions.


for(players=0;players<p->max;players++){
  updates = nts[players];
  while(updates--){      
      processAllPacket(packets, update);
      sendUpdate(packets[update]);      
  } //  while all updates
} //for all players

note: I have not programed in C in more than 10 years, so disregard anything in this code that looks lame.

note: The moment your code in unmanageable, you are doing something wrong.

HRose: You cannot avoid all those if’s. But there are ways you can remove some of them, if the condition fits.

For example, in your game you have different walking sounds based on the terrain under the character. I assume that you are currently waiting until you are almost ready to play the sound, and then performing the if or switch statement to arrive at the correct WAV filename to play. Something like: if (terrain==“grass”) then stepSoundFile=“grassStep.wav” else if …

The first thing I’d do is to put the entire if statement into a function, and have the function return the filename with the input terrain. This changes nothing yet.

The next thing I’d do is to change the terrain to be an integer instead of a string. You might be doing this already, so good. This still changes nothing: if (terrain==1) return “grassStep.wav”. Still an if. (It’s a much quicker check than a string comparison, but whatever.)

The next thing is to make sure the range of the terrain numbers lie from 0 to some positive number. Why? So that you can use terrain value as an index in an array. What array? This array (not real C code, I’m rusty):
char** stepsSound = {“brickStep.wav”, “grassStep.wav”, “sandStep.wav”, “astroturfStep.wav”};

Now your terrain step function can just do this: return stepsSound[terrain];

Look! No checking!

When this idea is taken to the extreme, you end up with some very unreadable code that runs pretty fast.

By the way, I would have organized the arrays around the terrain first: char **grassSounds = {“grassStep.wav”, “grassCrouch.wav”, “grassStand.wav”, …}; And I would pass in pointers to the correct terrain array based on the current terrain into any sound processing functions. They would then know the correct index into the array to pull out the sound they want. But that’s just me.

Anyways, that’s one idea, but it illustrates the power of data structures…everyone’s favourite 1st year or 2nd year CS course. Actually, this is more of adapting your data for incidental use by other data structures.

In Java, I would be able to keep the type of terrain as a string, and use a HashMap:
stepSoundMap[“grass”] = “grassStep.wav”;

If I put there a
#DEFINE Grass 1

this works the same?

The first thing I’d do is to put the entire if statement into a function, and have the function return the filename with the input terrain. This changes nothing yet.
I’d put ALL the sound code entirely off the main loop and its own function.

For example right now it’s:
else if(key[KEY_RIGHT])

and then begins the if cycle to check if music is enabled and then to pick the sound to play. After that it calls
move_hero(RIGHT);

That moves and draws the screen.

So instead of having the sound code in there, I’d rather call a function I made:
play_sound(RIGHT);

And have that function checking if sound is enabled, checking terrain, and then playing the sound. It returns when it’s done.

Yes, it is a good practice to use “#define TERRAIN_GRASS 1” to declare all of your constants. This way, you can easily change the value of the constant without needing to change all the code that uses it. Of course, this doesn’t help you if you need to split GRASS terrain into 2 other types…

And yes, finding the correct boundaries when separating code into little reusable functions/methods takes some practice, and can lead to different opinions. The “right” way is usually the one which is more reusable, or at least doing more obvious things, and has the least side effect.

Static class member variables are almost always superior to #define.

Only if your language sucks, you’re operating under library constraints, or you don’t have enough time to make it better.

Another quirky thing I was thinking about: say that there’s a poison effect that deals damage once every two movement turns.

Now I could implement this with another if…else cycle as usual, and check every time, but this gets really silly when in every loop you have to check for millions of effects, active spells and powers and whatnot.

The idea is that the check should be “installed” in the main loop only when active. So that the code “appears” only when one of the modules is on (this one would be “poison”). Otherwise it’s really silly that every loop I have to check everything that MAY happen within the WHOLE game.

So how you deal with this stuff? Is my way of thinking correct and there’s a way to swap pieces of code in and out a static loop?

You perhaps can build something like a list of effects. Having the elements in the list a “lifespan” of # of turns or conditions to get removed from the list.

Worst case scenarios, you will have a ginormeous switch() case somewhere that apply the right function to every item based on his type. There are better ways. There are riskier ways, like having in the list a “pointer to a function”, so the switch() case is not really needed. This is basically reinventing oop…


struct effect {
  int  lifetype;  
  function * apply;
  int deleted = 0; 
  struct effect * next; // ==null => end of the list.
}

Your language/libraries may already have functions to deal with list of things.

This is my opinion. Maybe not the best idea ever. Lets wait for other opinions.

Lets invent oop!


virtual class effect {
  int  lifetype;  
  virtual function apply();//TODO: define what it does
  virtual function lifespan(); //TODO: define how is removed
  int deleted = 0; //marked for deletion
  class effect * next; // ==null => end of the list.
}

class doubledamage extends effect {
    function apply(){
      player->damageEfective = player->damageBase * 2;
   }
   function lifespan(){
          this->lifetype--;
         if( this->lifetype<0){
           this->deleted = 1;
         }
    }   
}




Seems that the sound of my idiocy has muted other voices :P

overtime happened :P Ok I’ll be brief because I only skimmed the reply:
On advice I can give to HRose is to study a tutorial on Computer Simulations. A quick google gave me this book. This course deals with simulating the behaviour of a system over time, with random (but tweakable) inputs. It’s the way I’d write a game from scratch in my mind.

By the way, Teiman’s event list shows up in chapter 4 of that book.

Years ago, a friend of mine found a presentation that some self-taught programmer would give at anime conventions about “How to program games.” As could be expected, he had no business telling anybody else about how to program, and made a lot of bold pronouncements about how various basic features like functions and loops were unnecessary complications.

But the one thing I distinctly remember is his central piece of advice: “programming is just a series of if statements”. He didn’t mean that conceptually, he meant that literally: his entire run() loop was just filled with a series of if statements. I don’t think he even nested them. It was glorious and horrifying. Note that this was in about 2005 or so.

HRose: if your program is just a big block of if statements, you are doomed, because it will be impossible to maintain.

One old friend of mine had an awesome quote: “object-oriented programming is doing nothing in enough places.” That’s kind of true. The whole point of programming something large is to break it into pieces that have only limited interaction with each other.

I will reiterate my suggestion to look at my “Holofunk” open source project for an example. That project is a Kinect / Wiimote live looper that integrates the Kinect SDK (for visual and gesture input), an open source Bluetooth Wiimote library (for Wiimote button detection), the .NET XNA game library (for rendering), and the BASS audio library (for sound recording and playback).

It’s really only a 2D application at the moment – it uses only sprites for rendering, so it’s pretty simple. It’s a small enough amount of code that you might be able to take it all in with a night or two of code reading. Happy to walk you through it if you have questions.

Internally, I broke it into six separate libraries of code:

  • Core: this defines some basic data structures (like my minimal 2D “Transform” struct, consisting of a position and a scale, and like my “Clock” class, which defines time in terms of audio samples – all my audio timing is driven from the audio clock).

  • Holofunkinect: this library handles communication with Kinect, takes depth frames and color-codes them to highlight players (using code I cribbed from existing Kinect SDK samples), and exposes the position of the player’s hands (needed for gesture control).

  • HolofunkBass: this library handles communication with the audio library I’m using; it manages audio buffers, has callback routines that the audio library calls when it gets new microphone data or needs to mix sounds together. This library is particularly tricky because there is multithreading involved: the sound library has its own high-priority thread for handling audio data, and it needs to be able to communicate with the main game (running on the GUI thread) without waiting. So there are two queues; when the main thread wants the audio thread to do something, it adds an entry to one queue, and vice-versa for the audio thread communicating back to the main thread; and each side takes all available items off of the queue whenever it happens to run (because of audio callback).

  • SceneGraph: this defines a small, simple little scene hierarchy, so I can create a structure which describes all the visual elements on the screen. (e.g. “first create a SpriteNode for the background, then a SpriteNode for the semi-transparent player depth image, then a little one for each hand…”) Then I have a SceneGraph.Render command that walks down the whole tree of visual elements, drawing them all at the right positions. I can then group things together so they all draw relative to a common base position, I can hide and un-hide visual elements depending on gameplay logic, etc.

  • StateMachine: When defining the gameplay logic, it’s often easiest (for me) to think about “the game starts in Playing state; when the user presses the trigger, it goes into Recording state; when the user lets go, it goes back into Playing state.” This is a “state machine” design, which lets you design the UI interactions in terms of very clear “when in state A and event X happens, do action Q and go to state B” logic. The StateMachine library provides some infrastructure for that.

  • Holofunk: the game itself. In the Holofunk library, I have the main game code, including a HolofunkSceneGraph (which is just a SceneGraph that has game-specific setup code) and a HolofunkStateMachine (which is a StateMachine that encodes the Holofunk UI behavior). The main Holofunk class has an Update() method and a Draw() method; these are called by the XNA library 40 times a second to do their thing, and “their thing” mainly involves calling into HolofunkBass to check for new sound activity, and calling HolofunkSceneGraph.Update() and HolofunkSceneGraph.Render() to drive the UI.

The point here is that a full game consists of a number of systems – sound, rendering, game state and gameplay, and input handling – and if you can split each such body of code into a separate library with a relatively small interface, you then make it much easier to solve all the problems, because each problem has a specific place where it should be solved. The “big bag of if statement” code is impossible to maintain because the rendering code, the input code, and the gameplay code are all so tangled together that you can’t fix one issue without destabilizing several others. That’s why modularity is the secret of large-scale software development… solve each problem in one and only one place, and don’t let any one area of the code have access to ANYTHING that isn’t its specific responsibility, since then you can change all other areas without fucking up that one.

I did, for like a few seconds. I’m asking very basic things, and you’re telling me to look at a source code with plenty of files in a framework I’ve never used. I don’t even know WHAT I should look for. It’s just a bunch of files for me.

And I’ll say again that I’m going to use Python and libtcud to write a roguelike. In ASCII (but hopefully with full colors, Unicode, bigger screen and mouse support to hover on things and read what they are). I have a bunch of tutorials, some of them in different languages but that I (hope) should be able to port to Python when necessary.

My first mid term goal after putting down the barebone structure is to code a combat system modeled around the pen&paper RPG Harnmaster (that in my mind is a simple task since pen&paper combat is just a bunch of options and a bunch of basic math, but what seems simple always reveals to be hell). I want deep pen&paper rules, with dice rolls, in a computer roguelike.

I’ve asked this guy who made a really pretty and graceful roguelike in Pyhton to give me the source code. It seems he will, so hopefully I’ll be able to eventually understand it.

Short term I’m reading a bunch of books on C++ and Python to learn the languages and be ready to put down some code.

So while I’m interested in some general game programming conventions, most of what I’ll need is probably more specialized (I think the real mess will be to handle maps, write an editor of sort, do AI and pathfinding and so on).

I won’t even have to deal with sound, or rendering, for the most part (if not learning how the library works), or any platform specific thing (I hope Python and the library hide all that completely).

My whole point for this project (that is not finite and would take me many lives to get close to complete it, so if it works I’ll keep expanding it) is to use a so minimal presentation using ASCII and classic roguelike mechanics so that I really can focus on game logic, rules and content. Instead of wasting years to understand the framework, engines and whatnot.

My maybe naive idea is that once I handle how to draw simple windows, maps and menus in ASCII, all the remaining work is ALL GAME.

15 years ago it was the opposite. Writing a game meant that you had to know the hardware. How to draw stuff on screen, how to get input and so on. If you wanted the game to have an UI you had to code it from scratch. You had to study the video modes, how to handle palettes, refresh, buffering. That small RPG project based on a SNES Final Fantasy system would have made me spend YEARS to finish the “engine” and tools. Then after all those years writing menus, sprite animations, map handling and so on, I could have hoped to finally put some content in there and make my game.

That’s the part I hope to skip, since ASCII hopefully handles in very simple ways all the primitives I need to deliver the full game.

Returning to the problem:
my idea is that there should be a way (since it’s nothing fancy in computer logic) to tell a program to look inside a box:

  • Is the box empty? If so, skip and carry on.
  • Is there something in the box? Proceed calling each “object” in the order you find them.

So the process goes looking into the box. If empty it does nothing. If it find the “poison” object, it executes the poison effect and then continues.

That’s my idea of “swapping pieces of code in and out of a loop”.

Is this possible in the simple way I’m describing it (and so avoiding to build every virtual object inside the box and checking one by one if they are active)?

I don’t understand any of this. In my example with the box = list, a poison effect doesn’t need an explicit lifespan. Other portions of the game can trigger the poison effect (say you get the “poison” flag in combat, but now it keeps being active off combat, in a different game/system loop) and whether is cleared or not is not a problem of who calls the poison function, but of the function itself.

What is the “switch” for?

[1]

When a user open a box, you can create a temporary array (tmp) with a list of pointers to objects.

Then you can run a loop for them, to call his “onLoot” event “for(t=0;t< tmp->lenght; t++) tmp[t]->onLoot();”.

For most items, onLoot will do nothing. Since don’t make sense for a health potion to do anything wen is looted. Very rarelly a object will do anything in that case (your example is weird).

onLoot is just a method implemented in the objects you use, since is implemented in these objects, you don’t have to do anything at all.

If the language you use is decent (C++, Python), you probably can have a base objects where onLoot is already implemented as a method that does nothing, and you can do onLoot do something only wen you need to do something.

Hope this make sense for you.

May look like this


class xpBonus extends effects {
  var xpBonux = 10;
  function activate(player){               
               player.addXp( effect[t].xpBonux );                    
  }
}

function runEffects(effects){
      for(t=0;t<effects->lenght;t++){           
             effects->effect[t].activate();
      }    
}


class Box extends Activable {

  function onActivate(player){
       class  * effects;

       effects = this->generateEffectsForThis(player);
       runEffects(effects);

       //TODO: clean effects memory calling destructors?       
  }

}

I don’t understand any of this. In my example with the box = list, a poison effect doesn’t need an explicit lifespan. Other portions of the game can trigger the poison effect (say you get the “poison” flag in combat, but now it keeps being active off combat, in a different game/system loop) and whether is cleared or not is not a problem of who calls the poison function, but of the function itself.

What is the “switch” for?

Sorry. I mixed two ideas, making my comment even more confusing of what was already.

My idea was, [1], but with a linked list. Linked list can be interesting if this list of items that do things are not temporal at all, and may grown and shrink as more items are added. You can insert a new item in the middle with a linked list, and you can’t do that with a array.

I have said that I mixed two ideas.



//idea 1, crappy switch

function runEffects(){

   effect * head;
   head =  box->effects;
   while(head!=NULL){

         type = head->type;
        
        if( head->removed )
        switch(type){
              case "radiation":
                 player.health--;
                 head->time++;
                 if(head->time > effect[t].lifespam)  
                      head->removed = true;
                 break;
             case "xp":
                 player.xp += head->xpBonus; // player.addXp( effect[t].xpBonux );                    
                 head->removed = true;
                 break;
        }

        head = *head->next;
   }


}



//idea 2, oop

class xpBonus extends effects {
  var xpBonux = 10;
  function activate(){
               player.xp += this.xpBonus; // player.addXp( this.xpBonux );                    
               this.removed = true;
  }
}

function runEffects(){

   effect * head;
   head =  box->effects;
   while(head!=NULL){  
         head->activate();
   }
   * head = *head->next;
}

All of this is pseudocode, because I have not programmed in C++/C in a million years, and want to stay abstract with simple code.

I’m not saying there’s literally a box with poison in it. I’m saying figuratively ;)

The “box” is like a piece of code, as if I say that a variable is a box of a certain type containing a certain value.

In this case I mean to tell the code to look into some programming object, and do whatever it finds in it.

I’m asking if a similar (or equivalent) programming construct exists. Instead of having code checking for every possible status, I want it to look into some programming container and find everything it’s in there.

I’m saying that the programming language is a Zelda character opening a box and discovering what function(s) it contains. I’m thinking in code and logic, not in the context of the game. In the context of the game I simply made an example about a poison effect. In this case the “box” is a box containing possible statuses affecting a character. In the loop the program checks the box to see if it’s empty or not. Say that the character got poisoned, it means that in the code the “poison” object was previously put inside the box (could be operator overloading?). So the program looks in the box and sees that it’s not empty, and that it contains something called “poison”. So it calls the “poison” function. If instead of poison it found a buff to strength, it would have called the buff to strength, or whatever effect. This means that the program doesn’t need to look specifically for a specific object in the box to see if it’s there or not. Otherwise it’s as simple as: if (poison = 1)

I don’t want to do that. I want to avoid to check specifically for every possible thing one by one. And I want the “box” to be a virtual piece of code that may contain things or not (like an array). Whatever thing it contains, it calls it.

I don’t know arrays well. But ideally you could make this “box” as an array, and for every object that is put inside it, you increase its index: box[i], where “i” is the number of objects it contains.

That way, if “i” = 0, then it means it’s empty. If it’s not you do a “while” cycle so that it executes something and decreases the array by 1 (till the box is emptied again).

That kinda works. But I have two questions.
1- Is that a good programming practice for that kind of purpose?
2- How can I put “function calls” inside an array, or achieve a similar effect?

If I’m understanding correctly, what you want is what would be called a function pointer in C or function object in OOP (what Teiman is essentially describing). The basic idea being that you have data and you are going to invoke a function on the data but the actual implementation of the function is unknown by the caller, but it can be called by a standardized interface.

The usage is kind of cryptic in C, but in Python you can simply assign functions to variables and then call them through the variable, so it should be as simple as:


import somepackage;

box = [ somepackage.poisonfunc, somepackage.strfunc, somepackage.speedfunc ]

...

for func in box:
    func(parm1, parm2)

where ‘poisonfunc’, ‘strfunc’, and ‘speedfunc’ are functions in ‘somepackage’ that take two parameters (it works without the package qualifier too, if they’re local functions). Since Python is dynamically typed, it’s up to you to make sure that the parameters you pass when you call it match what the functions are defined with.

No, no. Objects are the kings of the kingdown*. You don’t tell them to do things, that is procedural. You give them messages, and make them gifts, and THEM the objects may do things with these messages/data.

Is… liberating. You don’t have to think how objects work, just how to pass them the message.

I’m asking if a similar (or equivalent) programming construct exists. Instead of having code checking for every possible status, I want it to look into some programming container and find everything it’s in there.

This is what OOP do for you. You have a triangle, square and circle objects of the base class “shape”. and you call the method ->draw(); you don’t know how draw is implemented, and you know is always called draw.

Suppose you are writting a SVG renderer. You can have a array of shapes, and you just call the draw method of each. You ignore how line or circle is implemented.

I’m saying that the programming language is a Zelda character opening a box and discovering what function(s) it contains. I’m thinking in code and logic, not in the context of the game. In the context of the game I simply made an example about a poison effect. In this case the “box” is a box containing possible statuses affecting a character. In the loop the program checks the box to see if it’s empty or not.

By calling ->draw(), you open the box. If your structures are dynamic. You only need to call ->draw() for objects that exist. If you don’t have a star shape figure, you will never call ->draw() for it. If theres 3 shapes, you have 3 method invocations.

I don’t know arrays well. But ideally you could make this “box” as an array, and for every object that is put inside it, you increase its index: box[i], where “i” is the number of objects it contains.

If you don’t like arrays (and arrays are one of the most basic programming block pieces, so you must learn to use them) you can use stacks. Stacks have a interface (push and pop), and are easy to understand because have a physical counterpart… real world stacks of objects.

That kinda works. But I have two questions.
1- Is that a good programming practice for that kind of purpose?

I think is good that you care if your style is good. But you understanding your code is more important than it being good. Plus you will improve your style with experience. But you will only get experience by writting bad code. So you will probably write a lot of bad code before you can start writting good code.

2- How can I put “function calls” inside an array, or achieve a similar effect?

In C you can have a static array with 200 elements of pointers to function. You can have a for() to move in this array checking if the element is 0, if is non-cero call the element as a function, perhaps using some parameter.

int (*p[200]) (struct Player *player);

if (p[t])
pt;

(a simple improvement would be to have this array be dynamic, so you are not limited to 200 effects).

update:

  • RepoMan friend say “object-oriented programming is doing nothing in enough places.”. But this shit is deep, plus you can write complex programs without even being near to understand it. It means that Objects thenselves are lazy, and want to “outsource” all the work to other objects or api functions as much as possible, to be as empty as possible. Too busy objects that do a lot of different stuff, may possible doing stuff should not be doing themselves. I think bad code is un-avoidable, so I don’t mind much if bad things happends to good code.

Yes, it’s perfectly possible to iterate over an array of dynamically created objects and call methods on each object, where the implementation varies by the type of object. Doing it C is hard, which is part of why vanilla C is way less possible than it used to be.

I don’t know how to say this in a way that you won’t be likely to take offense to, but you don’t need information on basic game programming. You need advice on basic programming: modularity, functions, encapsulation, data structures, good ways to handle control flow. When you say “I don’t know arrays well”, that’s a sign that you’re missing important fundamentals - an array is about the simplest data structure. The advice RepoMan’s giving you - look at this simple, but fully functional and well implemented code - is sound.

If you want to start at bare metal C, you have a lot to learn before you get to game-specific stuff. Jumping into raw C without fundamentals is a recipe for frustration and bad code. If you don’t know arrays, you shouldn’t try to use function pointers.