Skip to content

Instantly share code, notes, and snippets.

@Putnam3145
Last active March 15, 2019 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Putnam3145/9a5d65d0577dd4ef73dc554c5f899515 to your computer and use it in GitHub Desktop.
Save Putnam3145/9a5d65d0577dd4ef73dc554c5f899515 to your computer and use it in GitHub Desktop.
Generic programming lifelike cellular automata in D
private struct LifeLikeRule
{
ubyte notZero;
bool zero;
this(ushort initializer)
{
notZero=cast(ubyte)(initializer>>1);
zero=initializer&1;
}
pure ushort fullRule()
{
return cast(ushort)((notZero<<1)+zero);
}
pure ushort fullRule(ushort initializer)
{
notZero=cast(ubyte)(initializer>>1);
zero=initializer&1;
return fullRule;
}
alias fullRule this;
}
private struct LifeLike(LifeLikeRule birth,LifeLikeRule survive)
{
bool state=false;
alias state this;
pure bool opCall(ubyte numNeighbors) //pure only if you accept previous state as an implicit argument
{
auto neighbors=1<<numNeighbors;
if(neighbors&birth)
{
state=true;
}
else if(!(neighbors&survive))
{
state=false;
}
return state;
}
pure bool opCall()
{
return state=false;
}
}
/**
Expects arguments in a binary format with 9 bits representing number of neighbors.
First bit is 8 neighbors, second bit is 7 and so on down to 0.
*/
template LifeLike(ushort birth,ushort survive)
{
alias LifeLike=LifeLike!(LifeLikeRule(birth),LifeLikeRule(survive));
}
///Conway's Game of Life using the above syntax.
alias GameOfLife=LifeLike!(0b000001000,0b000001100);
unittest
{
GameOfLife lifeTile;
assert(!lifeTile);
assert(lifeTile(3));
assert(lifeTile(2));
assert(!lifeTile(4));
assert(!lifeTile(2));
LifeLike!(0b011111110,0b000000001) otherTile;
assert(!otherTile);
assert(!otherTile(0));
static foreach(i;1..7)
{
assert(otherTile(i));
}
assert(otherTile(0),"survival isn't working?");
assert(!otherTile(8));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment