// life.c               Section: 14.2
//      Copyright 1994, Center for Computer Vision and Visualization,
//      University of Florida.  All rights reserved.
// The game of life as described by John Conway.

#include "life.h"
#include "UcharConv.h"


// Note that by using a different template or different set of
//      values the rules for the game of "life" can be quite
//      easily changed.  Because of this this interface will
//      have two versions.
// The first assumes the standard game, and follows those rules.
// The second simply assumes the correct way to play the game
//      is by performing a linear_product and a chi test.
// Both versions allow more than one interation to be requested.


IA_DDTemplate<IA_Image<IA_Point<int>,u_char> >
standard_life_template() {

    IA_Image<IA_Point<int>,u_char>
	rules_image( IA_boxy_pset( IA_Point<int>( -1, -1 ),
				   IA_Point<int>(  1,  1 ) ),
		     1 );
    rules_image[ IA_Point<int>( 0, 0 ) ] = 9;

    return
	IA_DDTemplate<IA_Image<IA_Point<int>,u_char> >(
	    2, rules_image );
}


IA_Image<IA_Point<int>,u_char>
life( const IA_Image<IA_Point<int>,u_char> & citizens,
      unsigned int iterations /* = 1 */ ) {

    return
	life( citizens,
	      standard_life_template(),
	      IA_Set<u_char>( 3, 11, 12 ),
	      iterations );
}


IA_Image<IA_Point<int>,u_char>
life( const IA_Image<IA_Point<int>,u_char> & citizens,
      const IA_DDTemplate<IA_Image<IA_Point<int>,u_char> > & rules,
      const IA_Set<u_char> & limits,
      unsigned int iterations /* = 1 */ ) {

    IA_Image<IA_Point<int>,u_char>
	ctzns( citizens );  // Make a working copy
    for( int i=0; i<iterations; i++ ) {
	ctzns = chi_contains( linear_product( ctzns, rules ),
			      limits );
    }
    return ctzns;
}

