gpt4 book ai didi

使用 SDL_Rect 创建多个矩形

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

我正在使用 C 和 SDL 创建康威生命游戏的模拟。为了表示事件的细胞,我想在我创建的窗口中创建多个矩形。有没有办法在 for 循环中调用 SDL_Rect 而无需重新定义 SDL_Rect 并在同一个渲染器上输出 for 循环的结果?谢谢。

我的代码:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <SDL.h>
#define main SDL_main
#undef main

double CreateRectanglesX()
{
double x; double x_max = 640; double x_min = 20;
x = rand() / (x_max - x_min) / (double)RAND_MAX + x_min;
return x;
}

double CreateRectanglesY()
{
double y; double y_max = 480; double y_min = 20;
y = rand() / (y_max - y_min) / (double)RAND_MAX + y_min;
return y;
}

int main(int argc, char* argv[])
{
SDL_Init(SDL_INIT_VIDEO); //initializes the SDL/SDL2 window

SDL_Window *screen; //SDL window created with pointer
screen = SDL_CreateWindow("My Program Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL);
//definition for pointer - dimensions of SDL window

SDL_Renderer *renderer; //Renderer created with pointer
renderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_ACCELERATED); //definition for pointer - still to learn

if (screen == NULL) //checks if window exists or not
{
printf("Could not create window: %s\n", SDL_GetError()); //returns error if window doesn't exsit
return 1;
}

SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); //changes color of renderer
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer); //displays the renderer with the changed color

for (int i = 0; i < 5; i++)
{
double x = CreateRectanglesX();
double y = CreateRectanglesY();
printf("%lf %lf", x, y);
SDL_Rect a;
a.x = x;
a.y = y;
a.w = 20;
a.h = 20;
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
SDL_RenderFillRect(renderer, &a);
SDL_RenderPresent(renderer);
}

SDL_Delay(5000); //wait time for window
SDL_DestroyWindow(screen);
SDL_QUIT;

return EXIT_SUCCESS;
}

最佳答案

错误在于我使用 CreateRectanglesX() 和 CreateRectanglesY 的随机数生成公式是错误的。这是

v = rand() / (x_max - x_min) / RAND_MAX + x_min;

应该是:

v = rand() * (x_max - x_min) / RAND_MAX + x_min; 

仅显示一个矩形,因为随机生成函数生成的随机数太接近(由于公式错误)。修改公式解决了问题!

关于使用 SDL_Rect 创建多个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53995818/

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