我正在使用C和SDL为Conway的生活游戏创建一个模拟。为了表示活细胞,我想在创建的窗口中创建多个矩形。是否可以在不重新定义SDL_Rect的情况下在for循环中调用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;
}
答案 0 :(得分:1)
错误是事实,我的带有CreateRectanglesX()和CreateRectanglesY的随机数生成公式是错误的。是
class Index extends React.Component {
state = {drawerOpened: false}
handleClick = e => {
e.preventDefault();
this.setState(prevState => ({
drawerOpened: !prevState.drawerOpened
}))
};
render() {
return <div className={styles.root}>
<AppBar position="static">
<Toolbar>
<IconButton
className={styles.menuButton}
color="inherit"
aria-label="Menu"
onClick={this.handleClick}
>
<MenuIcon/>
</IconButton>
<Typography variant="h6" color="inherit" className={styles.grow}>
Example
</Typography>
<Button color="inherit" style={{ right: "0px", position: "absolute" }}>
Login
</Button>
</Toolbar>
</AppBar>
<SwipeableDrawer open={this.state.drawerOpened}>
<div tabIndex={0} role="button">
{sideList}
</div>
</SwipeableDrawer>
</div>
}
}
应该是:
v = rand() / (x_max - x_min) / RAND_MAX + x_min;
由于使用随机生成函数生成的随机数太近(由于公式错误),因此仅显示一个矩形。修正公式可以解决问题!