Conway’s Game of Life in C# e Raylib

Ecco un’implementazione in C# e Raylib di Conway’s Game of Life.

/*
Conways' Game of Life - version 0.0.1
Licensed under the terms of LGPL v 3.0
*/
using Raylib_cs;
namespace myRaylibTestApp;
class Cell {
	public bool statePresent;
	public bool stateNext;
	public bool hasLivedOnce;
	public int x, y;
	public Cell(int x, int y) {
		this.stateNext = false;
		Random random = new Random();
		int randomNumber = random.Next(0, 99);
		if (randomNumber > 50) {
			this.statePresent = true;
		}
		this.x = x;
		this.y = y; 
	}
	public void Draw() {
		if (this.statePresent) {
			Raylib.DrawRectangle(x*6, y*6, 6, 6, Color.Red);
		}else{
			if (this.hasLivedOnce) {
				Raylib.DrawRectangle(x*6, y*6, 6, 6, Color.LightGray);
			} else {
				Raylib.DrawRectangle(x*6, y*6, 6, 6, Color.DarkGray);
			}
		}
	}
	
}
class Program
{
	const int SCREEN_W = 600;
	const int SCREEN_H = 600;
	public static void Main()
	{
		Raylib.InitWindow(SCREEN_W, SCREEN_H, "Game of life");
		Raylib.SetTargetFPS(30);
		
		/* Cells initializing*/
		Cell[,] theCell = new Cell[100,100];
		for (int i = 0; i < 100; i++) {
			for (int j = 0; j < 100; j++) {
				theCell[i,j] = new Cell(j, i);
			}	 
		}
		/*-------*/
		while (!Raylib.WindowShouldClose())
		{
			/*compute effect of neighbours*/
			
			for (int y = 0; y < 100; y++) {
				for (int x = 0; x < 100; x++) {
					int s = 0;
					int tlx, tly, brx, bry;
					tlx = x-1;
					tly = y-1;
					brx = x+1;
					bry = y+1;
					if (tlx < 0) {
						tlx = 0;
					}
					if (tly < 0) {
						tly = 0;
					}
					if (brx > 99) {
						brx = 99;
					} 
					if (bry > 99) {
						bry = 99;
					}
					for (int row = tly; row <= bry; row++) {
						for (int col = tlx; col <= brx; col++) {
							if (row == y && col == x) {
								continue;
							}
							
							if (theCell[row,col].statePresent) {
								s++;
							}
						}
					}
					if (theCell[y,x].statePresent && s == 2 || s == 3) {
						theCell[y,x].stateNext = true;
					}else{
						theCell[y,x].stateNext = false;
					}
					if (!theCell[y,x].statePresent && s == 3){
						theCell[y,x].stateNext = true;
					}
				}
			}
			for (int y = 0; y < 100; y++) {
				for (int x = 0; x < 100; x++) {
					theCell[y,x].statePresent = theCell[y,x].stateNext;
					if (theCell[y,x].statePresent) {
						theCell[y,x].hasLivedOnce = true;
					}
				}
			}
			Raylib.BeginDrawing();
			Raylib.ClearBackground(Color.White);
			for (int y = 0; y < 100; y++) {
				for (int x = 0; x < 100; x++) {
				   theCell[y,x].Draw();
				}
			}
			Raylib.EndDrawing();
		}
		Raylib.CloseWindow();
	}
}