Small ape circle HTML5 tutorial how to quickly implement a simple canvas maze game

Now a variety of game industry, from the earliest Battle City, Super Mario and now the League, stimulate the battlefield and so numerous, do you remember the first maze game? Small circle web front end apes lecturer today is how quickly you implement a simple canvas labyrinth game that lets you recall childhood.

This little game is not difficult to achieve, let us think about it, what are the basic elements of a maze games. First, of course, you have to have a map, and then have to have a mobile villain, we use these two cavans to draw, followed by an object moving program that includes two aspects:

1, let us object with the specified instructions to move;
2, whether the object hit the wall or outlet.
Draw a map of the maze and move villain

The main steps of mapping is:
get a map image
using the cavans draw the image.

Maze map generation can be obtained by means of Google in a maze online generator.

Draw villain is the same picture directly to a villain can be, but to note here is that to find a square picture, because for a while we need to do collision detection movement, square better judgment.

Next step is to write a function to draw the main villain of the maze and

function drawMaze(mazeFile, startingX, startingY) {
var imgMaze = new Image()
imgMaze.onload = function () {
// 画布大小调整
canvas.width = imgMaze.width
canvas.height = imgMaze.height

// 绘制笑脸
var imgFace = document.getElementById("face")
context.drawImage(imgMaze, 0, 0)

x = startingX
y = startingY
context.drawImage(imgFace, x, y)
context.stroke()

}
imgMaze.src = mazeFile
}

mazeFile is a maze picture address, startingX and startingY, is the starting point coordinates. In the picture the way here with the introduction of two kinds, because the villain of the picture I do not frequently changed, write directly in the page, intended to map the maze made variable, introduced js, you want to have pictures there is no direct problem with js introduced. Other parts of relatively simple, not repeat them.

Move functions

The main principles of the movement are:

Accept the specified user input (in this case, in response to a direction key), into corresponding movement commands. Then periodic inspections movement command corresponding to the target position drawn. Here is a simple example:

For example each time a direction key is pressed, it moves upwards should be recorded, then every 100 milliseconds to check the current movement command, rendering the target point to be moved, the process is repeated. The code is relatively simple:

// Move functions
function processKey (E) {
DX = 0
Dy = 0
left direction key detection @
IF (e.keyCode 38 is ===) {
Dy = -1
}
IF (e.keyCode === 40) {
. 1 = Dy
}
IF (37 [e.keyCode ===) {
DX = -1
}
IF (e.keyCode === 39) {
DX =. 1
}
}

// Draw frame
function drawFrame () {
IF (DX! = 0 || Dy! = 0) {
// context.clearRect (X, Y, canvas.width, canvas.height)
// Draw trajectories
context.beginPath ( );
context.fillStyle = "RGB (254,244,207)"
context.rect (X, Y, 15, 15)
context.fill ()
X = DX +
Y + Dy =
// collision detection
IF (checkForCollision ()) {
X - DX =
Y - Dy =
DX = 0
Dy = 0
}

//绘制小人应该移动的地点
var imgFace = document.getElementById('face')
context.drawImage(imgFace, x, y)

if (canvas.height - y < 17) {
  // isFirst = false
  alert('恭喜你通关 游戏结束')
  return false
}
// 这里如果重置的话变成非自动移动,也就是每按下一次方向键只前进一步,由于目前体验不好所以先不做重置
// dx = 0
// dy = 0

}
setTimeout(drawFrame, 20)
}

In the above code, the mobile function is relatively simple, the more important function inside the frame is drawn collision detection function, explained in detail below.

Impact checking

To detect whether an object colliding with the wall, usually to first save the map information into memory, and then detect whether the collision with the wall in a current moving object, but because of our background is black and white maze map, so you can use color to detect collisions. Specific approach is:

Get the current coordinate position of the object, using the current color canvas detect this position on whether the map is black, and if so, say yes yes wall, move should not be performed, the following is the code:

function checkForCollision() {
var imageData = context.getImageData(x - 1, y - 1, 15 + 2, 15 + 2)
var pixels = imageData.data

for (var i = 0, len = pixels.length; i < len; i++) {
var red = pixels[i],
green = pixels[i + 1]
blue = pixels[i + 2]
alpha = pixels[i + 3]

// 检测是否碰到黑色的墙
if (red === 0 && green === 0 && blue === 0) {
  return true
}

}
return false
}

Here, 15 is the width of the villain, we detect the villain sides 1px range (corresponding to the code getImageData (x - 1, y - 1 lower, 2 + 15, 15 + 2) may be why there is little thought + 2), if it is black, the collision is detected.

the remaining:

In the code, I added some other features, such as prompt answers and so on. As for the replacement map is relatively simple: there is a corresponding map file address, starting coordinates, the answer pictures and path of an object, and then set up a map array, click on the map and re-rendering when switching on it. There are some places worth optimization, such as:

Collision detection in the corner where the experience of the poor;
the trajectory of the current situation is running, how in answer mode should remove the track?
Interested students can try to lower their own implementation.

The above is how to quickly implement a simple canvas maze game, what are you waiting for go and run the installation environment go, if you encounter a problem you can find small circle web front end apes instructor to answer, if you want to learn html5 development, small ape circle is still very good, there is a need to look at directly.

Guess you like

Origin blog.csdn.net/weixin_44867000/article/details/92576898