康威性命游戏的简朴完成

性命游戏,数学家 John Conway 发现的一个游戏,又称康威性命演变,性命棋,细胞自动机。

康威有很多好玩风趣的发现,最广为人知的一个是表面数列(Look-and-Say),这里不多说,另一个就是性命游戏(Game-of-Life)。

关于康威,摘录一段 Wikipedia 的叙说:

约翰·何顿·康威(John Horton Conway,1937年12月26日-),生于英国利物浦,数学家,活跃于有限群的研讨、意见意义数学、纽结理论、数论、组合博弈论和编码学等范畴。
康威幼年时就对数学很有强烈的兴趣:四岁时,其母发现他背诵二的次方;十一岁时,升读中学的面试,被问及他成长后想干甚么,他回复想在剑桥当数学家。后来康威果真于剑桥大学修读数学,现时为普林斯顿大学的传授。

性命游戏模仿的是二维平面上性命的演变过程。

划定规矩很简朴:每一个细胞有两种状况–存活或殒命,每一个细胞与以自身为中间的四周八格细胞发生互动。

  1. 假如一个活细胞四周有2至3个活细胞,鄙人一个阶段继承存活,不然殒命;

  2. 假如一个死细胞四周有3个活细胞,鄙人一个阶段将变成活细胞,不然继承坚持殒命

康威性命游戏是简朴划定规矩发生庞杂变化的典范例子。在演变过程当中,能够看到一些异常美好的变化,和一些幽美的几何图形。

下面是用 HTML5 Canvas 完成的一个简朴版本

源码:https://github.com/mirreal/moon9/tree/master/GameOfLife

DEMO:http://mirreal.net/game-of-life/

JS代码以下:

function Game() {
  this.stones = [];
  this.canvas = new Canvas();

  this.init();
}

Game.prototype.init = function() {
  var self = this;

  this.createRandomStones();
  this.draw();

  this.getAroundStones();

  this.eventHandler();
  
  this.loop = setInterval(function() {
    self.update();
    self.draw();
  }, 120);
};

Game.prototype.eventHandler = function() {
  var self = this;

  var snapshotButton = document.getElementById('snapshotButton'),
      snapshotImageElement = document.getElementById('snapshotImageElement'),
      canvas = document.getElementById('canvas');

  snapshotButton.onclick = function(event) {
    event.preventDefault();

    if (snapshotButton.innerHTML == 'Snapshot') {
      clearInterval(self.loop);
      var dataUrl = canvas.toDataURL();
      snapshotImageElement.src = dataUrl;
      snapshotImageElement.style.display = 'inline';
      canvas.style.display = 'none';
      snapshotButton.innerHTML = 'Continue';
    } else {
      self.loop = setInterval(function() {
        self.update();
        self.draw();
      }, 800);
      canvas.style.display = 'inline';
      snapshotImageElement.style.display = 'none';
      snapshotButton.innerHTML = 'Snapshot';
    }
  };
};

Game.prototype.createRandomStones = function() {
  for (var i = 0; i < 32; i++) {
    for (var j = 0; j < 32; j++) {
      var status = Math.random() < 0.2 ? true : false;
      this.stones.push(new Stone({x: i, y: j}, status))
    }
  }
};

Game.prototype.draw = function() {
  var self = this;

  this.canvas.drawGrid("lightgrey", 20, 20);
  this.stones.forEach(function(stone) {
    if (stone.status === true) {
      self.canvas.drawStone(stone);
    }
  });
};

Game.prototype.getAroundStones = function() {
  var self = this;

  this.stones.forEach(function(stone) {
    stone.around.forEach(function(position) {
      stone.aroundStones.push(self.stones[32*position.x + position.y]);
    });
  });
};

Game.prototype.update = function() {
  var self = this;

  this.stones.forEach(function(stone) {
    stone.aroundStones.forEach(function(s) {
      if (s.status === true) stone.aliveCount += 1;
    });

    if (stone.status === true) {
      if (stone.aliveCount === 2 || stone.aliveCount === 3) {
        stone.nextStatus = true;
      } else {
        stone.nextStatus = false;
      }
    } else {
      if (stone.aliveCount === 3) stone.nextStatus = true;
      else stone.nextStatus = false;
    }
  });

  this.stones.forEach(function(stone) {
    stone.status = stone.nextStatus;
    stone.aliveCount = 0;
  });
}




function Stone(position, status) {
  this.x = position.x;
  this.y = position.y;

  this.status = status;
  this.nextStatus = false;

  this.aroundStones = [];
  this.aliveCount = 0;

  this.around = [];
  this.getAround();
}

Stone.prototype.getAround = function() {
  for (var i = this.x-1; i <= this.x+1; i++) {
    for (var j = this.y-1; j <= this.y+1; j++) {
      if (i == this.x && j == this.y) continue;
      if (i < 0 || i >= 32) continue;
      if (j < 0 || j >= 32) continue;
      this.around.push({x: i, y: j});
    }
  }
};


function Canvas() {
  this.canvas = document.getElementById('canvas');
  this.context = canvas.getContext('2d');
}

Canvas.prototype.drawGrid = function(color, stepx, stepy) {
  var canvas = this.canvas;
  var ctx = this.context;

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.save();
  ctx.strokeStyle = color;
  ctx.lineWidth = 0.5;

  for (var i = stepx + 0.5; i < ctx.canvas.width; i += stepx) {
    ctx.beginPath();
    ctx.moveTo(i, 0);
    ctx.lineTo(i, ctx.canvas.height);
    ctx.stroke();
    ctx.closePath();
  }
  
  for (var i = stepy + 0.5; i < ctx.canvas.height; i += stepy) {
    ctx.beginPath();
    ctx.moveTo(0, i);
    ctx.lineTo(ctx.canvas.width, i);
    ctx.stroke();
    ctx.closePath();
  }
  ctx.restore();
};

Canvas.prototype.drawStone = function(stone) {
  var ctx = this.context;

  var x = 20 * stone.x + 10;
  var y = 20 * stone.y + 10;

  ctx.fillStyle = 'orange';
  ctx.beginPath();
  ctx.arc(x, y, 9, 0, Math.PI*2, false);
  ctx.closePath();
  ctx.fill();
};

new Game();

TIPS:

在Google搜刮 Conway's Game of Life ,会看到Google的一个完成。

    原文作者:离独逸
    原文地址: https://segmentfault.com/a/1190000000671779
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞