/// <summary> /// Gets the GOl field according to the display /client position /// </summary> /// <param name="x">client x position</param> /// <param name="y">client y position</param> /// <param name="gol">The game of life instance</param> /// <param name="display">The display instance</param> /// <param name="x1">The result x coordinate</param> /// <param name="y1">The result y coordinate</param> internal static void GetFieldFromDisplayPos(int x, int y, GameOfLife gol, Control display, out int x1, out int y1) { // get size of individual boxes Statics.GetBoxSize(gol, display, out x1, out y1); x1 = (int)Math.Floor(x * 1.0 / x1); y1 = (int)Math.Floor(y * 1.0 / y1); }
public GameOfLifeForm(IntPtr previewHandle) { Rectangle parentRect; _isPreview = true; this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true); // Make process DPI aware (solve preview scaling issue) if (Environment.OSVersion.Version.Major >= 6) { SetProcessDPIAware(); } InitializeComponent(); // Set the preview window as the parent of this window SetParent(this.Handle, previewHandle); // Make this a child window so it will close when the parent dialog closes SetWindowLong(this.Handle, -16, new IntPtr(GetWindowLong(this.Handle, -16) | 0x40000000)); // Place our window inside the parent GetClientRect(previewHandle, out parentRect); Size = parentRect.Size; //Size = new Size(parentRect.Width, parentRect.Height); Location = new Point(0, 0); _gameOfLife = new GameOfLife(parentRect.Width, parentRect.Height, 4, 0.15); DrawingComplete += DrawingEvent; }
/// <summary> /// Show particular game grid in console window. /// And particular game statistic. /// </summary> /// <param name="game">Game to show.</param> public void ShowGrid(GameOfLife game) { string currentCell; for (int row = 0; row < game.Grid.Size.Rows; row++) { for (int column = 0; column < game.Grid.Size.Columns; column++) { if (game.Grid[row, column].CurrentState == State.Alive) { Console.ForegroundColor = ConsoleColor.Red; currentCell = _alive; } else { Console.ForegroundColor = ConsoleColor.White; currentCell = _dead; } Console.Write(currentCell); } Console.Write('\n'); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"ID:{game.Id}"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"Iteration: {game.IterationNumber}"); Console.WriteLine($"Live cells: {game.Grid.AliveCellsCount()}"); }
static void Main(string[] args) { var initialCells = new List<string>() { "{0}x{0}", "{1}x{0}", "{2}x{-1}", "{2}x{1}", "{3}x{0}", "{4}x{0}", // Lifespan of these cycles at 15 "{5}x{0}", "{6}x{0}", "{7}x{-1}", "{7}x{1}", "{8}x{0}", "{9}x{0}", }; var gameOfLife = new GameOfLife(); gameOfLife.Initialize(initialCells); //foreach (var cell in gameOfLife.GetLifeCells(0)) //{ // Console.WriteLine(cell); //} foreach (var cell in gameOfLife.GetLifeCells(3000)) { Console.WriteLine(cell); } Console.ReadLine(); }
static void Main(string[] args) { //Console.WriteLine("Hello World!"); GameOfLife sim = new GameOfLife(20, 30); sim.GameRun(); }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { using (GameOfLife game = new GameOfLife()) { game.Run(); } }
static void Main(string[] args) { var gol = new GameOfLife(1000); var sw = new Stopwatch(); Console.WriteLine("TaskBarrier:"); sw.Restart(); var golTB = new GameOfLifeTB(1000); golTB.Run(50); Console.WriteLine(sw.Elapsed); Console.WriteLine("Sequential:"); sw.Restart(); gol.Run(50); sw.Stop(); Console.WriteLine(sw.Elapsed); Console.WriteLine("Parallel:"); sw.Restart(); var golP = new GameOfLifeP(1000); golP.Run(50); Console.WriteLine(sw.Elapsed); }
static void Main(string[] args) { var initialCells = new List<string>() { "0x0", "1x0", "2x-1", "2x1", "3x0", "4x0", // Lifespan of these cycles at 15 "5x0", "6x0", "7x-1", "7x1", "8x0", "9x0", }; var gameOfLife = new GameOfLife(); gameOfLife.Initialize(initialCells); //foreach (var cell in gameOfLife.GetLifeCells(0)) //{ // Console.WriteLine(cell); //} foreach (var cell in gameOfLife.GetLifeCells(3000)) { Console.WriteLine(cell); } Console.ReadLine(); }
/// <summary> /// Handles mouse move event on display. checks if left mouse button /// is pressed, then toggles the field (once...) currently under /// the mouse pointer. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnDisplayMouseMove(object sender, MouseEventArgs e) { int x = e.X; int y = e.Y; GameOfLife m = this.gol; if (m != null & m.Envir != null) { Statics.GetFieldFromDisplayPos(x, y, m, this.form.display, out x, out y); if (x >= m.SizeX || y >= m.SizeY) { return; } bool nc = (x != this.lastMousePosition[0]) || (y != this.lastMousePosition[1]); // a secret this.lastMousePosition[0] = x; this.lastMousePosition[1] = y; if (e.Button == MouseButtons.Left & nc) { this.gol.ToggleField(x, y); this.form.Redraw(); } } }
public void SaveGame(GameOfLife game) { List <Point> coordsList = new List <Point>(); for (int x = 0; x < game.SizeX; x++) { for (int y = 0; y < game.SizeY; y++) { if (game[x, y]) { coordsList.Add(new Point(x, y)); } } } string fileName = GetDateTimeFileName("GameOfLife\\saves\\", namePrefix: "LifeGame_", applicationExtention: ".lifegame"); Console.WriteLine("Saving game to file '{0}'...", fileName); System.IO.StreamWriter file = new System.IO.StreamWriter(fileName); file.WriteLine("0 0"); foreach (Point coords in coordsList) { file.WriteLine(string.Format("{0} {1}", coords.X, coords.Y)); } file.Close(); Console.WriteLine("Saved"); }
static void Main(string[] args) { bool[,] array = new bool[6, 12]; array[1, 4] = true; array[2, 3] = true; array[2, 4] = true; array[2, 5] = true; array[3, 4] = true; var grid = GameOfLife.GetGrid(array); GameOfLife.Print(Console.WriteLine, grid, 0); Console.WriteLine("Press Enter To Begin"); Console.ReadLine(); GameOfLife.Run( grid: grid, iterations: 1000, iterator: (g) => GameOfLife.Iterate(g, GameOfLife.ApplyConditions), print: (gridToPrint, iteration) => GameOfLife.Print(Console.WriteLine, gridToPrint, iteration, clear: Console.Clear), postIteration: () => Task.Delay(250).Wait()); Console.ReadLine(); }
public GameOfLife LoadGameFile(string gameFileName, bool destroySideCells) { string currentLine; List <int> xCoords = new List <int>(); List <int> yCoords = new List <int>(); List <Point> coordsList = new List <Point>(); System.IO.StreamReader file = new System.IO.StreamReader(gameFileName); string[] offsetString = file.ReadLine().Split(' '); int offsetX = Convert.ToInt32(offsetString[0]); int offsetY = Convert.ToInt32(offsetString[1]); while ((currentLine = file.ReadLine()) != null) { string[] coordinateStrings = currentLine.Split(' '); int x = Convert.ToInt32(coordinateStrings[0]) + offsetX; int y = Convert.ToInt32(coordinateStrings[1]) + offsetY; xCoords.Add(x); yCoords.Add(y); coordsList.Add(new Point(x, y)); } file.Close(); GameOfLife game = new GameOfLife(xCoords.Max() + 2, yCoords.Max() + 2); SetUpGame(game, coordsList.ToArray()); return(game); }
static void Main(string[] args) { int width = 50, height = 30, borderwidth = 1; char livingCell = 'o', deadCell = ' '; int value; Console.SetCursorPosition(0, 0); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Выберите режим игры:"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("1.Автоматический режим"); Console.WriteLine("2.Ручной режим (переход к следующему шагу по нажатию Enter)"); value = Convert.ToInt32(Console.ReadLine()); Console.Clear(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" Инструкция"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Для того чтобы поставить/удалить клетку - нажмите кнопку Space"); Console.WriteLine("Игра будет начата через 10 секунд..."); Thread.Sleep(10000); Console.Clear(); Console.ForegroundColor = ConsoleColor.Green; GameOfLife.CreateInstance(width, height, borderwidth, livingCell, deadCell, value); GameOfLife.GetDrawing(); GameOfLife.Start(); }
public void SetUpGame(GameOfLife game, Point[] coordsList) { foreach (Point coords in coordsList) { game.ToggleCell(coords.X, coords.Y); } }
public void ReturnNewPatternWhenYouIntroduceABeaconPattern() { Ecosystem expectedEcosystem = new Ecosystem(); expectedEcosystem.AddCell(0, 0); expectedEcosystem.AddCell(1, 0); expectedEcosystem.AddCell(0, 1); expectedEcosystem.AddCell(2, 3); expectedEcosystem.AddCell(3, 2); expectedEcosystem.AddCell(3, 3); Ecosystem ecosystem = new Ecosystem(); ecosystem.AddCell(0, 0); ecosystem.AddCell(0, 1); ecosystem.AddCell(1, 1); ecosystem.AddCell(1, 0); ecosystem.AddCell(2, 2); ecosystem.AddCell(2, 3); ecosystem.AddCell(3, 2); ecosystem.AddCell(3, 3); GameOfLife gameOfLife = new GameOfLife(ecosystem); gameOfLife.Play(); Assert.Equal(expectedEcosystem, ecosystem); }
public void ReturnNewPatternWhenYouIntroduceAInitialPatternFromListToEcosystem() { var expectedGeneration = new List <CellPosition> { new CellPosition(0, 0), new CellPosition(1, 0), new CellPosition(0, 1), new CellPosition(2, 3), new CellPosition(3, 3), new CellPosition(3, 2) }; Ecosystem expectedEcosystem = new Ecosystem(expectedGeneration); GameOfLife expectedGameOfLife = new GameOfLife(expectedEcosystem); var generation = new List <CellPosition> { new CellPosition(0, 0), new CellPosition(0, 1), new CellPosition(1, 1), new CellPosition(1, 0), new CellPosition(2, 2), new CellPosition(2, 3), new CellPosition(3, 2), new CellPosition(3, 3) }; Ecosystem ecosystem = new Ecosystem(generation); GameOfLife gameOfLife = new GameOfLife(ecosystem); var evolve = gameOfLife.Play(); Assert.Equal(expectedGameOfLife, evolve); }
/// <summary> /// Redraws the current GOL instance to the display /// </summary> internal void Redraw() { if (this.controller == null || this.model == null) { return; } GameOfLife m = this.model; // show generation info this.lGeneration.Text = "Generation: " + m.Generation.ToString(); // flag whether to use 'fancy graphics' i.e. gradient coloring bool fancy = this.controller.DrawFancy; // flag whether to use random colors bool random = this.controller.UseRandomColor; // show only the profile bool showProfile = this.controller.ShowProfile; // field color Color fc = this.controller.FieldColor; // get image buffer to draw fields on before // drawing on display Bitmap bm = new Bitmap(this.display.Width, this.display.Height); Graphics g = Graphics.FromImage(bm); g.Clear(Color.Gray); int sizeX = 0; int sizeY = 0; // get size of individual boxes Statics.GetBoxSize(m, this.display, out sizeX, out sizeY); // set background color Color bgCol = this.controller.BGColor; if (this.controller.FlickerBG && Controller.RNG.NextDouble() > 0.7) { bgCol = Color.Transparent; } // iterate over each field and draw it for (int i = 0; i < m.SizeX; i++) { for (int j = 0; j < m.SizeY; j++) { // get the brush Brush b = GetBrush(m, i, j, fc, bgCol, fancy, random, showProfile); // draw the actual field g.FillRectangle(b, new Rectangle(i * sizeX, j * sizeY, sizeX, sizeY)); } } // draw the buffer to the display this.display.CreateGraphics().DrawImage(bm, new Point(0, 0)); this.Invalidate(); }
/// <summary> /// gets the box size for individual cells given the currnet /// GoL instane and the display on which it should be drawn /// </summary> /// <param name="gol"></param> /// <param name="display"></param> /// <returns></returns> internal static void GetBoxSize(GameOfLife gol, Control display, out int sizeX, out int sizeY) { // get size of individual boxes, make it square always float reference = Math.Min(display.Width, display.Height); sizeX = (int)Math.Floor(reference / gol.SizeX); sizeY = (int)Math.Floor(reference / gol.SizeY); }
public void ThrowExceptionIfNumberOfCellsIsZero() { Ecosystem ecosystem = new Ecosystem(); GameOfLife gameOfLife = new GameOfLife(ecosystem); Assert.Throws <Exception>(() => gameOfLife.Play()); }
static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Cyan; var game = new GameOfLife(); var consoleRenderer = new ConsoleRenderer(); var gameInstance = new GameEngine(game, consoleRenderer); gameInstance.StartGame(); }
protected bool Equals(GameOfLife other) { if (this._ecosystem.Equals(other._ecosystem)) { return(true); } return(false); }
//this function is called when 'Clear' button is pressed private void btn_clear_Click(object sender, EventArgs e) { timer1.Enabled = false; btn_stop.Enabled = false; btn_start.Enabled = true; //new 'life' will be created with initial empty values so grid is empty life = new GameOfLife(life.height, life.width); UpdateColours(); }
private static void NewGame(ITemplate template) { Console.Write($"Enter game height (must be at least {template.Height}): "); string input = Console.ReadLine(); Console.WriteLine(); int height; if (!int.TryParse(input, out height) || height < 1 || height < template.Height) { Console.WriteLine("Invalid input."); return; } Console.Write($"Enter game width (must be at least {template.Width}): "); input = Console.ReadLine(); Console.WriteLine(); int width; if (!int.TryParse(input, out width) || width < 1 || width < template.Width) { Console.WriteLine("Invalid input."); return; } Console.Write($"Enter template x coordinate (cannot be more than {width - template.Width}): "); input = Console.ReadLine(); Console.WriteLine(); int templateX; if (!int.TryParse(input, out templateX) || templateX < 0 || templateX > width - template.Width) { Console.WriteLine("Invalid input."); return; } Console.Write($"Enter template y coordinate (cannot be more than {height - template.Height}): "); input = Console.ReadLine(); Console.WriteLine(); int templateY; if (!int.TryParse(input, out templateY) || templateY < 0 || templateY > height - template.Height) { Console.WriteLine("Invalid input."); return; } GameOfLife gameOfLife = new GameOfLife(height, width); gameOfLife.PlayGame(template, templateX, templateY); }
static void Main(string[] args) { System.Console.WriteLine("Starting the game of life..."); var game = new GameOfLife(20, 20, null); game.DrawBoard(); System.Console.ReadLine(); Observable.Interval(TimeSpan.FromMilliseconds(200)).Subscribe(l => { game.AdvanceGeneration(); game.DrawBoard(); }); System.Console.ReadLine(); }
public void Block() { var state = new[,]{ {O,O,O,O}, {O,X,X,O}, {O,X,X,O}, {O,O,O,O}}; var gameOfLife = new GameOfLife(state); Assert.That(gameOfLife.Tick().CurrentState(), Is.EquivalentTo(state)); }
static void Main(string[] args) { var watch = System.Diagnostics.Stopwatch.StartNew(); GameOfLife gol = new GameOfLife(1000); gol.RunParrel(100); watch.Stop(); Console.WriteLine($"Time to exe in milli : {watch.ElapsedMilliseconds}"); Console.ReadKey(); }
static void Main(string[] args) { if (!ValidateArgs(args)) { return; } gol = new GameOfLife(Size); GenerateLivingCells(); Print(); ItsAlive(); }
public GameOfLifeScreen(Camera currentCamera, GraphicsDeviceManager graphics, GameOfLife game, Vector2 blockSize) : base(currentCamera) { gameOfLife = game; Point gameOfLifeSize = new Point(gameOfLife.SizeX, gameOfLife.SizeY); texture = new Texture2D(graphics.GraphicsDevice, (int)blockSize.X, (int)blockSize.Y); Color[] colors = new Color[texture.Width * texture.Height]; for (int i = 0; i < colors.Length; i++) { colors[i] = Color.White; } backgroundColour = Color.Gray; }
static void Main(string[] args) { // Print the grid to the user. GameOfLife.PrintGrid(); WriteLine("Press ENTER for newer generation"); // Update the grid everytime the user hits enter. while (ReadLine() == "") { GameOfLife.Update(); GameOfLife.PrintGrid(); WriteLine("Press ENTER for newer generation"); } }
private static List <IGameOfLife> CreateThousandGames()//Creating Thousand games and returns List of them { List <IGameOfLife> games = new List <IGameOfLife>(); for (int i = 0; i < 1000; i++) { RandomPattern randompattern = new RandomPattern(); IGameOfLife tempgame = new GameOfLife(30, 15); randompattern.Add(tempgame); games.Add(tempgame); } Messages.ThousandGameCreation(); return(games); }
static void Main(string[] args) { int sleepTime = 100; if (args.Length != 0) { sleepTime = int.Parse(args[0]); } GameOfLife gol = new GameOfLife(60, 250, true); /*gol.currentMap[10, 10] = 1; * gol.currentMap[10, 11] = 1; * gol.currentMap[10, 12] = 1; * gol.currentMap[10, 13] = 1; * gol.currentMap[10, 14] = 1; * * gol.currentMap[12, 10] = 1; * gol.currentMap[12, 14] = 1; * * gol.currentMap[15, 10] = 1; * gol.currentMap[15, 11] = 1; * gol.currentMap[15, 12] = 1; * gol.currentMap[15, 13] = 1; * gol.currentMap[15, 14] = 1;*/ Console.Clear(); Console.CursorVisible = false; string time = DateTime.Now.ToString("ss"); int iterations = 0; while (true) { gol.Draw(); gol.NextGeneration(); if (DateTime.Now.ToString("ss") == time) { iterations++; } else { Console.WriteLine("\n\nFPS : {0}", iterations); iterations = 0; } time = DateTime.Now.ToString("ss"); Thread.Sleep(sleepTime); } }
//private void MainWindow_KeyUp(object sender, KeyEventArgs e) //{ // _game.ComputeNextTurn(); // Display(_game); //} private static void Display(GameOfLife.GameOfLife game) { for (int i = 0; i < game.Size; i++) { for (int j = 0; j < game.Size; j++) { try { // Reserve the back buffer for updates. writeableBitmap.Lock(); unsafe { // Get a pointer to the back buffer. IntPtr pBackBuffer = writeableBitmap.BackBuffer; // Find the address of the pixel to draw. pBackBuffer += j * writeableBitmap.BackBufferStride; pBackBuffer += i * 4; if (game.board[i, j]) { // Compute the pixel's color. int color_data = 0 << 16; // R color_data |= 255 << 8; // G color_data |= 0 << 0; // B // Assign the color data to the pixel. *((int *)pBackBuffer) = color_data; } else { // Assign the color data to the pixel. *((int *)pBackBuffer) = 0; } } // Specify the area of the bitmap that changed. writeableBitmap.AddDirtyRect(new Int32Rect(i, j, 1, 1)); } finally { // Release the back buffer and make it available for display. writeableBitmap.Unlock(); } } } }
static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.DarkRed; int width = 40, height = 20, spawnProbability = 7; char aliveCell = '0', deadCell = ' '; Console.Read(); GameOfLife game = new GameOfLife(width, height, 1, aliveCell, deadCell); game.RandomFill(spawnProbability); game.Start(); }
static void Main(string[] args) { var game = new GameOfLife(15, 15, Density.Medium); var gamePrinter = new GamePrinter(game); do { while (!Console.KeyAvailable) { game.Next(); gamePrinter.PrintBoard(); Thread.Sleep(300); } } while (Console.ReadKey(true).Key != ConsoleKey.Escape); }
public void ShouldReturnGamesCurrentState() { var state = new[,]{ {X,X,X}, {O,O,O}, {O,O,O}, {X,O,X}}; var gameOfLife = new GameOfLife(state); Assert.That(gameOfLife.CurrentState(), Is.EquivalentTo(state)); }
private static void Main( string[] args ) { try { AliveChar = Encoding.GetEncoding( 437 ).GetChars( new byte[] { 4 } )[0]; DeadChar = Encoding.GetEncoding( 437 ).GetChars( new byte[] { 0 } )[0]; bool isInteractive = false; bool argsValid = false; int consoleWidth = 0, consoleHeight = 0, speed = 0; if( args.Length < 1 ) { isInteractive = argsValid = true; } else if( args.Length == 1 && int.TryParse( args[0], out speed ) ) { argsValid = true; consoleHeight = DefaultHeight; consoleWidth = DefaultWidth; } else if( args.Length == 3 && int.TryParse( args[0], out speed ) && int.TryParse( args[1], out consoleWidth ) && int.TryParse( args[2], out consoleHeight ) ) { argsValid = true; } if( isInteractive ) { Console.WriteLine( "Running interactively." ); Console.Write( "Set speed (in milliseconds): " ); if( int.TryParse( Console.ReadLine(), out speed ) ) { if( speed < 50 || speed > 10000 ) { Console.WriteLine( "speed out of range, using default value: {0}", DefaultSpeed ); speed = DefaultSpeed; } } else { speed = DefaultSpeed; } Console.Write( "Set console width: " ); if( int.TryParse( Console.ReadLine(), out consoleWidth ) ) { if( consoleWidth < 10 || consoleWidth > 150 ) { Console.WriteLine( "width out of range, using default value: {0}", DefaultWidth ); consoleWidth = DefaultWidth; } } else { consoleWidth = DefaultWidth; } Console.Write( "Set console height: " ); if( int.TryParse( Console.ReadLine(), out consoleHeight ) ) { if( consoleHeight < 5 || consoleHeight > 80 ) { Console.WriteLine( "height out of range, using default value: {0}", DefaultHeight ); consoleWidth = DefaultHeight; } } else { consoleHeight = DefaultHeight; } } if( !argsValid ) { Console.WriteLine( "Usage: gameoflife.exe [speed [console-width console-height]]\n" + "Where\n" + "\tspeed: refresh rate (in ms)\n" + "\tconsolewidth: width in characters (20-150)\n" + "\tconsoleheight: height in characters (10-80)\n" ); return; } game = new GameOfLife( consoleWidth, consoleHeight, speed, AliveChar, DeadChar ); game.DoSetup(); game.DoLoop(); } catch( Exception ex ) { Console.Clear(); Console.WriteLine( "ERROR:" ); Console.WriteLine( ex.Message ); } }
public GamePrinter(GameOfLife game) { _game = game; }
static void Main(string[] args) { GameOfLife game = new GameOfLife(new Cell[24, 24]); game.Init(); Console.ReadKey(); }