的主要问题是,Sprite zombie_sprite
只有一个对象。使这个对象数组,你可以开始看其他问题。接下来,对指向Sprite
对象的指针会有一些混淆。为了简化一些事情,我们可以调整zombies
函数中的变量,并对最佳实践进行一些“整理”。
// Start by using a compile-time constant to define the number of zombies.
// This could be changed to a vriable in the, once the simple case is working.
#define NUMBER_OF_ZOMBIES 8
void zombies()
{
// Eight zombies are required, so define an array of eight sprites.
Sprite zombie_sprites[NUMBER_OF_ZOMBIES];
byte zombie_bitmap [] =
{
BYTE(11100000),
BYTE(01000000),
BYTE(11100000)
};
// Continued below...
这使得该函数的其余部分更容易初始化精灵。这一次,可以将指针指向数组中的i
th元素。此外,您将看到create_zombies
函数需要一个参数:Sprite
对象的地址,因此将它传递给刚刚初始化的同一阵列中第一个精灵的地址。
再次,进行一些内部的,功能的其余部分是这样的:
// ...continued from above
for (int i = 0; i < NUMBER_OF_ZOMBIES; i++)
{
// Initialise the ith sprite using the address of its element
// in the zombie_sprites array.
init_sprite(&zombie_sprites[i], rand()%76, rand()%42,
3, 3, zombie_bitmap);
}
// Animate the zombies in the array.
create_zombies(&zombie_sprites[0]);
}
最后,create_zombies
功能本身需要循环的微小变化,通过所有的精灵的数组中传递作为其参数。此外,它的类型为void
它没有return语句。
void create_zombies(Sprite * zombie_sprites)
{
while(1)
{
clear();
// loop round drawing all of the sprites.
for(int zombie_index = 0; zombie_index < NUMBER_OF_ZOMBIES; zombie_index++)
{
draw_sprite(&zombie_sprites[zombie_index]);
}
refresh();
}
}
未来的改进可能包括:
- 更改NUMBER_OF_ZOMBIES是一个变量。
- 使用
malloc
和free
替换动态分配的阵列中的静态阵列。
- 用更复杂的抽象数据类型(如列表或双向链表)替换数组,以便在运行时添加或删除僵尸。
- 重命名函数并重构每个被调用的地方。
您已经在不提供参数的情况下调用'create_zombies()'。 –
这行'Sprite * zombie_sprites =&zombie_sprites [i];'产生一个编译器警告。正确的是:它是自引用的。 –
随机线现在看起来不同,但它仍然没有显示精灵 –