game-of-life/main.c

162 lines
2.5 KiB
C
Raw Permalink Normal View History

2023-11-24 14:05:48 +01:00
#include <stdio.h>
#include <graph.h>
#define WIDTH 50
#define HEIGHT 50
#define BLOCK_SIZE 20
#define CYCLE 50000L
void populate(int map[HEIGHT][WIDTH])
{
for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
map[i][j] = 0;
}
}
}
void display_map(int map[HEIGHT][WIDTH], int mode) {
for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
if (map[i][j])
{
switch (mode)
{
case 1:
ChoisirCouleurDessin(CouleurParComposante(0, 0, 0));
break;
default:
ChoisirCouleurDessin(CouleurParComposante(50, 50, 50));
break;
}
}
else
{
ChoisirCouleurDessin(CouleurParComposante(255, 255, 255));
}
RemplirRectangle(
i * BLOCK_SIZE,
j * BLOCK_SIZE,
BLOCK_SIZE,
BLOCK_SIZE
);
ChoisirCouleurDessin(CouleurParComposante(0, 0, 0));
if (mode == 0)
DessinerRectangle(
i * BLOCK_SIZE,
j * BLOCK_SIZE,
BLOCK_SIZE,
BLOCK_SIZE
);
}
}
}
int get(int map[HEIGHT][WIDTH], int x, int y)
{
if (x < 0 || y < 0 || x > WIDTH - 1 || y > HEIGHT - 1) return 0;
return map[x][y];
}
void tick(int map[HEIGHT][WIDTH])
{
int toggle_map[HEIGHT][WIDTH];
populate(toggle_map);
for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
int count = 0;
int alive = map[i][j];
count += get(map, i - 1, j - 1);
count += get(map, i - 1, j);
count += get(map, i - 1, j + 1);
count += get(map, i, j - 1);
count += get(map, i, j + 1);
count += get(map, i + 1, j - 1);
count += get(map, i + 1, j);
count += get(map, i + 1, j + 1);
if (
(!alive && count == 3) ||
(alive && (count < 2 || count > 3))
)
{
toggle_map[i][j] = 1;
}
}
}
for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
if (toggle_map[i][j]) map[i][j] = !map[i][j];
}
}
}
int main()
{
int map[HEIGHT][WIDTH] = {};
int x, y;
populate(map);
InitialiserGraphique();
CreerFenetre(0, 0, WIDTH * BLOCK_SIZE, HEIGHT * BLOCK_SIZE);
x = _X / BLOCK_SIZE;
y = _Y / BLOCK_SIZE;
display_map(map, 0);
while (1)
{
SourisPosition();
if (ToucheEnAttente()) break;
x = _X / BLOCK_SIZE;
y = _Y / BLOCK_SIZE;
if (SourisCliquee())
{
map[x][y] = !map[x][y];
display_map(map, 0);
}
}
display_map(map, 1);
unsigned long suivant = Microsecondes() + CYCLE;
while (1)
{
if (Microsecondes() > suivant)
{
tick(map);
display_map(map, 1);
suivant = Microsecondes() + CYCLE;
}
if (SourisCliquee()) break;
}
FermerGraphique();
return 0;
}