Versionsvergleich

Aus ProgrammingWiki

Vergleich: 2009-04-30T07:20:34+00:00 → 2015-06-02T18:13:25+00:00

−
<language>Java</language>
+
<language>Javascript</language>
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];
+
<run id="556df1d7d39e5">
+
var w = 20; 
+
var h = 10;
+
var Spielfeld = [];
+
for(var i=0; i<w; i++) Spielfeld[i] = []; // 2D Array anlegen
−
for(int i=0; i<10; i++) Spielfeld[5+i][4] = 1;
+
for(var i=0; i<10; i++) Spielfeld[5+i][4] = 1; // Mauern setzen
−
void drawCell(int x, int y, boolean black){
+
function drawCell(x, y, 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(int y=0; y<h; y++)
+
function drawCells(){
+
  for(var x=0; x<w; x++)
+
   for(var y=0; y<h; y++)
    drawCell(x,y,Spielfeld[x][y] == 1);
}
−
int countNeighbors(int x, int y){
−
  int r = 0;
+
function countNeighbors(x, y){
+
  var r = 0;
  if(x>0   && Spielfeld[x-1][y] == 1) r++; 
  if(x<w-1 && Spielfeld[x+1][y] == 1) r++; 
  if(y>0   && Spielfeld[x][y-1] == 1) r++; 
  if(y<h-1 && Spielfeld[x][y+1] == 1) r++; 
  if(x>0   && y>0    && Spielfeld[x-1][y-1] == 1) r++; 
  if(x>0   && y<h-1  && Spielfeld[x-1][y+1] == 1) r++; 
  if(x<w-1 && y>0    && Spielfeld[x+1][y-1] == 1) r++; 
  if(x<w-1 && y<h-1  && Spielfeld[x+1][y+1] == 1) r++; 
  return r;
}
−
void flipCells(){
−
  int[][] SpielfeldNeu = new int[w][h];
−
  for(int x=0; x<w; x++)
−
   for(int y=0; y<h; y++){
−
    int neighbors = countNeighbors(x,y); 
+
function flipCells(){
+
  var SpielfeldNeu = [];
+
  for(var i=0; i<w; i++) SpielfeldNeu[i] = []; // 2D Array anlegen
+
  for(var x=0; x<w; x++)
+
   for(var y=0; y<h; y++){
+
    var neighbors = countNeighbors(x,y); 
    SpielfeldNeu[x][y] = Spielfeld[x][y];
    if(Spielfeld[x][y] == 1){
     if (neighbors  < 2 || neighbors  > 3) SpielfeldNeu[x][y] = 0;
    }else{
     if (neighbors  == 3) SpielfeldNeu[x][y] = 1;
    }
   }
  Spielfeld = SpielfeldNeu;
}
canvas.clear();
−
while(true) { drawCells(); flipCells(); Thread.sleep(100); }
−
</eval>
+
if(window.runInterval) clearInterval(window.runInterval);
+
window.runInterval = setInterval(function(){
+
  drawCells(); flipCells(); 
+
},100);
+
</run>
+
<canvas h=225></canvas>