12/4/2023 0 Comments Breaking conways game of life![]() To prevent a Segmentation Violation or memory corruption the value of the pointer return by the memory allocation function should always be tested before use. While memory allocation failure is rare these days with the large memories most processors have it can still occur. When memory allocation fails in C the memory allocation function ( calloc(), malloc() or realloc()) returns NULL (nullptr in C++). ![]() In C++ if new fails it throws an exception that would halt the program unless the exception was handled, this is not true in the C programming language. It would also be more like some of the object oriented design patterns such as MVC or MVVM. That way the game would work with different display mechanisms. I would separate the game logic from the display logic. I'm really curious about how many classes you would use to implement this program in C++? All of the functions seem to follow the single responsibility principle and that is great! In main() I might have put the game loop into its own function. ![]() Initially I was very impressed because the file started with the declaration of 2 enums. set alive states for drawing and reset next If(cells.alive & (count = 2 || count = 3)) // rule 3 Static int32_t count_neighbours(const int32_t cell_x, const int32_t cell_y)įor(int32_t x = max(cell_x - 1, 0) x 3)) // rule 2 & 4 Static void on_key_down(const SDL_Ke圜ode key) Set_field_from_mousepos(event->x, event->y, false) Set_field_from_mousepos(event->x, event->y, true) Renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED) Ĭells = calloc(field_size, sizeof(struct Cell*)) Window = SDL_CreateWindow("Conway's Game of Life", 50, 50, window_size, window_size, SDL_WINDOW_OPENGL) Int32_t window_size = field_size * pixels_per_cell Static const Uint32 tickrate = 200 // update frequency in ms Static const int32_t pixels_per_cell = 6 // size of a displayed cell in pixels Static const int32_t field_size = 200 // the amount of cells in both dimensions Here is the code: #define SDL_MAIN_HANDLED Upon start you can set up the starting pattern (left-click = alive, right-click = dead) and pressing the Enter key starts the simulation. ![]() I would like to get some review/feedback/suggestions for improvements about my code. Since im quite comfortable in writing C++ it's probably not completely awful. This is actually my first program written in C. So i implemented Conway's Game of Life using SDL2 for visualization. Lately i got interested in writing some C. My programming background is mostly C++/C#. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |