c - What's wrong with my print_random_sprites function? -
i'm writing code in c randomly displays sprites on lcd screen on microprocessor. when run code produces 8 lines running top bottom. it's printing in random order not sprite. why this? me? (note: rand seeded in separate function works fine, problem within code.)
void zombies() { sprite zombie_sprite; sprite * zombie_sprite_pointer = &zombie_sprite; byte zombie_bitmap [] = { byte( 11100000 ), byte( 01000000 ), byte( 11100000 ) }; (int = 0; < 8; i++) { sprite * zombie_sprites = &zombie_sprites[i]; init_sprite(zombie_sprites, rand()%76, rand()%42, 3, 3, zombie_bitmap); } create_zombies(); } void create_zombies(sprite * zombie_sprites) { while(1) { clear(); draw_sprite( &zombie_sprites ); refresh(); } return 0; }
the main problem sprite zombie_sprite
1 object. make array of objects , can start looking @ other problems. next there fair bit of confusion on pointers sprite
objects. simplify things bit can tweak variables in zombies
function, along 'tidying up' best practices.
// start using compile-time constant define number of zombies. // changed vriable in the, once simple case working. #define number_of_zombies 8 void zombies() { // 8 zombies required, define array of 8 sprites. sprite zombie_sprites[number_of_zombies]; byte zombie_bitmap [] = { byte( 11100000 ), byte( 01000000 ), byte( 11100000 ) }; // continued below...
this makes rest of function initialise sprites easier. time, possible pointer i
th element in array. also, see create_zombies
function requires argument: address of sprite
object, pass address of first sprite in same array has been initialised.
again, bit of housekeeping, rest of function this:
// ...continued above (int = 0; < number_of_zombies; i++) { // initialise ith sprite using address of element // in zombie_sprites array. init_sprite(&zombie_sprites[i], rand()%76, rand()%42, 3, 3, zombie_bitmap); } // animate zombies in array. create_zombies(&zombie_sprites[0]); }
finally, create_zombies
function needs minor change loop through of sprites in array passed parameter. also, being of type void
not have return statement.
void create_zombies(sprite * zombie_sprites) { while(1) { clear(); // loop round drawing of sprites. for(int zombie_index = 0; zombie_index < number_of_zombies; zombie_index++) { draw_sprite( &zombie_sprites[zombie_index] ); } refresh(); } }
future enhancements might include:
- changing number_of_zombies variable.
- replacing static array dynamically allocated array using
malloc
,free
. - replacing array more complex abstract data type such list or doubly linked list, zombies can added or removed @ run-time.
- renaming functions , restructuring each gets called.
Comments
Post a Comment