Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.Immutable;
- using System.IO.Pipes;
- using System.Linq;
- using System.Runtime.CompilerServices;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- using System.Threading.Tasks;
- using NUnit.Framework;
- using System.Drawing;
- namespace CodeRetreatConwaysGameLife
- {
- class Game
- {
- private readonly ImmutableHashSet<Point> aliveCells;
- public Game()
- : this(ImmutableHashSet<Point>.Empty)
- {
- }
- private Game(ImmutableHashSet<Point> aliveCells)
- {
- this.aliveCells = aliveCells;
- }
- public static Game Stick()
- {
- return new Game()
- .SetCellAlive(2, 2)
- .SetCellAlive(2, 3)
- .SetCellAlive(2, 4)
- ;
- }
- private Game SetCellAlive(int x, int y)
- {
- return SetCellAlive(new Point(x, y));
- }
- public static IEnumerable<Point> GetNeighbours(Point cell)
- {
- return
- from dx in new int[] { -1, 0, 1 }
- from dy in new int[] { -1, 0, 1 }
- where Math.Abs(dx) + Math.Abs(dy) != 0
- select new Point(cell.X + dx, cell.Y + dy);
- }
- public IEnumerable<Point> GetAliveNeighbours(Point cell)
- {
- return GetNeighbours(cell).Where(IsAlive);
- }
- public bool IsAlive(Point cell)
- {
- return aliveCells.Contains(cell);
- }
- public Game SetCellAlive(Point cell)
- {
- return new Game(aliveCells.Add(cell));
- }
- public Game NextStep()
- {
- return new Game(GetNextGeneration());
- }
- private ImmutableHashSet<Point> GetNextGeneration()
- {
- return aliveCells.SelectMany(GetNeighbours)
- .Where(WillBeAlive)
- .ToImmutableHashSet();
- }
- private bool WillBeAlive(Point cell)
- {
- var count = GetAliveNeighbours(cell).Count();
- return (IsAlive(cell) && count == 2) || count == 3;
- }
- public override string ToString()
- {
- return String.Join("\n",
- Enumerable.Range(0, 10)
- .Select(y =>
- String.Join("", Enumerable.Range(0, 10)
- .Select(x => IsAlive(new Point(x, y)) ? "*" : " ")
- )));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement