Animation in Visual 2D Arrays - javascript

I'm currently making a Pacman ghost with visual 2D arrays. I want the ghost to move like this:
I think I would use CSS transitions, but I'm not sure how! If there's a way to do it in javascript, that would be just as helpful. Here is my code:
<!doctype html>
<html>
<head>
<title>Visualizing 2D arrays</title>
<style>
#stage {
position:relative;
}
.cell {
position:absolute;
width:30px;
height:30px;
border:1px solid black;
background-color:black;
}
</style>
</head>
<body>
<div id="stage"></div>
<script>
// GRAB A REFERENCE TO THE STAGE
var stage = document.querySelector("#stage");
// THE 2D ARRAY THAT DEFINES THE PATTERN
var pattern = [
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0],
[0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0],
[0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0],
[0,0,1,2,2,1,1,1,1,2,2,1,1,1,0,0],
[0,0,2,2,2,2,1,1,2,2,2,2,1,1,0,0],
[0,0,3,3,2,2,1,1,3,3,2,2,1,1,0,0],
[0,1,3,3,2,2,1,1,3,3,2,2,1,1,1,0],
[0,1,1,2,2,1,1,1,1,2,2,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
[0,1,1,0,1,1,1,0,0,1,1,1,0,1,1,0],
[0,1,0,0,0,1,1,0,0,1,1,0,0,0,1,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
];
// THE SIZE OF EACH CELL
var SIZE = 30;
// THE SPACE BETWEEN EACH CELL
var SPACE = 10;
// DISPLAY THE ARRAY
var ROWS = pattern.length;
var COLS = pattern[0].length;
// CREATE THE DIVS and POSITION THEM IN THE STAGE... BUT DON'T WORRY ABOUT COLORING THEM HERE!!!!
for (var row = 0; row < ROWS; row++) {
for (var col = 0; col < COLS; col++) {
// CREATE A DIV HTML ELEMENT CALLED CELL
var cell = document.createElement("div");
// SET ITS CSS CLASS TO CELL
cell.setAttribute("class", "cell");
// GIVE EACH OF THE CREATED DIVS A UNIQUE ID
// BASED ON THE ROW# AND COL#
// EXAMPLE : <div id="c-1-2" class="cell"></div>
// In this example, row = 1 and col = 2
cell.setAttribute("id", "c-" + row + "-" + col);
// ADD A CLICK HANDLER TO EACH OF THE INDIVIDUAL DIVS
cell.addEventListener("click", cellClick, false);
// ADD THE DIV HTML ELEMENT TO THE STAGE
stage.appendChild(cell);
// POSITION THE CELL IN THE CORRECT PLACE
// WITH 10 PIXELS OF SPACE AROUND IT
cell.style.top = row * (SIZE + SPACE) + "px";
cell.style.left = col * (SIZE + SPACE) + "px";
}
}
colorizeDivs();
function cellClick() {
// RIP APART THE DIV ID THAT WAS CLICKED ON
// WERE HIDING THE ROW AND COLUMN IN THE ID
// THE FORMAT OF THE ID IS "C-ROW#-COL#"
// EXAMPLE : <div id="c-1-2" class="cell"></div>
// In this example, row = 1 and col = 2
var zpos;
// THE "this" KEYWORD RETURNS THE HTML ELEMENT THAT WAS CLICKED ON
var thisid = this.id;
zpos = thisid.indexOf("-");
thisid = thisid.substr(zpos+1);
zpos = thisid.indexOf("-");
var thisRow = thisid.substr(0,zpos);
var thisCol = thisid.substr(zpos+1);
// now that we have the row and column for this div... change the array
pattern[thisRow][thisCol] += 1;
if (pattern[thisRow][thisCol] > 7) {
pattern[thisRow][thisCol] = 0;
}
colorizeDivs();
}
function colorizeDivs() {
for (var row = 0; row < ROWS; row++) {
for (var col = 0; col < COLS; col++) {
var cell = document.querySelector("#c-" + row + "-" + col);
if (pattern[row][col] === 0) {
cell.style.backgroundColor = "black";
} else if (pattern[row][col] === 1) {
cell.style.backgroundColor = "orange";
} else if (pattern[row][col] === 2) {
cell.style.backgroundColor = "white";
} else if (pattern[row][col] === 3) {
cell.style.backgroundColor = "blue";
} else if(pattern[row][col] === 4) {
cell.style.backgroundColor = "green";
} else if(pattern[row][col] === 5) {
cell.style.backgroundColor = "red";
} else if(pattern[row][col] === 6) {
cell.style.backgroundColor = "lightblue";
} else if(pattern[row][col] === 7) {
cell.style.backgroundColor = "pink";
}
}
}
}
</script>
</body>
</html>
Thank you!

I don't believe you would be able to use CSS transitions in this case. Transitions are typically applied to an entire HTML element, while you are attempting to selectively change certain colours of the ghost. I have created a solution to your problem in this fiddle. What this solution does is add another visual pattern representing the second frame of the ghost movement, as shown below:
var patterns = [
[
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 2, 2, 1, 1, 1, 1, 2, 2, 1, 1, 1, 0, 0],
[0, 0, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 1, 1, 0, 0],
[0, 0, 3, 3, 2, 2, 1, 1, 3, 3, 2, 2, 1, 1, 0, 0],
[0, 1, 3, 3, 2, 2, 1, 1, 3, 3, 2, 2, 1, 1, 1, 0],
[0, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
],
[
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 2, 2, 1, 1, 1, 1, 2, 2, 1, 1, 1, 0, 0],
[0, 0, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 1, 1, 0, 0],
[0, 0, 3, 3, 2, 2, 1, 1, 3, 3, 2, 2, 1, 1, 0, 0],
[0, 1, 3, 3, 2, 2, 1, 1, 3, 3, 2, 2, 1, 1, 1, 0],
[0, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]
];
The next important aspect for creating this animation is to create a render loop with the requestAnimationFrame function. This is simply used to run the render function as fast as possible,
var startTime = Date.now();
var SPEED = 5; // Runs 5 times per second
function render() {
requestAnimationFrame(render.bind(this));
var elapsed = (Date.now() - startTime) / 1000;
var index = Math.floor((elapsed * SPEED) % patterns.length);
colorizeDivs(patterns[index]);
}
render();
So what the render function first does is calculate how long the animation has run for in seconds, which is also known as the elapsed time. This value can then be used to retrieve the appropriate index from the patterns defined above. This calculation simply applies the floor and modulo operation so that the index is always from the bound 0 to patterns.length - 1. After the index is retrieved, the current pattern is passed into the colorizeDivs function so the cells can be updated.

Related

Adding images by combining cells with Javascript canvas

First of all, I have difficulty in explaining because my English is not very good. But I will try to explain as best I can.
I add random photos to the canvasta cells fields with Javascript.
Each plot is equivalent to 20pixels. What I want to do is:
if i and y in the map data are equal to 4;
I want to add the photo I want to a 4x4 area.
In other words, while adding a photo to 20 pixels;
I want to add a photo to a 320pixel area when it is 4x4.
As in the sample photo.
Check Photo
var map = [
[1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1],
[4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];
window.onload = function() {
const canvas = document.getElementById("main");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "transparent";
ctx.lineWidth = 0;
//draw grid
for (let i = 0; i <= 300; i++) {
const x = i*20;
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
const y = i*20;
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
}
//draw images
const p = ctx.lineWidth / 1; //padding
for (let xCell = 0; xCell < map.length; xCell++) {
for (let yCell = 0; yCell < map[xCell].length; yCell++) {
const x = xCell * 20;
const y = yCell * 20;
const img = new Image();
if (map[xCell][yCell] === 1) {
img.onload = function() {
ctx.drawImage(img, y+p, x+p, 20-p*2, 20-p*2);
};
//TODO: set img.src to your api url instead of the dummyimage url.
img.src = `https://picsum.photos/id/${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}/200/300`;
}else if(map[xCell][yCell] == 4){
img.onload = function() {
ctx.drawImage(img, y+p, x+p, 20-p*2, 20-p*2);
};
//TODO: set img.src to your api url instead of the dummyimage url.
img.src = `https://picsum.photos/id/${Math.floor(Math.random() * 12)}${Math.floor(Math.random() * 12)}/200/300`;
}
}
}
};
<canvas id="main" width="600" height="630"></canvas>
</canvas>
I solved the problem as below. There are positional errors but I will completely fix them.
Thanks to Lajos Arpad for trying to help.
var defaultMap = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1],
[0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
[1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
[1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
[1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
[1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1],
];
var images = [
{
name: "player 1",
position: [
{
x: [0,4],
y: [4,4]
}
]
},
{
name: "player 2",
position: [
{
x: [5,7],
y: [5,2]
}
]
}
];
window.onload = function() {
const canvas = document.getElementById("main");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "transparent";
ctx.lineWidth = 0;
//draw grid
for (let i = 0; i <= 300; i++) {
const x = i*40;
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
const y = i*40;
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
}
const p = ctx.lineWidth / 1;
for (let xCell = 0; xCell < defaultMap.length; xCell++) {
for (let yCell = 0; yCell < defaultMap[xCell].length; yCell++) {
const x = xCell * 20;
const y = yCell * 20;
const img = new Image();
if (defaultMap[xCell][yCell] === 1) {
img.onload = function() {
ctx.drawImage(img, y+p, x+p, 20-p*2, 20-p*2);
};
img.src = `https://besthqwallpapers.com/Uploads/5-6-2020/134999/thumb-black-ground-texture-macro-grunge-textures-black-backgrounds-ground-textures.jpg`;
}
}
}
for (let i = 0; i < images.length; i++) {
var width = 1, height = 1, x = images[i].position[0].x[0], y = images[i].position[0].y[0];
console.log(images[i].name + " x => " + images[i].position[0].x[0])
for(let w = images[i].position[0].x[0]; w < images[i].position[0].x[1]; w++){
width++
}
for(let h = 1; h < images[i].position[0].y[1]; h++){
height++
}
const img = new Image();
img.src = `https://picsum.photos/id/${Math.floor(Math.random() * 12)}${Math.floor(Math.random() * 12)}/200/300`;
img.onload = function() {
console.log(20*images[i].position[0].x[0]+p)
/* ctx.rect(20*i, 20*i, 20*width-p*2, 20*height-p*2)
ctx.fillStyle = "blue";
ctx.fill(); */
ctx.drawImage(img, 20*images[i].position[0].y[0]+p, 20*images[i].position[0].x[0]+p, 20*width-p*2, 20*height-p*2);
};
}
};
<canvas id="main" width="600" height="630"></canvas>
</canvas>
You can compute the value of a multiplier and use that to determine the picture size.
var map = [
[1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1],
[4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];
window.onload = function() {
const canvas = document.getElementById("main");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "transparent";
ctx.lineWidth = 0;
//draw grid
for (let i = 0; i <= 300; i++) {
const x = i*20;
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
const y = i*20;
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
}
//draw images
const p = ctx.lineWidth / 1; //padding
for (let xCell = 0; xCell < map.length; xCell++) {
for (let yCell = 0; yCell < map[xCell].length; yCell++) {
let multiplier = ((map[xCell][yCell] % 4) ? 1 : 4);
const x = xCell * 20;
const y = yCell * 20;
const img = new Image();
if (map[xCell][yCell] === 1) {
img.onload = function() {
ctx.drawImage(img, y+p, x+p, multiplier * 20-p*2, multiplier * 20-p*2);
};
//TODO: set img.src to your api url instead of the dummyimage url.
img.src = `https://picsum.photos/id/${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}/200/300`;
}else if(map[xCell][yCell] == 4){
img.onload = function() {
ctx.drawImage(img, y+p, x+p, multiplier * 20-p*2, multiplier * 20-p*2);
};
//TODO: set img.src to your api url instead of the dummyimage url.
img.src = `https://picsum.photos/id/${Math.floor(Math.random() * 12)}${Math.floor(Math.random() * 12)}/200/300`;
}
}
}
};
<canvas id="main" width="600" height="630"></canvas>
</canvas>

Im trying to build pacman with JS but im getting an error that says cannot read properties of undefined

I'm trying to build a simple pacman game before I start learning react but I keep getting three errors that says
if you can't see the image these are the errors:
cannot read properties of undefined (reading 'add' )
cannot read properties of undefined (reading 'classList' )
cannot read properties of undefined (reading 'remove' )
const grid = document.querySelector('.grid');
const width = 28;
let squares = [];
const layout = [
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
];
function createBoard() {
for (let i = 0; i < layout.length; i++) {
const square = document.createElement('div');
grid.appendChild(square);
squares.push(square);
if (layout[i] === 0) {
squares[i].classList.add('pac-dot');
} else if (layout[i] === 1) {
squares[i].classList.add('wall');
} else if (layout[i] === 2) {
squares[i].classList.add('ghost-lair');
} else if (layout[i] === 3) {
squares[i].classList.add('power-pallets');
}
}
}
createBoard();
class ghost {
constructor(name, startPosition, speed) {
this.name = name;
this.startPosition = startPosition;
this.position = startPosition;
this.speed = speed;
this.isScared = false;
}
}
const ghosts = [
new ghost('red', 348, 250),
new ghost('blue', 349, 250),
new ghost('pink', 350, 250),
new ghost('yellow', 351, 250)
]
ghosts.forEach((ghost) => {
squares[ghost.position].classList.add(ghost.name);
squares[ghost.position].classList.add('ghost');
})
function moveGhost(ghost) {
let random = Math.floor(Math.random() * 4) + 1;
const allDirections = [-1, +1, -width, +width];
let direction = allDirections[random];
//
setInterval(() => {
if (!squares[ghost.position + direction].classList.contains('wall')) {
//remove the ghost from the old position
squares[ghost.position].classList.remove(ghost.name)
squares[ghost.position].classList.remove('ghost')
//update the ghost position
squares[ghost.position] += direction;
//add the ghost to the grid
squares[ghost.position].classList.add(ghost.name);
squares[ghost.position].classList.add('ghost');
} else {
direction = allDirections[Math.floor(Math.random() * allDirections.length)]
}
}, 2500)
}
ghosts.forEach(ghost => moveGhost(ghost))
.grid {
width: 420px;
height: 420px;
border: 1px solid black;
display: flex;
flex-wrap: wrap;
}
.grid>* {
box-sizing: border-box;
width: 15px;
height: 15px;
border: 1px solid green;
/*delete or change color and opacity*/
}
.pac-dot {
border: 5px solid #fff;
background: greenyellow;
}
.wall {
background: blue;
}
.power-pallets {
background: green;
border-radius: 7.5px;
}
.ghost-lair {
background-color: #fff;
}
.ghost {
border-radius: 7.5px;
}
.red {
background: red;
}
.blue {
background-color: aqua;
}
.pink {
background-color: palevioletred;
}
.yellow {
background-color: yellow;
}
<div class="grid"></div>
There is one thing that i noticed here:
squares[ghost.position] += direction;
squares[ghost.position] will return HTML element and you want to sum an element and a number?
So after that value of squares[ghost.position] will be "[object HTMLDivElement]1"and thats a string. Thats why you got errors.
You have to change
squares[ghost.position] += direction
to
ghost.position += direction
Also the following random value
let random = Math.floor(Math.random() * 4) + 1
should instead be:
let random = Math.floor(Math.random() * 4)
so it does not occasionally result in an undefined direction value.

Displaying an 11x11 Matrix on a Canvas

I've been trying to create a canvas that displays an 11x11 matrix.
const canvas = document.getElementById('canvasGame');
const context = canvas.getContext('2d');
context.scale(10, 10);
context.fillstyle = '#000';
context.fillstyle(0,0, canvas.width, canvas.height);
const matrix = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
];
Depending on the number inside the matrix it will create a rectangle of a certain colour.
I've created a basic function that goes through every entry.
if = 0, white rectangle.
else, black rectangle.
function drawMatrix(matrix){
matrix.forEach((row, y) =>{
row.forEach((value, x) => {
if(value === 0) {
context.fillStyle = 'white';
context.fillRect(x, y, 1, 1);
}
else
{
context.fillStyle = 'black';
context.fillRect(x, y, 1, 1);
}
});
});
}
drawMatrix(matrix);
However when I load my html file with my .js file and my canvas set-up it doesnt load anything apart from the styling I've applied to my canvas.
Screenshot: What it loads.
My HTML, if that matters.
<html>
<head>
<title>Testing Grounds</title>
<style>
body {
background: #345;
color: #fff;
font-family: sans-serif;
font-size: 2em;
text-align: center;
}
canvas {
border: dashed .2em #fff;
height: 90vh;
}
</style>
</head>
<body>
<h1>Test Zone</h1>
<p>Using a canvas to display 11x11 matrix</p>
<canvas id="canvasGame" width="350" height="350"/>
<script src="app.js"></script>
</body>
</html>
Here is also another way...
const canvas1 = document.getElementById('canvas1');
const context1 = canvas1.getContext('2d');
const canvas2 = document.getElementById('canvas2');
const context2 = canvas2.getContext('2d');
//context.scale(canvas.height / 16, canvas.height / 16);
matrix = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
];
function drawMatrix(matrix) {
z = matrix.map((c) => c.map((c) => c == 0 ? [255, 255, 255, 255] : [0, 0, 0, 255]));
i = new ImageData(Uint8ClampedArray.from(z.flat(2)), 12)
context1.putImageData(i, 0, 0);
context2.scale(16, 16);
context2.webkitImageSmoothingEnabled = false;
context2.mozImageSmoothingEnabled = false;
context2.imageSmoothingEnabled = false;
context2.drawImage(canvas1, 0, 0);
}
drawMatrix(matrix);
<center><canvas hidden id="canvas1" width=12 height=12></canvas></center>
<center><canvas id="canvas2" width=192 height=192></canvas></center>
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
// every drawn pixel will be 16 times bigger
context.scale(canvas.height / 16, canvas.height / 16);
const matrix = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
];
function drawMatrix(matrix) {
// write all pixels cycling thru rows and columns
matrix.forEach((row, y) => {
row.forEach((value, x) => {
context.fillStyle = value && "black" || "white";
context.fillRect(x, y, 1, 1);
});
});
}
drawMatrix(matrix); // draw the matrix
<center><canvas id="canvas" width=192 height=192></canvas></center>
The rectangles you're creating are 1 by 1 pixel and always in the upper-left. You should calculate the width/height of the rectangle (width / 11, height / 11). Then translate the x and width using those values. Something like the following should work:
function drawMatrix(matrix){
var cellWidth = canvas.width / 11.0;
var cellHeight = vanvas.height / 11.0;
matrix.forEach((row, y) =>{
row.forEach((value, x) => {
context.fillStyle = cellColor(value);
context.fillRect(x * cellWidth, y * cellHeight, cellWidth, cellHeight);
});
});
}
function cellColor(val) {
if(value == 0)
{
return 'white';
}
return 'black';
}
drawMatrix(matrix);
This will calculate the width and height of the cell, loop through each element, and draw the rectangle with either white or black depending on the value.
You should also make sure that the drawMatrix function is called after the body is loaded.

Multidimensional array fill

I'm trying to fill an area in a multidimensional array and not sure on the approach.
For example I have the following array:
var map = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 2, 2, 2, 2, 2, 0, 0],
[0, 2, 0, 0, 0, 0, 2, 0, 0],
[0, 2, 0, 2, 0, 0, 2, 0, 0],
[0, 2, 0, 0, 2, 0, 2, 0, 0],
[0, 0, 2, 0, 0, 0, 2, 0, 0],
[0, 0, 0, 2, 2, 2, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
];
And then I am trying to get the number from X and Y position and fill all those numbers (which is 0) with a number given such as 1, which will result in the following array:
var map = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 2, 2, 2, 2, 2, 0, 0],
[0, 2, 1, 1, 1, 1, 2, 0, 0],
[0, 2, 1, 2, 1, 1, 2, 0, 0],
[0, 2, 1, 1, 2, 1, 2, 0, 0],
[0, 0, 2, 1, 1, 1, 2, 0, 0],
[0, 0, 0, 2, 2, 2, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
];
Basically just replacing all numbers next to each other (0) with (1) within that area.
What is the correct way to do this with JavaScript?
Assuming you're given a starting position and you want to then fill all neighboring values up/down, left/right that contain the same value, you can do something like this:
var map = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 2, 2, 2, 2, 2, 0, 0],
[0, 2, 0, 0, 0, 0, 2, 0, 0],
[0, 2, 0, 2, 0, 0, 2, 0, 0],
[0, 2, 0, 0, 2, 0, 2, 0, 0],
[0, 0, 2, 0, 0, 0, 2, 0, 0],
[0, 0, 0, 2, 2, 2, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
];
function fill(data, x, y, newValue) {
// get target value
var target = data[x][y];
function flow(x,y) {
// bounds check what we were passed
if (x >= 0 && x < data.length && y >= 0 && y < data[x].length) {
if (data[x][y] === target) {
data[x][y] = newValue;
flow(x-1, y); // check up
flow(x+1, y); // check down
flow(x, y-1); // check left
flow(x, y+1); // check right
}
}
}
flow(x,y);
}
fill(map, 2, 2, 1);
Working demo: http://jsfiddle.net/jfriend00/C83AT/
Here's a version that doesn't use recursion and appears to work with large data sets. Your large test data set wasn't a very interesting test pattern so I wouldn't say this is tested conclusively, but it seems to work on both the small and large data set:
Large data example: http://jsfiddle.net/jfriend00/8mrhN/
Small data example: http://jsfiddle.net/jfriend00/BFTub/ (easier to see the result)
function fill(data, x, y, newValue) {
// get target value
var target = data[x][y];
// maintain list of cells to process
// put the starting cell in the queue
var queue = [{x:x, y:y}], item;
while (queue.length) {
item = queue.shift();
x = item.x;
y = item.y;
if (data[x][y] === target) {
data[x][y] = newValue;
// up
if (x > 0) {
queue.push({x:x-1, y:y})
}
// down
if (x + 1 < data.length) {
queue.push({x:x+1, y:y})
}
// left
if (y > 0) {
queue.push({x:x, y:y-1});
}
// right
if (y + 1 < data[x].length) {
queue.push({x:x, y:y+1});
}
}
}
}
This could be optimized further for performance by testing the value before putting it in the queue and by following a given direction until you find a non-matching value, if required.
This is an alternative implementation (queue-based) roughly translated, no optimisations performed. There are also others.
Javascript
var map = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 2, 2, 2, 2, 2, 0, 0],
[0, 2, 0, 0, 0, 0, 2, 0, 0],
[0, 2, 0, 2, 0, 0, 2, 0, 0],
[0, 2, 0, 0, 2, 0, 2, 0, 0],
[0, 0, 2, 0, 0, 0, 2, 0, 0],
[0, 0, 0, 2, 2, 2, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
];
/*
1. Set Q to the empty queue.
2. If the color of node is not equal to target-color, return.
3. Add node to Q.
4. For each element N of Q:
5. If the color of N is equal to target-color:
6. Set w and e equal to N.
7. Move w to the west until the color of the node to the west of w no longer matches target-color.
8. Move e to the east until the color of the node to the east of e no longer matches target-color.
9. For each node n between w and e:
10. Set the color of n to replacement-color.
11. If the color of the node to the north of n is target-color, add that node to Q.
12. If the color of the node to the south of n is target-color, add that node to Q.
13. Continue looping until Q is exhausted.
14. Return.
*/
function floodFill(data, node, targetValue, replacementValue) {
var Q;
if (data[node[0]][node[1]] === targetValue) {
Q = [node];
while (Q.length) {
var N = Q.shift(),
value,
index,
n,
e,
s,
w;
if (data.hasOwnProperty([N[0]]) && data[N[0]][N[1]] === targetValue) {
w = e = N[0];
do {
w -= 1;
} while (data.hasOwnProperty(w) && data[w][N[1]] === targetValue);
do {
e += 1;
} while (data.hasOwnProperty(e) && data[e][N[1]] === targetValue);
n = N[1] - 1;
s = N[1] + 1;
for (index = w + 1; index < e; index += 1) {
data[index][N[1]] = replacementValue;
if (data[index].hasOwnProperty(n) && data[index][n] === targetValue) {
Q.push([index, n]);
}
if (data[index].hasOwnProperty(s) && data[index][s] === targetValue) {
Q.push([index, s]);
}
}
}
}
}
}
floodFill(map, [2, 2], 0, 1);
map.forEach(function (m) {
console.log(JSON.stringify(m));
});
Output
[0,0,0,0,0,0,0,0,0]
[0,2,2,2,2,2,2,0,0]
[0,2,1,1,1,1,2,0,0]
[0,2,1,2,1,1,2,0,0]
[0,2,1,1,2,1,2,0,0]
[0,0,2,1,1,1,2,0,0]
[0,0,0,2,2,2,2,0,0]
[0,0,0,0,0,0,0,0,0]
On jsFiddle

Javascript - Loading XML into Multidimensional array

I have been creating a game in HTML5 and javascript and have came across a problem.
The game uses a tile system to load the map. Currently my map is saved within a multidimensional array and looks like this:
var map = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 3, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
I would like to add move levels by using a XML file to update the array.
My XML file currently looks like this:
<TileMaps>
<Level level="1">
<map>[ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 3, 0, 0, 0, 0, 2, 4, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
</map>
</Level>
<Level level="2">
<map>[ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 3, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
</map>
</Level>
</TileMaps>
If anyone could help me load level="1" into my map variable that would be great.
Thanks
Don't use xml, use json. Here's a link to what its about, http://www.json.org/.
While not entirely precise, its pretty safe to think of json as a subset of javascript.
For example:
{
"levels":[
[
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 3, 0, 0, 0, 0, 2, 4, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
],
[
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 3, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 2, 0, 4, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
]
}
Use http://jsonlint.org to validate json.
For anyone who wanted to know i fixed this by using the following code:
req=new XMLHttpRequest();
req.open("GET","my.xml",false);
req.send();
xmlDoc = req.responseXML;
map = JSON.parse(xmlDoc.getElementsByTagName('map')[0].firstChild.nodeValue);

Categories

Resources