我可以比较2个SDL_Surface(它们是否相同)

时间:2019-01-22 00:25:28

标签: c sdl-2

在C中使用SDL2进行游戏时,我必须比较2个SDL_Surface来检查获胜条件,但我找不到解决方法

1 个答案:

答案 0 :(得分:0)

您似乎对比较两个SDL_Surfaces很感兴趣,所以这是您的操作方法。解决您的特定问题可能有更好的方法,但是无论如何:

SDL Wiki中,SDL_Surface有感兴趣的成员format, w, h, pitch, pixels

  • format代表像素编码信息
    • format->format是用于指定给定编码的特定枚举常量
  • w代表表面上一行像素中的像素数
  • h代表表面上的像素行数
  • pitch代表一行的字节长度
  • pixels是一个包含所有像素数据的数组

如果要比较两个SDL_Surfaces,则需要将像素彼此比较。但是首先我们应该检查像素编码和尺寸是否匹配:

int SDL_Surfaces_comparable(SDL_Surface *s1, SDL_Surface *s2) {
  return (s1->format.format == s2->format.format && s1->w == s2->w && s1->h == s2->h);
}

如果SDL_Surfaces_comparable的值为true,我们可以通过逐字节比较pixels字段来检查两个表面是否相等。

int SDL_Surfaces_equal(SDL_Surface *s1, SDL_Surface *s2) {
  if (!SDL_Surfaces_comparable(s1, s2) {
    return 0;
  }
  // the # of bytes we want to check is bytes_per_pixel * pixels_per_row * rows
  int len = s1->format->BytesPerPixel * s1->pitch * s1->h;
  for (int i = 0; i < len; i++) {
    // check if any two pixel bytes are unequal
    if (*(uint8_t *)(s1->pixels + i) != *(uint8_t *)(s2->pixels + i))
      break;
  }
  // return true if we finished our loop without finding non-matching data
  return i == len;
}

这假设像素数据已序列化为字节而没有任何填充,或者填充为零。我找不到任何SDLPixel结构,所以我假设这是比较像素的标准方法。我确实找到了这个link,似乎证明了我的方法。