JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
var c = document.getElementById('canvas')
var WDT = c.width = window.innerWidth
var HGT = c.height = window.innerHeight
var ctx = c.getContext('2d')
var SZ = 4
var xMax = Math.floor(WDT / SZ)
var yMax = Math.floor(HGT / SZ)
var matrix, ant
function drawAnt(x, y) {
ctx.fillStyle = '#FF0000'
ctx.fillRect(x * SZ, y * SZ, SZ, SZ)
}
var LangtonAnt = function(x, y, direction) {
this.x = x
this.y = y
this.direction = direction
this.updateDirection = function(isClockwise) {
if (isClockwise) {
this.direction = this.direction >= 3 ? 0 : this.direction + 1
} else {
this.direction = this.direction <= 0 ? 3 : this.direction - 1
}
}
this.move = function() {
switch (this.direction) {
case 0:
this.y--
break;
case 1:
this.x++
break;
case 2:
this.y++
break;
case 3:
this.x--
break;
}
drawAnt(this.x, this.y)
}
}
function getMousePos(event) {
return [event.clientX, event.clientY]
}
function addLangtonAnt(event) {
var mousePos = getMousePos(event)
for (i = 0; i < 2; i++) {
if (mousePos[i] % SZ == 0) {
mousePos[i] = mousePos[i] / SZ
} else {
mousePos[i] = (mousePos[i] - mousePos[i] % SZ) / SZ
}
}
ant = new LangtonAnt(mousePos[0], mousePos[1], 0)
drawAnt(mousePos[0], mousePos[1])
}
function initMatrix() {
matrix = []
for (var xVal = 0; xVal < xMax; xVal++) {
matrix[xVal] = []
for (var yVal = 0; yVal < yMax; yVal++) {
if (xVal == Math.floor(xMax / 2) && yVal == Math.floor(yMax / 2)) {
matrix[xVal][yVal] = 1
ant = new LangtonAnt(xVal, yVal, 0)
drawAnt(xVal, yVal)
} else {
matrix[xVal][yVal] = 0
}
}
}
c.addEventListener('click', function(e) {
addLangtonAnt(e)
repeat = setInterval(function() {
nextStep()
if (ant.x < 0 || ant.x > xMax || ant.y < 0 || ant.y > yMax)
clearInterval(repeat)
}, 0)
})
}
function draw(x, y, isAliveCell) {
ctx.fillStyle = isAliveCell ? '#FFFFFF' : '#000000'
ctx.fillRect(x * SZ, y * SZ, SZ, SZ)
}
function nextStep() {
if (matrix[ant.x][ant.y] == 1) {
ant.updateDirection(true)
matrix[ant.x][ant.y] = 0
draw(ant.x, ant.y, false)
} else if (matrix[ant.x][ant.y] == 0) {
ant.updateDirection(false)
matrix[ant.x][ant.y] = 1
draw(ant.x, ant.y, true)
}
ant.move()
}
initMatrix()
var repeat = setInterval(function() {
nextStep()
if (ant.x < 0 || ant.x > xMax || ant.y < 0 || ant.y > yMax)
clearInterval(repeat)
}, 0)