gpt4 book ai didi

c - 我的 print_random_sprites 函数有什么问题?

转载 作者:行者123 更新时间:2023-11-30 17:14:47 25 4
gpt4 key购买 nike

我正在用 C 编写一些代码,在微处理器的 LCD 屏幕上随机显示 Sprite 。目前,当我运行此代码时,它会生成从上到下运行的 8 行。所以它以随机顺序打印一些东西,但不打印 Sprite 。为什么是这样?有人可以帮助我吗? (注意:rand 被播种在一个单独的函数中,该函数工作正常,问题就出在这段代码中。)

void zombies() {

Sprite zombie_sprite;
Sprite * zombie_sprite_pointer = &zombie_sprite;
byte zombie_bitmap [] = {
BYTE( 11100000 ),
BYTE( 01000000 ),
BYTE( 11100000 )
};

for (int i = 0; i < 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;
}

最佳答案

主要问题是 Sprite僵尸_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...

这使得初始化 Sprite 的函数的其余部分变得更容易。这次,可以获得指向数组中第 i 个元素的指针。另外,您将看到 create_zombies 函数需要一个参数:Sprite 对象的地址,因此将刚刚创建的同一数组中的第一个 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 函数本身需要进行一些小的更改,以循环遍历作为其参数传递的数组中的所有 Sprite 。此外,由于 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();
}
}

future 的增强功能可能包括:

  • 将 NUMBER_OF_ZOMBIES 更改为变量。
  • 使用 mallocfree 将静态数组替换为动态分配的数组。
  • 用更复杂的抽象数据类型(例如列表或双向链表)替换数组,以便可以在运行时添加或删除僵尸。
  • 重命名函数并重组每个函数的调用位置。

关于c - 我的 print_random_sprites 函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30185012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com