0% found this document useful (0 votes)
9 views3 pages

Conways Game of Life

Uploaded by

pranaybolli2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views3 pages

Conways Game of Life

Uploaded by

pranaybolli2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

GROUP - L

MM2103
Remanshu 2301mm38
Pranay Bolli 2301mm39
Sankruti shetti 2301mm40

REPORT
Conway’s Game of Life

Objectives :
Logic :
1. Grid Setup :
 A 256x256 grid is initialized with all cells dead (0).
 Some cells are set to alive (1) to create an initial pattern.
2. Display Grid :
 The current state of the grid is printed, using * for alive cells and . for dead cells.
3. Neighbor Counting :
 For each cell, the program counts the number of alive neighbors (8 surrounding cells),
wrapping around edges using modulo arithmetic.
4. State Update :
 The next state of each cell is determined:
o Alive cells survive with 2 or 3 neighbors; otherwise, they die.
o Dead cells become alive if they have exactly 3 alive neighbors.
5. Infinite Loop :
 The grid is updated and printed continuously, with a short delay to visualize the evolution over
time.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define WIDTH 256
#define HEIGHT 256
#define ALIVE 1
#define DEAD 0

void printGrid(int grid[HEIGHT][WIDTH]) {


for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
printf("%c ", grid[y][x] == ALIVE ? '*' : '.');
}
printf("\n");
}
printf("\n");
}

int countAliveNeighbors(int grid[HEIGHT][WIDTH], int y, int x) {


int count = 0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
if (dy == 0 && dx == 0) continue;
int ny = (y + dy + HEIGHT) % HEIGHT;
int nx = (x + dx + WIDTH) % WIDTH;
count += grid[ny][nx];
}
}
return count;
}

void updateGrid(int grid[HEIGHT][WIDTH], int newGrid[HEIGHT][WIDTH]) {


for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int aliveNeighbors = countAliveNeighbors(grid, y, x);
if (grid[y][x] == ALIVE) {
newGrid[y][x] = (aliveNeighbors == 2 || aliveNeighbors == 3) ? ALIVE : DEAD;
} else {
newGrid[y][x] = (aliveNeighbors == 3) ? ALIVE : DEAD;
}
}
}
}

int main() {
int grid[HEIGHT][WIDTH] = {0};
int newGrid[HEIGHT][WIDTH] = {0};

// Example: Initialize some cells to be alive


grid[1][2] = ALIVE;
grid[2][3] = ALIVE;
grid[3][1] = ALIVE;
grid[3][2] = ALIVE;
grid[3][3] = ALIVE;

while (1) {
printGrid(grid);
updateGrid(grid, newGrid);

// Copy newGrid to grid


for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
grid[y][x] = newGrid[y][x];
}
}

// Sleep for a short period


usleep(200); // 200 milliseconds
}

return 0;
}

Output :

You might also like