Good morning, hope everyone is well and keeping safe. I am learning JavaScript and still struggling with some parts.
I am trying to create a kind of slot machine and need to find a way to keep the blocks individual with their colours but it is not working. Can someone please help me?
Bellow is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Slot Machine</title>
</head>
<body>
<canvas id="canvas" width="1000" height="2000"></canvas>
<script>
var game = {
tickNumber: 0,
timer: null,
board: [
"####################",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"####################"
],
tick: function() {
game.tickNumber++;
snake.move();
graphics.drawGame();
game.timer = window.setTimeout("game.tick()", 500);
}
};
var snake = {
parts: [
{x: 2, y: 2, color: "green"},
{x: 2, y: 6, color: "red"},
{x: 2, y: 10, color: "blue"},
{x: 2, Y: 14, color: "yellow"},
{x: 2, Y: 16, color: "grey"}
],
facing: "S",
nextLocation: function() {
var snakeHead = snake.parts[0];
var targetX = snakeHead.x;
var targetY = snakeHead.y;
targetY = snake.facing == "S" ? targetY + 4 : targetY;
if (targetY >= 24) {
targetY = 2;
}
return {x: targetX, y: targetY};
},
move: function() {
var location = snake.nextLocation();
snake.parts.unshift(location);
snake.parts.pop();
}
};
var graphics = {
canvas: document.getElementById("canvas"),
squareSize: 20,
squarePic: 60,
drawBoard: function(ctx) {
var currentYoffset = 0;
game.board.forEach(function checkLine(line) {
line = line.split('');
var currentXoffset = 0;
line.forEach(function checkCharacter(character) {
if(character == '#') {
ctx.fillStyle = "black";
ctx.fillRect(currentXoffset, currentYoffset, graphics.squareSize, graphics.squareSize);
}
currentXoffset += graphics.squareSize;
});
currentYoffset += graphics.squareSize;
});
},
drawSnake: function(ctx) {
snake.parts.forEach(function drawPart(part) {
var partXlocation = part.x * graphics.squareSize;
var partYlocation = part.y * graphics.squareSize;
var coloracao = part.color;
ctx.fillStyle = coloracao;
ctx.fillRect(partXlocation, partYlocation, graphics.squarePic, graphics.squarePic);
});
},
drawGame: function () {
var ctx = graphics.canvas.getContext("2d");
ctx.clearRect(0,0, graphics.canvas.width, graphics.canvas.height);
graphics.drawBoard(ctx);
graphics.drawSnake(ctx);
}
};
graphics.drawGame();
var gameControl = {
startGame: function() {
game.tick();
}
};
gameControl.startGame();
</script>
</body>
</html>