1024快乐!
用html+js模拟兰顿蚂蚁(Langton‘s Ant)。地图和蚂蚁是分离的,地图自动扩充,地图能拖动缩放,可以添加干扰,,bug未知
兰顿蚂蚁,是于1986年,由克里斯·兰顿提出来的,属于细胞自动机的一种。
平面上的正方形格子被填上黑色或白色。在其中一格正方形内有一只“蚂蚁”。
蚂蚁的头部朝向为:上下左右其中一方。蚂蚁的移动规则十分简单:
若蚂蚁在黑格,右转90度,将该格改为白格,并向前移一格;
若蚂蚁在白格,左转90度,将该格改为黑格,并向前移一格。规则虽然简单,蚂蚁的行为却十分复杂。刚刚开始时留下的路线都会有接近对称,像是会重复,但不论起始状态如何,蚂蚁经过漫长的混乱活动后,会开辟出一条规则的“高速公路”。
<!-- ######################################################################### -->
<button onclick="nextSteps(1)">下一步</button>
<button onclick="nextSteps(10)">下10步</button>
<button onclick="nextSteps(100)">下100步</button>
<button onclick="nextSteps(1000)">下1000步</button>
<button onclick="nextSteps()">下N步</button>
<input type='number' min=1 max=10000 value=100 id="stepsCount">
<button onclick="randomDots()">干扰点</button>
<button onclick="nextStepsStart()">开始</button>
<button onclick="nextStepsStop()">停止</button>
步数:<span id='stepsTotal'>0</span>
<br>
<canvas id="out" width="800px" height="600px" style="border:2px solid #777;"></canvas>
<script>
function CellMap(canvasId = 'out', initMapWidth = 50, initMapHeight = 50, mapWidthMax = 100000, mapHeightMax = 100000) {
this.canvasId = canvasId;
this.map = null;
this.mapWidth = initMapWidth;
this.mapHeight = initMapHeight;
this.mapWidthMax = mapWidthMax;
this.mapHeightMax = mapHeightMax;
this.canvas = null;
this.cctx = null;
this.mapImageZoomMin = 0.5;
this.mapImageZoomMax = 10;
this.cellBaseWidth = 8;
this.mapImageZoom = 1;
this.mapImageOffsetX = 0;
this.mapImageOffsetY = 0;
this.mapImageWidth = null;
this.mapImageHeight = null;
// ------------------------------------
this.init = function() {
this.initMap();
this.initCanvas();
this.initVMap();
}
this.initMap = function() {
this.map = Array(this.mapHeight);
for (var i = 0, len = this.mapHeight; i < len; i++) {
this.map[i] = Array(this.mapWidth);
}
}
this.initCanvas = function() {
this.canvas = document.getElementById(this.canvasId);
this.canvasWidth = this.canvas.width;
this.canvasHeight = this.canvas.height;
//console.log(this.canvas, this.canvasWidth, this.canvasHeight);
this.cctx = this.canvas.getContext("2d");
this.cctx.strokeStyle = '#aaa';
this.cctx.fillStyle = '#888';
this.cctx.lineWidth = 1;
this.cctx.translate(0.5,0.5);
}
// 支持缩放和拖动地图
this.bindCanvasEvent = function() {
var that = this;
var down = false;
var x1, x2, y1, y2;
this.canvas.onmousedown = function(evt) { // 触发鼠标按下
down = true;
x1 = evt.offsetX;
y1 = evt.offsetY;
}
this.canvas.onmouseup = function(evt) { // 触发鼠标抬起
down = false;
x2 = evt.offsetX;
y2 = evt.offsetY;
that.moveMapImageDisplayArea(x2 - x1, y2 - y1);
}
this.canvas.onmousemove = function(evt) { // 触发鼠标拖动
if (!down) {
return;
}
var x =