I am attempting to make a simple 2D sand simulation using basic cellular automata concepts (for more information watch: https://www.youtube.com/watch?v=VLZjd_Y1gJ8) and display it in the console but for some reason random particles appear near the bottom line of the matrix and there is a lot of chaos if you modify the matrix in the slightest(e.g. if you draw a line across horizontally in the middle or a random point somewhere low it will appear completely different), I believe this could be due to an error in my in bounds check if(grid[y][x] <= sizeY && grid[y][x] <=sizeX)
but I am not sure.
Code:
#include <stdio.h>
#include <stdlib.h>
#ifdef __unix__
# include <unistd.h>
#elif defined _WIN32
# include <windows.h>
#define sleep(x) Sleep(1000 * (x))
#endif
int sizeX = 20;
int sizeY = 20;
int alive = 1;
int dead = 0;
int grid[20][20] = {{0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}};
int drawScreen(int x, int y) {
system("cls"); // Clear screen
for (x = 0; x <= sizeX; x++) {
printf("\n");
for (y = 0; y <= sizeY; y++) {
if (grid[x][y] == alive) {
printf("@");
} else {
printf(" ");
}
}
}
}
int sand(int grid[sizeX][sizeY], int x, int y) {
if (grid[y + 1][x] == dead) {
grid[y][x] = dead;
grid[y + 1][x] = alive;
} else if (grid[y + 1][x - 1] == dead) {
grid[y][x] = dead;
grid[y + 1][x - 1] = alive;
} else if (grid[y + 1][x + 1] == dead) {
grid[y][x] = dead;
grid[y + 1][x + 1] = alive;
}
}
int main(void) {
int x, y, iterations;
for (iterations = 0; iterations < 1000; iterations++) {
for (y = sizeY - 1; y >= 0; y--) {
for (x = sizeX - 1; x >= 0; x--) {
if (grid[y][x] == alive) {
if (grid[y + 1][x] <= sizeY && grid[y][x + 1] <= sizeX) { // Bounds
sand(grid, x, y);
}
}
}
}
drawScreen(x, y);
}
}