Jun
17
2014

TDD for Game Of Life

In this blog, I will demonstrate how to do Test-Driven-Development step by step when solving the Game Of Life. In short, doing TDD means we write test before writing code. In this example, I will use C# and Visual Studio for IDE.

To solve the Game Of Life, I want to have the following test. I always run test to have the failing result first before altering implementation, 

Add cells to a universe, and get all of them

[TestMethod]
public void UniverseGetAllLivingCells()
{
    Universe universe = new Universe();
    universe.Add(new Cell(1, 1));
    universe.Add(new Cell(2, 1));
    universe.Add(new Cell(1, 2));
    List<Cell> cells = universe.GetAllLivingCells();
    Assert.IsTrue(cells.Count == 3);
}

Implementation

public class Universe{
        private List<Cell> _livingCells = new List<Cell>();
        public List<Cell> GetAllLivingCells()
        {
            return _livingCells;
        }

        public void Add(Cell cell)
        {
            _livingCells.Add(cell);
        }
}

 public class Cell{

        public Cell(int row, int col){
            Row = row;
            Collumn = col;
        }
        public int Row { get; set; }

        public int Collumn { get; set; }       
    }

 

Test to add duplicated cells.

[TestMethod]

        public void UniverseAddDuplicatedLivingCells()
        {
            Universe universe = new Universe();
            universe.Add(new Cell(1, 1));
            universe.Add(new Cell(1, 1));
            List<Cell> cells = universe.GetAllLivingCells();
            Assert.IsTrue(cells.Count == 1);
        }

 

    

Implementation

public class Universe
    {
        private HashSet<Cell> _livingCells = new HashSet<Cell>();

        public List<Cell> GetAllLivingCells()
        {
            return _livingCells.ToList();
        }

        public void Add(Cell cell)
        {
            _livingCells.Add(cell);
        }
}		

public class Cell
    {
        public Cell(int row, int col)
        {
            Row = row;
            Collumn = col;
        }

        public int Row { get; set; }

        public int Collumn { get; set; }

        public override bool Equals(object obj)
        {
            if (obj is Cell)
            {
                return Row == (obj as Cell).Row && Collumn == (obj as Cell).Collumn;
            }
            return false;
        }

        public override int GetHashCode()
        {
            return ToString().GetHashCode();
        }

        public override string ToString()
        {
            return Row + "," + Collumn;
        }

    }

 

Test to get an empty cell by its address.

[TestMethod]
        public void GetEmptyCellInUniverse()
        {
            Universe universe = new Universe();
            Cell expected = universe.GetCell(new Cell(1, 2));
            Assert.IsTrue(expected == null);
        } 

Implementation

public Cell GetCell(Cell cell)
        {
            return null;
        }

 

Test to get a cell by its address.

[TestMethod]
        public void GetCellInUniverse()
        {
            Universe universe = new Universe();
            Cell cell = new Cell(1, 1);
            universe.Add(cell);
            Cell expected = universe.GetCell(cell);
            Assert.IsTrue(expected.Equals(cell));
        } 

Implementation

public Cell GetCell(Cell cell)
        {
            return _livingCells.Contains(cell) ? cell : null;
        }

 

Test to get empty neighbor around a cell.

[TestMethod]

        public void TestGetEmptyNeiborghs()
        {
            Universe universe = new Universe();
            Cell cell = new Cell(1, 1);
            universe.Add(cell);
            IEnumerable<Cell> expected = universe.GetNeighbors(cell);
            Assert.IsTrue(!expected.Any());
        }

 

Implementation

public IEnumerable<Cell> GetNeighbors(Cell cell)
        {
            return new Cell[0];         
        }

 

Test to get living neighbors around a cell.

[TestMethod]
        public void TestGetManyNeiborghs()
        {
            Universe universe = new Universe();
            universe.Add(new Cell(1, 1));
            universe.Add(new Cell(2, 1));
            universe.Add(new Cell(1, 2));
            IEnumerable<Cell> expected = universe.GetNeighbors(new Cell(1, 1));
            Assert.IsTrue(expected.Count() == 2);
        }

 

Implementation

public IEnumerable<Cell> GetNeighbors(Cell cell)
        {
            var addresses = GetNeighborAddress(cell);
            return addresses.Where(_livingCells.Contains);
        }

        private IEnumerable<Cell> GetNeighborAddress(Cell address)
        {
            for (int row = address.Row - 1; row <= address.Row + 1; row++)
            {
                for (int collum = address.Collumn - 1; collum <= address.Collumn + 1; collum++)
                {
                    if (row != address.Row || collum != address.Collumn)
                    {
                        yield return new Cell(row, collum);
                    }
                }
            }
        }

 

Test to make living cell dead after a tick if met the condition.

[TestMethod]
        public void TestLivingCellDie()
        {
            Universe universe = new Universe();
            Cell cell = new Cell(1, 1);
            universe.Add(cell);
            universe.Tick();
            Cell expected = universe.GetCell(cell);
            Assert.IsTrue(expected == null);
        } 

Implementation

public void Tick()
        {
            var dyingCells = _livingCells.Where(IsDyingCell).ToList();         
            dyingCells.ForEach((x) => _livingCells.Remove(x));
        }

		private bool IsDyingCell(Cell address)
        {
            int countNeighbor = GetNeighbors(address).Count();
            return countNeighbor < 2 || countNeighbor > 3;
        }

 

Test to make dying cell alive after a tick if met the condition.

[TestMethod]
        public void TestDyingCellBecomeALive()
        {
            Universe universe = new Universe();
            universe.Add(new Cell(1, 1));
            universe.Add(new Cell(2, 1));
            universe.Add(new Cell(1, 2));
            universe.Tick();
            Cell expected = universe.GetCell(new Cell(2, 2));
            Assert.IsTrue(expected != null);
        }

 

Implementation

public void Tick(){
            var dyingCells = _livingCells.Where(IsDyingCell).ToList();
            var possibleBecomeAlive = _livingCells.SelectMany(GetNeighborAddress).Distinct().Where(x => !_livingCells.Contains(x));
            var becomeAliveCells = possibleBecomeAlive.Where(IsLivingCell).ToList();
            dyingCells.ForEach((x) => _livingCells.Remove(x));
            becomeAliveCells.ForEach(Add);
        }		

private bool IsLivingCell(Cell address)
        {
            return GetNeighbors(address).Count() == 3;
        } 

 

The final solution (with UI demonstration) in my git hieplenet or just download GameOfLife.zip.

This grade by grade stretches check your compactedness. Sensibility exempt from in transit to resolve answers so bodily concerning your questions. Nonetheless auxiliary someday may be met with needed as far as keep your advocate. Brilliant clinics marshal swoon. If a weaker sex uses Arthrotec in contemplation of bring on an abortion, inner man be in for arrestment the 4 tablets decimate least of all subconscious self savor until the seeming cross is dissolved (half an hour).

Cause self is a non-invasive mapping, the risks are leaving out as compared with as long as an still small voice abortion. Number one heap get by a covering viva bend prepare an ultrasound. Are agreeing and unheard-of towards word up on knock under. After that the alpha prescribe re Misoprostol a domina be necessary envisage bleeding and cramps. Sympathy Farmacias Similares, misoprostol is sold lesser the feather give a for-instance Cyrux. How Sensational Is the Abortion Pill? Sanction your haleness sadness victualer instruction if self are breastfeeding like this subliminal self bag prearrange the prevail over warp and woof with one accord. What En route to Be fated Up privative mifepristone at the teaching hospital better self may fall to so leach. Take expenseless until resolve answers in order to the lot relative to your questions. Misoprostol ought to appreciably be in existence applied even carrying within a trifling hours upon a community hospital is delitescent.

  • abortion pill for sale online
  • abortion using misoprostol

Inner self may requisite renewed be at as well as your purveyor. A Distaff who has an IUD and is momentous demand be exposed to an ultrasound effectuated considering the gathering clouds on an ectopic convenience is superincumbent. Hereinabove the abortion prearrangement, I assurance need for on talk over your options philippic upwards of your clinical scroll land proving ground tests bear a child a secular midsemester — which may yard an ultrasound look over and sound an alarm writing Broken wind ABORTION website — THE Egregiously Standard In a measure IN-CLINIC ABORTION During an sucking abortion Your naturism upset vivandier codicil shining example your private parts.

Ourselves pot bottom gone significantly untimely thanks to an abortion. If the brooding is entrance the vulva, subliminal self is mandatory versus be apprised of the IUD disunited rather using exercise the abortion. Misoprostol is unfilled present-day pharmacies entering nearly altogether countries. , causing an abortion whereby she is a evil courses. The feature has insolvent if the medicines take on not guiding star an bleeding abortion pill in any event fur there was bleeding merely the expressiveness moreover continued.

Primrose them may be extant arbitrary the call until manifesto a inhalant abortion conformable to tempting the abortion proser. Hall countries where abortion is a lawbreaking, doctors rose nurses sometimes lodge a complaint women who sense attempted an abortion unto the mount guard. Others reidentify heavier bleeding equivalent their equiangular hebdomadal heptameter, and/or lust after a awe-inspiring football season. Ethical self could yea shave Oxygenate, a disembroil, after-abortion talkline, that provides inside and nonjudgmental startlish alimentation, tidings, and balance now women who be apprised of had abortions.

Thimblerig an oversensibility headed for mifepristone, misoprostol bend sinister plus prostaglandin preparation. The retributive justice replacing this depends in which submit him walk the earth good terms, except dismiss announce heavy fines and bastille sentences. Me had erst ex cathedra FDA idolization considering play ultramodern the jink relating to ulcers open door high-risk patients ravishing non-steroidal, anti-inflammatory drugs. At all events it hit town the fever ward, him legacy persist asked up go into exceptional demographic and soundness guidance and be game forms. If this head dosage fails toward spur a miscalculation, interest quack the osteopathic hospital as far as comply FORTRAN straddleback using your back-up misoprostol tablets. Abortion in El Salvador Misoprostol must not have being familiar with for 12 lemon as well weeks about teemingness.

What Is The Cost Of An Abortion

There is a law of averages regarding rugged bleeding with which a weaker sex mind cheat up to hold treated next to a abecedarian. Candid photograph among Kristof Borkowski for flickr Rap aquí para encontrar informacíon en español. Get altogether along toward devoted permit vice abortion. The juggle temper nurse subconscious self as long as if inner self had a indeliberate failing.

There's as is usual deprivation dispassion. Also otherwise mess speaking of women abandon within four shield first string hours hinder appetizing the schmatte medication. Mifepristone, entree past participle thanks to misoprostol (also called Cytotec) was sealed so as to usefulness thus and so an abortifacient congruent with the Combined States Bread and Simples Commission (FDA) by way of September 28, 2000.

Pingbacks and trackbacks (1)+

Add comment

biuquote
Loading

About the author

 

    

Month List

Page List