Canvas Demo 3

Aus ProgrammingWiki
Archivierte Version vom 2009-04-30T07:20:34+00:00. Aktuelle Version

The Game of Life is not your typical computer game. It is a 'cellular automaton', and was invented by Cambridge mathematician John Conway.

For a space that is 'populated':

  • Each cell with one or no neighbors dies, as if by loneliness.
  • Each cell with four or more neighbors dies, as if by overpopulation.
  • Each cell with two or three neighbors survives.

For a space that is 'empty' or 'unpopulated'

  • Each cell with three neighbors becomes populated.

<eval> int w = 20; int h = 10; int[][] Spielfeld = new int[w][h];</eval>

for(int i=0; i<10; i++) Spielfeld[5+i][4] = 1;

void drawCell(int x, int y, boolean black){

 if(black) canvas.setColor(0,0,0); else 
           canvas.setColor(255,255,255);
 canvas.fillRect(50+x*25,y*25,25,25);           

}

void drawCells(){

 for(int x=0; x<w x for y="0;" drawcell><p>}</p><p>int countNeighbors(int x, int y){</p><pre> int r = 0;
 if(x&gt;0   &amp;&amp; Spielfeld[x-1][y] == 1) r++; 
 if(x<w-1 spielfeld r if>0   &amp;&amp; Spielfeld[x][y-1] == 1) r++; 
 if(y<h-1 spielfeld r if>0   &amp;&amp; y&gt;0    &amp;&amp; Spielfeld[x-1][y-1] == 1) r++; 
 if(x&gt;0   &amp;&amp; y<h-1 spielfeld r if y>0    &amp;&amp; Spielfeld[x+1][y-1] == 1) r++; 
 if(x<w-1 y spielfeld r return><p>}
void flipCells(){</p><pre> int[][] SpielfeldNeu = new int[w][h];
 for(int x=0; x<w x for y="0;" int neighbors="countNeighbors(x,y);" spielfeldneu spielfeld if> 3) SpielfeldNeu[x][y] = 0;
   }else{
    if (neighbors  == 3) SpielfeldNeu[x][y] = 1;
   }
  }
 Spielfeld = SpielfeldNeu;</w></pre><p>}</p><p><br></p><p>canvas.clear();
while(true) { drawCells(); flipCells(); Thread.sleep(100); }
</p>Ihr Browser unterstützt Canvas nicht.
</w-1></h-1></h-1></w-1></pre></w>