0 registered members (),
18,561
guests, and 5
spiders. |
Key:
Admin,
Global Mod,
Mod
|
|
|
'Structured' programming in Lite-C
#277335
07/08/09 21:02
07/08/09 21:02
|
Joined: Oct 2004
Posts: 4,134 Netherlands
Joozey
OP
Expert
|
OP
Expert
Joined: Oct 2004
Posts: 4,134
Netherlands
|
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.
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:
//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
}
//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
}
//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!
Last edited by Joozey; 07/08/09 21:08.
Click and join the 3dgs irc community! Room: #3dgs
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Widi]
#277343
07/08/09 21:20
07/08/09 21:20
|
Joined: Oct 2004
Posts: 4,134 Netherlands
Joozey
OP
Expert
|
OP
Expert
Joined: Oct 2004
Posts: 4,134
Netherlands
|
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  . Regards, Joozey
Click and join the 3dgs irc community! Room: #3dgs
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Cowabanga]
#277502
07/09/09 12:44
07/09/09 12:44
|
Joined: Oct 2004
Posts: 4,134 Netherlands
Joozey
OP
Expert
|
OP
Expert
Joined: Oct 2004
Posts: 4,134
Netherlands
|
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.
Last edited by Joozey; 07/09/09 12:46.
Click and join the 3dgs irc community! Room: #3dgs
|
|
|
Re: 'Structured' programming in Lite-C
[Re: GorNaKosh]
#278936
07/16/09 08:58
07/16/09 08:58
|
Joined: Aug 2007
Posts: 1,922 Schweiz
Widi
Serious User
|
Serious User
Joined: Aug 2007
Posts: 1,922
Schweiz
|
I have a question about allocate Memory with: malloc(sizeof(STRUCT));
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?
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Widi]
#278966
07/16/09 09:59
07/16/09 09:59
|
Joined: Oct 2004
Posts: 4,134 Netherlands
Joozey
OP
Expert
|
OP
Expert
Joined: Oct 2004
Posts: 4,134
Netherlands
|
You can create dynamic arrays this way:
PLAYER *player = malloc( sizeof( PLAYER ) * Anz_spieler );
A multidimensional array would go like:
PLAYER **player = malloc( sizeof( PLAYER* ) * players_y );
for( i=0; i<players_x; i++ ) {
player[i] = malloc( sizeof( PLAYER ) );
}
Click and join the 3dgs irc community! Room: #3dgs
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Widi]
#280749
07/24/09 03:08
07/24/09 03:08
|
Joined: Apr 2009
Posts: 39
TrQuocAn
Newbie
|
Newbie
Joined: Apr 2009
Posts: 39
|
excuseme ! But can we use the Array without malloc function ?? for ex :
PLAYER Player[Anz_spieler];
// Not use the malloc here because Player is a array not pointer !
Player[1].r = 2;
Player[3].u = 3;
....
|
|
|
Re: 'Structured' programming in Lite-C
[Re: TrQuocAn]
#280796
07/24/09 09:19
07/24/09 09:19
|
Joined: Feb 2008
Posts: 3,232 Australia
EvilSOB
Expert
|
Expert
Joined: Feb 2008
Posts: 3,232
Australia
|
I think so, but "Anz_spieler" cannot be a variable, it must be an actual number, or a '#define'ed constant number.
"There is no fate but what WE make." - CEO Cyberdyne Systems Corp. A8.30.5 Commercial
|
|
|
Re: 'Structured' programming in Lite-C
[Re: EvilSOB]
#280875
07/24/09 13:48
07/24/09 13:48
|
Joined: Jun 2006
Posts: 2,640 Earth
Germanunkol
Expert
|
Expert
Joined: Jun 2006
Posts: 2,640
Earth
|
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?
~"I never let school interfere with my education"~ -Mark Twain
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Germanunkol]
#280876
07/24/09 13:57
07/24/09 13:57
|
Joined: Feb 2008
Posts: 3,232 Australia
EvilSOB
Expert
|
Expert
Joined: Feb 2008
Posts: 3,232
Australia
|
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.
"There is no fate but what WE make." - CEO Cyberdyne Systems Corp. A8.30.5 Commercial
|
|
|
Re: 'Structured' programming in Lite-C
[Re: EvilSOB]
#281025
07/25/09 01:21
07/25/09 01:21
|
Joined: Oct 2004
Posts: 4,134 Netherlands
Joozey
OP
Expert
|
OP
Expert
Joined: Oct 2004
Posts: 4,134
Netherlands
|
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!  . 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.
Click and join the 3dgs irc community! Room: #3dgs
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Joozey]
#281247
07/26/09 12:39
07/26/09 12:39
|
Joined: Sep 2003
Posts: 5,900 Bielefeld, Germany
Pappenheimer
Senior Expert
|
Senior Expert
Joined: Sep 2003
Posts: 5,900
Bielefeld, Germany
|
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?
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Pappenheimer]
#281259
07/26/09 13:44
07/26/09 13:44
|
Joined: Oct 2004
Posts: 4,134 Netherlands
Joozey
OP
Expert
|
OP
Expert
Joined: Oct 2004
Posts: 4,134
Netherlands
|
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  . Regards, Joozey
Last edited by Joozey; 07/26/09 13:45.
Click and join the 3dgs irc community! Room: #3dgs
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Joozey]
#281403
07/27/09 05:27
07/27/09 05:27
|
Joined: Jul 2007
Posts: 424 EUROPE
maslone1
Senior Member
|
Senior Member
Joined: Jul 2007
Posts: 424
EUROPE
|
Very clear!
Thanx for your cool thread, and detailed explaining how to use "structured programming".
Have a nice day joozey!
cheers Marcel
A8c, Blender, FlStudio, Unity3d
|
|
|
Re: 'Structured' programming in Lite-C
[Re: maslone1]
#285388
08/18/09 11:02
08/18/09 11:02
|
Joined: Jan 2004
Posts: 3,023 The Netherlands
Helghast
Expert
|
Expert
Joined: Jan 2004
Posts: 3,023
The Netherlands
|
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  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,
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Joozey]
#286131
08/23/09 10:47
08/23/09 10:47
|
Joined: Aug 2009
Posts: 11
alwaysblack
Newbie
|
Newbie
Joined: Aug 2009
Posts: 11
|
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? //a function to visualize an item on a panel void item_visualize( Inventory *inventory, Panel *panel ) { panel->bmap = inventory->image; }
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Rei_Ayanami]
#317787
04/02/10 15:22
04/02/10 15:22
|
Joined: Dec 2006
Posts: 1,086 Queensland - Australia
Nidhogg
Serious User
|
Serious User
Joined: Dec 2006
Posts: 1,086
Queensland - Australia
|
Great explanation Joozey. Will defanitly find this usefull.
Windows XP SP3 Intel Dual Core CPU: E5200 @ 2.5GHz 4.00GB DDR3 Ram ASUS P5G41T-M LX PCIE x16 GeForce GTS 450 1Gb SB Audigy 4 Spyware Doctor with AntiVirus
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Nidhogg]
#317802
04/02/10 16:16
04/02/10 16:16
|
Joined: Feb 2009
Posts: 3,207 Germany, Magdeburg
Rei_Ayanami
Expert
|
Expert
Joined: Feb 2009
Posts: 3,207
Germany, Magdeburg
|
I don't get it...
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;
|
|
|
Re: 'Structured' programming in Lite-C
[Re: Rei_Ayanami]
#317806
04/02/10 16:35
04/02/10 16:35
|
Joined: Jul 2001
Posts: 6,904
HeelX
Senior Expert
|
Senior Expert
Joined: Jul 2001
Posts: 6,904
|
try
(block[0])->pnl->pos = 1;
Last edited by HeelX; 04/02/10 16:35.
|
|
|
|