Simple Maze
Simple javascript maze game.
by realhunts
HTML
<canvas id="GameBoardCanvas" width="400px" height="400px">
</canvas>
CSS
#GameBoardCanvas {
border: 1px solid red;
padding: 5px;
margin-left: auto;
margin-right: auto;
}
body {
background: black;
padding: 5px;
}
JavaScript
var canvas = $('#GameBoardCanvas');
//The game board 1 = walls, 0 = free space, and -1 = the goal
var board = [
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[ 1, 0, 1, 0, 0, 0, 0, 0, 1, 0],
[ 0, 0, 0, 0, 1, 1, 1, 0, 1, 0],
[ 0, 1, 1, 0, 0, 0, 1, 0, 1, 0],
[ 0, 0, 1, 1, 1, 1, 1, 0, 1, 0],
[ 1, 0, 1, 0, 0, 0, 1, 0, 1, 0],
[ 1, 0, 1, 0, 1, 0, 1, 0, 0, 0],
[ 1, 0, 1, 0, 1, 0, 0, 1, 1, 0],
[-1, 0, 1, 0, 1, 1, 0, 0, 0, 0]
];
var player = {
x: 0,
y: 0
};
//Draw the game board
function draw(){
var width = canvas.width();
var blockSize = width/board.length;
var ctx = canvas[0].getContext('2d');
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, width, width);
ctx.fillStyle="white";
//Loop through the board array drawing the walls and the goal
for(var y = 0; y < board.length; y++){
for(var x = 0; x < board[y].length; x++){
//Draw a wall
if(board[y][x] === 1){
ctx.fillRect(x*blockSize, y*blockSize, blockSize, blockSize);
}
//Draw the goal
else if(board[y][x] === -1){
ctx.beginPath();
ctx.lineWidth = 5;
ctx.strokeStyle = "gold";
ctx.moveTo(x*blockSize, y*blockSize);
ctx.lineTo((x+1)*blockSize, (y+1)*blockSize);
ctx.moveTo(x*blockSize, (y+1)*blockSize);
ctx.lineTo((x+1)*blockSize, y*blockSize);
ctx.stroke();
}
}
}
//Draw the player
ctx.beginPath();
var half = blockSize/2;
ctx.fillStyle = "blue";
ctx.arc(player.x*blockSize+half, player.y*blockSize+half, half, 0, 2*Math.PI);
ctx.fill();
}
function animate(){
requestAnimationFrame(animate)
if(canMove(player.x+1, player.y))player.x += .2;
draw();
}
//animate()
//Check to see if the new space is inside the board and not a wall
function canMove(x, y){
return...