html5游戏角色行走,HTML5/Canvas 随机行走的小蚂蚁

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值