'Structured' programming in Lite-C

Posted By: Joozey

'Structured' programming in Lite-C - 07/08/09 21:02

To all those who are new to structures, or trouble with errors, or get lost in yer own spaghetti, or because you just like to read this, I present you a solution I commonly use to keep things structured with as few memory leaks, code spaghetti and unpredictable behaviour as possible.

First, an example code about structures.
Next, the explanation about structures.
Follows, the way I do it, and an explanation.

Code:
typedef struct {

  var itemNumber;
  BMAP *image; //pointer to bitmap
  String *name; //pointer to string

} Item;


typedef struct {
  
  Item item1; //no pointer, actual object!
  Item item2;

} Inventory;


void main() {
  Inventory *inv; //pointer to inventory
  inv = malloc( sizeof( Inventory ) ); //assign a new inventory
  
  //first you do after allocating a new structure, is fill all its parameters!
  //Otherwise you can end up with some nasty unpredictable errors

  //fill item1
  //arrow (->) means you call from pointer "inv" to its member "item1"
  //point (.) means you call from object "item1" to its member "itemNumber" (or "image", "name")
  inv->item1.itemNumber=0;
  inv->item1.image = bmap_create("bla");
  inv->item1.name = "bitmap of item 1";

  //same for item2
  [...]

  //for the sake of this example, let's remove this inventory again
  free( inventory ); //remove the inventory (and automatically the items!)
  
}



You see, the inventory can now be removed by free(), and it'll remove the items along automatically as they are part of the inventory structure. If the items were pointers, you had to remove the items manually before removing the inventory. Else their pointer will be lost and thus cause a memory leak.

If you look further, you see that the item structures have a bitmap and string pointer. While the item structures are removed along with the inventory, the bitmaps and strings will not! So, before removing the inventory, you will have to remove the bitmap and strings of the item structures first in order to prevent memory leaks.

As you see, this causes quite some hassle, and is pretty "dangerous" as you may easily oversee a memory leak. Your memory will slowly fill with 'floating', unreachable data structures, often freezing your game after a while, or give other unpredictable results.

To solve this requires some dedication to tidy programming. What I do, is give EVERY object I make a new file. This should be consequently done, no exceptions, to keep your code overviewable and tidy. Each objects always gets a creation function, a remove function, and possibly (commonly) a run function.


Now, another example code, the way I usually do it:

Code:
//Item.c
typedef struct {

  int itemNumber;
  BMAP *image;
  String *name;

} Item;


//a function to visualize an item on a panel
void item_visualize( Inventory *inventory, Panel *panel ) {
  panel->bmap = inventory->image;
}


//Item creation function, returns pointer to the newly created Item
Item *item_create( int number, String *imageName ) {
  
  Item *item = malloc( sizeof( Item ) );
  
  //always fill ALL the item's properties immediately after!
  item->itemNumber = number;
  item->image = bmap_create( imageName );
  item->name = imageName;
  
  return item; //return the new item back
}


//function to remove an item
void item_remove( Item *item ) {
  ptr_remove( item->image ); //remove bitmap first
  ptr_remove( item->name ); //remove name
  free( item ); //THEN remove item
}



Code:
//Inventory.c
typedef struct {
  
  bool alive;

  Panel *panel;

  Item *item1;
  Item *item2;
  
} Inventory


//function to keep the inventory running and catch input
void inventory_run( Inventory *inventory ) {
  
  //infinite loop
  //in order to check if the object still exists and prevent empty pointer errors,
  //you can best add an "alive" state, just add an "alive" boolean in the structure, and check it here
  //after the while, call the inventory_remove function to fully destroy
  //We simply make an inventory_kill() function, and set the boolean to false to kill the object
  while( inventory->alive ) { //as long as the inventory is alive, keep loopin'

    //when we press key_1, show item1
    if( key_1 ) {
      item_visualize( inventory->item1, inventory->panel ); //remember this function in the item code?
    }

    //when we press key_2, show item2
    if( key_2 ) {
      item_visualize( inventory->item2, inventory->panel );
    }

    wait( 1 );
  }

  inventory_remove( inventory ); //the object is dead, remove it!
}


//function kill
void inventory_kill( Inventory *inventory ) {
  inventory->alive = false;
}


//function to create a new inventory
Inventory *inventory_create() {

  //allocate new inventory structure
  Inventory *inventory = malloc( sizeof( Inventory ) );
 
  //once again, fill all its parameters immediately after
  inventory->alive = true; //we set this object to alive first!
  inventory->panel = pan_create("bla");
  inventory->item1 = item_create( 1, "item1.tga" ); //easily create an item
  inventory->item2 = item_create( 2, "item2.tga" );

  //in addition to the item code, the inventory code catches player input
  //this run function handles this input, and loops infinitely
  inventory_run( inventory );

  return inventory; //give back the inventory
}


void inventory_remove( Inventory *inventory ) {
  item_remove( inventory->item1 ); //remove item1 first
  item_remove( inventory->item2 ); //remove item2
  ptr_remove( inventory->panel ); //don't forget to remove the panel too
  free( inventory ); //THEN remove inventory safely
}



Code:
//main
#include "Item.c"
#include "Inventory.c"


void main() {

  //create a new inventory!
  Inventory *inventory = inventory_create();

  //main loop (a little dirty, but forgiveable for now :) )
  while( 1 ) {
    
    //when we press q, remove the inventory
    if( key_q ) {
      inventory_remove( inventory ); //this should go smooth without errors...
    }

    wait( 1 );
  }
}



The biggest fight is against pointer management. You can easily end up under heaps of empty pointer errors, or worse, random crashes that occur at unpredictable times, or even more worse, errors pointing to parts of code that aren't wrong at all! Yes, Lite-c has its bad moments, but they can be overcome.

So, quite the hassle for a bit of code that's sort of tidy and emulates a part of object orientation, but this way I discovered to be working quite well when your project gets big. Too big to handle.

All comments and critics are welcome.

Regards,
Joozey



P.s.
The code represented above is not tested at all. It's about the concept, not about giving away a piece of inventory code. IF something does not work for you and you fail to see why, feel free to comment, I shall change it in the example!
Posted By: Widi

Re: 'Structured' programming in Lite-C - 07/08/09 21:18

Thanks for that example, i am not so good with structs now. But with this Code i can learn more about it.
Posted By: VeT

Re: 'Structured' programming in Lite-C - 07/08/09 21:20

Very nice explanation, Joozey. wink
Posted By: Joozey

Re: 'Structured' programming in Lite-C - 07/08/09 21:20

I did my best to explain clearly. Feel free to point out any oddities and parts that are hard to understand.

Good luck with them structures smile.

Regards,
Joozey
Posted By: 4gottenname

Re: 'Structured' programming in Lite-C - 07/09/09 09:54

Thank you so much for posting that! Been trying to understand and use them structs last couple of days and this will realy help a lot. laugh
Posted By: Cowabanga

Re: 'Structured' programming in Lite-C - 07/09/09 11:50

Great explanation, thanks!! laugh smile
Posted By: Joozey

Re: 'Structured' programming in Lite-C - 07/09/09 12:44

The most important thing when starting to program like this, is separating responsibilities clearly over your different objects. The only object that can make the Item visible on a panel, is the Item itself. Therefore you need to create a method in the Item "class" (I name each separate object in a file a class, but I'm still waiting for Lite-C to introduce the real deal with classes!!) to visualize the Item (item_visualize()). You may then call this function from every other "class" that uses an Item. If you, for example, start assigning an Item bitmap to a panel bitmap in a different class without calling the item_visualize() function, you'd get a big mess very soon.

Create responsibilities only where they apply, and only perform calls on those responsibilities in parental "classes", never start fiddling with the parameters and logic-functions from other classes outside the class itself.

Mind you, there are a lot of different ways to distribute responsibilities. Those 'ways' are called Design Patterns. The one I represented is just one way, but there are many more. If you know them well, you can easily make maintainable, extendible and overviewable source code.
Posted By: PigHunter

Re: 'Structured' programming in Lite-C - 07/09/09 14:08

Thank you for this explaination of structures, Joozey. Any tips on how to use add_struct for game_save?

Thanks again!
Posted By: Joozey

Re: 'Structured' programming in Lite-C - 07/09/09 16:18

I'm affraid you'll have to figure that out yourself, as I've never worked with add_struct smile. But for what I read, you can easily add a save function for an object with this function.
Posted By: PigHunter

Re: 'Structured' programming in Lite-C - 07/09/09 16:35

From what I've read, I don't think anyone has worked with add_struct before.
Posted By: GorNaKosh

Re: 'Structured' programming in Lite-C - 07/09/09 17:05

I was trying to deal with add_struct and game_save/game_load the whole day long, but I don't get it work!
One Problem is, that when you use the game_load function, there musst exists the same count of initialized structs in the script like when you saved the game. And also I have no idea where the pointer of the saved memory area are after game_load ...

I'm really confused an frustrated about that save management!
Posted By: Widi

Re: 'Structured' programming in Lite-C - 07/16/09 08:58

I have a question about allocate Memory with: malloc(sizeof(STRUCT));

Code:
typedef struct
{
	var    koor_x_abs;
	var    koor_y_abs;
	var    koor_x;
	var    koor_y;
	var    bombenreichweite;
	var    erzeuger_id;
	var    kicker_id;
	var    speed;
	PANEL* panel;
} BOMBE;



typedef struct
{
	var    koor_x_abs;
	var    koor_y_abs;
	var    koor_x;
	var    koor_y;
	var    start_koor_x;
	var    start_koor_y;
	var    anz_leben;
	var    unverwundbar;
	var    richtung;
	var    bombenanzahl;
	var    bombenanzahl_max;
	var    bombenreichweite;
	var    speed;
	var    speed_orginal;
	var    anz_schuhe;
	var    tod;
	var    id;
	var    ki;
	var    sp_status;
	var    negativ;
	
	var    r;
	var    l;
	var    u;
	var    o;
	
	var    t1;
	var    t2;
	
	var    joy1_aktiv;
	var    joy2_aktiv;
	
	var    t1_gedr;
	var    t2_gedr;
	
	PANEL* panel;
	
	BOMBE  Bombe[Anz_bomben];
} PLAYER;

PLAYER  Player[Anz_spieler];



You can see i want to use a array from the Struct (Anz_spieler = 8).
How do i use now malloc?

Player = malloc(sizeof(PLAYER)); --> is this right?
Posted By: Joozey

Re: 'Structured' programming in Lite-C - 07/16/09 09:59

You can create dynamic arrays this way:

Code:
PLAYER *player = malloc( sizeof( PLAYER ) * Anz_spieler );



A multidimensional array would go like:
Code:
PLAYER **player = malloc( sizeof( PLAYER* ) * players_y );

for( i=0; i<players_x; i++ ) {
  player[i] = malloc( sizeof( PLAYER ) );
}


Posted By: Widi

Re: 'Structured' programming in Lite-C - 07/16/09 10:15

Thanks a lot, will go test it...
Posted By: TrQuocAn

Re: 'Structured' programming in Lite-C - 07/24/09 03:08

excuseme !

But can we use the Array without malloc function ??

for ex :

Code:
PLAYER  Player[Anz_spieler];
// Not use the malloc here because Player is a array not pointer !
Player[1].r = 2;
Player[3].u = 3;
....


Posted By: EvilSOB

Re: 'Structured' programming in Lite-C - 07/24/09 09:19

I think so, but "Anz_spieler" cannot be a variable, it must be an
actual number, or a '#define'ed constant number.
Posted By: Germanunkol

Re: 'Structured' programming in Lite-C - 07/24/09 13:48

Funny, I thought of pretty much the same method (creating create_ and remove_ functions for all structs) the other day. Good to know someone has tested it!

Joozey, what's the " ** " in your last post? I've never seen that... what does it mean?
Posted By: EvilSOB

Re: 'Structured' programming in Lite-C - 07/24/09 13:57

Pointer to a pointer. (The start of an array of of pointers)
Cause the ENTITYs in the array are really only a pointer to an object, you need an array of pointers.
Posted By: Joozey

Re: 'Structured' programming in Lite-C - 07/25/09 01:21

Quote:
Funny, I thought of pretty much the same method (creating create_ and remove_ functions for all structs) the other day. Good to know someone has tested it!

And good to know someone else has got the same idea ^^ must be some use in this way of programming then! grin.

Quote:
Joozey, what's the " ** " in your last post? I've never seen that... what does it mean?


As evil says.

*A = [0][1][2][3][4][5][6] //array, where pointer A points to [0]
**B = [A[0]][A[0]][A[0]] //array where pointer A points to [p[0]]

A is a normal array with 6 indexes containing some value.
B is a normal array with 3 indexes, but each containing a pointer to array A. Doesn't need to be the same array, just a new array of type A.

So, B is a pointer to an array containing pointers to an array. Hence the two asteriskes. The compiler will puke with only one asterisk.
Posted By: Pappenheimer

Re: 'Structured' programming in Lite-C - 07/26/09 12:39

Joozey, you're explanations are very appreciated!
I have an additional question though, hope you don't mind.
I'm still thinking in ways of c-script how to solve a certain task.
I read your codes and explanations the third time, and I think my problem is that I think more 'material', as you might know or not, I programed a fish game where the player collects fishes in a swarm to keep an evil fish in a safe distance.
This 'collecting' might be similar to that of an inventory.
At the beginning of a level, I place the fishes in the level, the swarm gets an array to save the handle of each fish that has been collected while the fish saves in a skill the number of its place in the array, and when the fish leaves the swarm, because it dies or it flees because the evil fish comes to near to it, it resets it place in the array to zero, and its skill as well.

What advantage has a struct as you use it in your example to the way that I just described?
Posted By: Joozey

Re: 'Structured' programming in Lite-C - 07/26/09 13:44

The advantage is code overview, more logical division of responsibilities and doesn't waste unused resources. This stuff with skills has always bugged me in c-script. What does an entity object do with an inventory value of the player? That's not making sense. Instead, the player should keep track of the fishes (entities), and manage their index position in the array, because the player has the fishes. The fishes shouldn't care whether or not they're in an array. They should just do their own thing.

So you lay the responsibility of the fish management to the swarm object, and the fish behaviour to the fish itself. The player tells the fish where to swim, and the fish will do the rest. You probably don't want to make an entity object for the swarm just to have the skills available. Instead, you can make your own structure with only the data you need. An entity has more data than just the skills that are then unused. Would be confusing and wastes resources.

I hope it's a bit clear.
After re-reading my first post I have doubts that everyone can understand it grin.

Regards,
Joozey
Posted By: maslone1

Re: 'Structured' programming in Lite-C - 07/27/09 05:27

Very clear!

Thanx for your cool thread, and detailed explaining how to use "structured programming".

Have a nice day joozey!

cheers
Marcel
Posted By: Helghast

Re: 'Structured' programming in Lite-C - 08/18/09 11:02

best thread ever! make it a sticky or add this to AUM!!

thanks Joozey, you explained (several times) over MSN how structs work, so I got a head start tongue the array and multi dimensional array structs still are a bit over my head, I'll have to look a bit more into that I guess...

I decided to re-program/structure my game using these methods.
Might wanna go as far and convert my ragdoll code using this... hmmmmm...

anyway, thanks! keep up the good job!

regards,
Posted By: alwaysblack

Re: 'Structured' programming in Lite-C - 08/23/09 10:47

Hello, and thank you for making this thread, it's very interesting.

I'm trying to learn about the topic you've raised here, but I'm struggling to get my code to compile. Can you tell me what is wrong with these lines that would prompt a syntax error?

Click to reveal..

//a function to visualize an item on a panel
void item_visualize( Inventory *inventory, Panel *panel ) {
panel->bmap = inventory->image;
}

Posted By: Joozey

Re: 'Structured' programming in Lite-C - 08/29/09 16:37

@alwaysblack:
Not from that piece right away, I experience no trouble in assigning a bitmap to a panel. It would be helpful if you can paste the message and some more relevant code.

Regards,
Joozey
Posted By: WapiAchak

Re: 'Structured' programming in Lite-C - 04/02/10 13:34

hi Joozey, great thread ! I can see structs more clearly now.

I understood how you deal with structs, but I have a little prob with this part :

void item_visualize( Inventory *inventory, PANEL *panel ) {

panel->bmap = inventory->image;

}

when I try to compile the code I've the message : 'image': is not a member of 'Inventory'


so I can't call the function like this : item_visualize( inventory->item1, inventory->panel );


I modified the part like this :


void item_visualize( Inventory *inventory, PANEL *panel ) {

panel->bmap = inventory->item1->image;

}

But it's not a good way for me. Can you tell me what's wrong ?

Regards,
WapiAchak
Posted By: Rei_Ayanami

Re: 'Structured' programming in Lite-C - 04/02/10 14:46

Oh, haven't seen this thread...


Very many thanks, this can will make things much easier laugh
Posted By: Nidhogg

Re: 'Structured' programming in Lite-C - 04/02/10 15:22

Great explanation Joozey. Will defanitly find this usefull.
Posted By: Rei_Ayanami

Re: 'Structured' programming in Lite-C - 04/02/10 16:16

I don't get it...
Code:
typedef struct
{
	var    koor_x_abs;
	var    koor_y_abs;
	var    koor_x;
	var    koor_y;
	var    btype;
	PANEL* pnl;
} BLOCK;


/////////////////////////////////////////Actions//////////////////////////////////////////
//noch nicht Benötigt
////////////////////////////////////////Functions/////////////////////////////////////////
function create_new_level(var height, var lenght)
{
	var i, j;
	BLOCK **block = malloc( sizeof( BLOCK* ) * height );

	for( i=0; i<lenght; i++ ) {
		block[i] = malloc( sizeof( BLOCK ) );
	}
	
	for(i = 0; i<=height; i++)
	{
		for(j = 0; j<=1; j++)
		{
			if((i/height)*random(100) > 60)
			{
				block[0]->pnl.pos_x = 1;
			}
		}
	}
}


crashes in the block[0]->pnl.pos_x = 1;
Posted By: HeelX

Re: 'Structured' programming in Lite-C - 04/02/10 16:35

try

(block[0])->pnl->pos = 1;
Posted By: muffel

Re: 'Structured' programming in Lite-C - 04/02/10 18:55

There is on more thing which makes the allokation of memory safer.

if you use sys_malloc instead of the normal malloc, the engine will release this memory automaticlly when the game closes. However you should release the memory manually via sys_free(mixing the C methods with the engine methods causes errors).


muffel
© 2024 lite-C Forums