Grid game board - javascript

I would like to quad my board game, I must create coordinates, but i don't know how to do. I need your help !! Thanks
var mapArray = [
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 1, 0]
];
function drawMap() {
var col = [];
var table = document.createElement("table");
for (var i = 0; i < mapArray.length; i++) {
for (var j = 0; j < mapArray[i].length; j++) {
if (parseInt(mapArray[i][j]) == 0) {
$('#canvas').append('<div class="grass"></div>');
}
if (parseInt(mapArray[i][j]) == 1) {
$('#canvas').append('<div class="wall"></div>');
}}}}
$('document').ready(function() {
drawMap();
});

It sounds like you need to read up on some canvas manipulation using JavaScript. Example on how to draw lines and what not. But here you go.
I have the below function which draws the grid
function drawGrid(w, h, canvas, ctx, spacing) {
canvas.width = w;
canvas.height = h;
ctx.beginPath();
ctx.strokeStyle = 'rgb(0, 0, 0, 0.35)';
ctx.lineWidth = 1;
for (var x=0; x<=w; x+=spacing) {
ctx.moveTo(x, 0);
ctx.lineTo(x, h);
}
for (var y=0;y<=h;y+=spacing) {
ctx.moveTo(0, y);
ctx.lineTo(w, y);
}
ctx.stroke();
};
Now to explain the above: I pass the width of the canvas, the height of the canvas, the canvas element, the context of the canvas and then the spacing of the grid (example: 16px) I then do a for loop to create the lines and the. I draw them.
The next part of your question is returning the cell the mouse is in. It can be done by the following code - which is two functions for simplicity
function getMousePos(canvas, evt){
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function getGridLocation(posX, posY, gridsize)
{
var cellRow = Math.floor(posY / gridsize);
var cellColumn = Math.floor(posX / gridsize);
return {
row: cellRow,
column: cellColumn
};
}
So above is first to get the mouse co-ordinates and then I use the second function which gets passed the mouse coordinates and then divides them by each cell of the grid and floors the number.
Below is how to get mouse position per cell.
gridCanvas.addEventListener('click', function(evt) {
var mousePos = getMousePos(gridCanvas, evt);
var gridLocation = getGridLocation(mousePos.x, mousePos.y, 64);
//alert("Row: " + gridLocation.row + " Column: " + gridLocation.column);
}, false);

You can do something like this:
const board = [
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
];
const markup = board.map(row => row.map(col => `<span class="field ${col === 0 ? "grass" : "wall"}"></span>` ).join("")).join("<span class='clear'></span>");
document.getElementById("container").innerHTML = markup;
.field {
float: left;
height: 20px;
width: 20px;
border: 1px solid #000;
}
.clear {
clear: both;
float: left;
}
.grass {
background: green;
}
.wall {
background: black;
}
<div id="container">

Related

Inserting value in array table js

I have the following array table:
var ticket1 = [
[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]
];
I want to insert values in the above array. How do I do that?
I have tried this:
ticket1[0, 0] = 20;
ticket[1, 0] = 30;
ticket[2, 0] = 40;
Expected result:
[20, 0, 0, 0, 0, 0, 0, 0, 0],
[30, 0, 0, 0, 0, 0, 0, 0, 0],
[40, 0, 0, 0, 0, 0, 0, 0, 0]
Actual result:
[20, 30, 40, 0, 0, 0, 0, 0, 0]
Consider the following example.
$(function() {
var ticket1 = [
[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]
];
ticket1[0][0] = 20;
ticket1[1][0] = 30;
ticket1[2][0] = 40;
$.each(ticket1, function(k, v) {
$("<p>").html(v.join(", ")).appendTo("div");
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
Reference: https://www.w3schools.com/js/js_arrays.asp
When using a Matrix, or an Array of Arrays, you still access each Array Index. So ticket1[0] will access the first element, which is an Array of Integers, so ticket1[0][0] accesses the first index of the first array.
You can make a more complex function to update / change elements in the Matrix.
Array.prototype.mPush = function(x, y, e) {
this[x][y] = e;
return this;
}
$(function() {
var ticket1 = [
[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]
];
ticket1.mPush(0, 0, 20);
ticket1.mPush(1, 0, 30);
ticket1[2][0] = 40;
$.each(ticket1, function(k, v) {
$("<p>").html(v.join(", ")).appendTo("div");
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
function add(var){
ticket.push(var)
}
Eg:
ticket.push(2)
ticket1[0][0] = 20;
posted by ozer and twisty

Why is my drawChar function's drawImage not showing?

First things first, I am trying my hand at a very simple tile map engine for 2d games using HTML5 canvas and Javascript and everything seems to be working okay except that my second drawChar function's drawImage() isn't showing on the canvas. I know the urls are good and I have checked for missing chars, etc. but cant figure it out. Code is below. Any help is appreciated.
P.S. I know that much of this code is not "modern" or "best practice", I am still learning and am just trying learn why this error is occurring. Thanks.
<canvas id="canvas" width="1000" height="500" style="border: 2px solid black; margin: 10px auto;"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var draw=canvas.getContext('2d');
var tileSize=canvas.height/10;
var mapLength=canvas.width/tileSize;
var tilex=0;
var tiley=0;
var tile1= new Image();
var tile2= new Image();
var charImg= new Image();
tile1.src='https://raw.githubusercontent.com/daveboy87/Jscript-TileEngine/master/tile_sky.jpg';
tile2.src='https://raw.githubusercontent.com/daveboy87/Jscript-TileEngine/master/tile_ground.jpg';
charImg.src='https://raw.githubusercontent.com/daveboy87/Jscript-TileEngine/master/player.jpeg';
var mapArray = [
[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, 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, 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, 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, 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, 0, 0, 1, 1, 1, 1, 0, 1, 1]
];
function drawMap() {
for (var y=0; y<mapLength; y++){
for (var x=0; x<tileSize; x++){
tilex=x*tileSize;
tiley=y*tileSize;
if (parseInt(mapArray[y][x]) == 0) {
draw.drawImage(tile1, tilex, tiley, tileSize, tileSize); }
if (parseInt(mapArray[y][x]) == 1) {
draw.drawImage(tile2, tilex, tiley, tileSize, tileSize); }
}
}
}
function drawChar(){
draw.drawImage(charImg, 300, 200, tileSize, tileSize); }
function nextFrame(){
draw.clearRect(0, 0, canvas.width, canvas.height);
drawMap();
drawChar();
}
setInterval(nextFrame, 1000);
You're checking mapArray[y][x] - but y and x aren't related with the size of mapArray, so you're checking for an element that doesn't exist, and getting a Javascript error, which blocks the program execution.
You should keep the Chrome developer tools open so you can see Javascript errors, which will show you the problem here.

How to display arrays as visuals in Javascript (e.g. for a maze)

So, I am making a maze, in javascript. I do not know how to display an array (such as 1's and 0's) graphically. The best way is to show you the code:
var maze= [
[0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,0],
[0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,1,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,0,1,1,0,1,0,0,0,1,1,1,0,0,1,0,0,0],
[0,0,1,1,0,1,1,0,0,0,0,0,0,1,0,0,1,1,1,1],
[0,0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,0,1],
[0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,1],
];
With the 0's representing walls, and the 1's representing empty space, and 2 meaning the end of the maze, how can I display this as a maze using only javascript? Shall I make each 0 an individual rectangle? How can I do this?
Please do not make fun as I am just starting out.
Here is the code for reference (this is on "coding with chrome", as it was the easiest to use, as I did not have to import anything).
//PART 1 : THE CHARACTER
//Where is the character???
charX=10;
charY=10;
//Draw char
function drawChar(){
draw.circle(charX, charY, 5, "black");
}
//Loop happens at 40 milliseconds
setInterval (loop, 40);
//loop that clears screen
function loop(){
draw.rectangle(0,0, window.innerWidth, window.innerHeight,"white");
drawChar();
}
//Move Character
document.addEventListener("keydown", moveChar);
function moveChar (e) {
if(e.keyCode ==37){
//Left arrow
charX=charX-50;
}
if(e.keyCode== 38){
//Up arrow
charY=charY-50;
}
if(e.keyCode == 39){
//right arrow
charX=charX+50;
}
if(e.keyCode == 40){
//down arrow
charY=charY +50;
}
//PART 1 DONE :-)
//PART 2: Walls
//map of maze
var maze= [
[0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,0],
[0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,1,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,0,1,1,0,1,0,0,0,1,1,1,0,0,1,0,0,0],
[0,0,1,1,0,1,1,0,0,0,0,0,0,1,0,0,1,1,1,1],
[0,0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,0,1],
[0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,1],
];
//How can we display this graphically, with the 0 being a wall, and 1 being an empty space?
span {
white-space: pre;
display: inline-block;
width: 24px;
}
<script>
var maze = [
[0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1],
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1],
[0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1],
[0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1],
];
maze.forEach(function(arr, index) {
arr.forEach(function(path, i) {
var span = document.createElement("span");
if (path === 0) {
span.textContent = " ";
span.style.backgroundColor = "#000";
}
if (path === 1) {
span.textContent = " ";
span.style.backgroundColor = "yellow";
}
if (path === 2) {
span.textContent = "end";
span.style.backgroundColor = "green";
span.style.color = "gold";
}
document.body.appendChild(span)
});
document.body.appendChild(document.createElement("br"))
})
</script>

HTML5 Canvas - Block side collisions on dynamic map

I'm making a platformer game in HTML5 Canvas and I have run into some collision problems. I've been experimenting with numerous collision algorithms but I can't seem to get any to work.
My question:
How can I get the blocks/darker grey squares to stop my ball from passing through it?
Some info about my code:
The map is dynamically generated
I have tried collision algorithms many times
Collision handling is done in the canMoveHere function and returns true or false to the moveAll function, where it is determined if the ball can move to the next square
My code on jsfiddle.net
My code download from Google Drive
My full code:
<html>
<head>
<canvas id ="gameCanvas" width = "500" height = "500" style = "border:1px solid black;"></canvas>
<script>
var canvas, canvasContext;
var framesPerSecond = 30;
var gravity = .2;
var leftKey = false;
var rightKey = false;
const TILE_H = 25;
const TILE_W = 25;
var map = [
[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, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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250`,
`radius:10`,
color:"#ff9966",
`velocityX:5`,
`velocityY:1`,
`terminalVel:8`,
draw:function()
{
canvasContext.beginPath();
canvasContext.fillStyle = this.color;
canvasContext.arc(this.x, `this.y`, this.radius, 0, Math.PI * 2, false);
canvasContext.fill();
canvasContext.closePath();
}
};
document.addEventListener("keydown", function(evt)
{
if(evt.keyCode == 37)
{
leftKey = true;
}
if(evt.keyCode == 39)
{
rightKey = true;
}
});
document.addEventListener("keyup", function(evt)
{
if(evt.keyCode == 37)
{
leftKey = false;
}
if(evt.keyCode == 39)
{
rightKey = false;
}
});
window.onload = function()
{
canvas = document.getElementById("gameCanvas");
canvasContext = canvas.getContext("2d");
setInterval(function()
{
drawAll();
moveAll();
}, 1000/framesPerSecond);
}
var renderMap = function()
{
for(var eachRow=0; eachRow<20; eachRow++)
{
for(var eachCol=0; eachCol<20; eachCol++)
{
if(map[eachRow][eachCol] == 0)
{
canvasContext.fillStyle = "#a6a6a6";
canvasContext.fillRect(TILE_W*eachCol, TILE_H*eachRow, TILE_W, TILE_H);
}
if(map[eachRow][eachCol] == 1)
{
canvasContext.fillStyle = "#666666";
canvasContext.fillRect(TILE_W*eachCol, TILE_H*eachRow, TILE_W, TILE_H);
}
}
}
}
var drawAll = function()
{
canvasContext.clearRect(0, 0, canvas.width, canvas.height);
renderMap();
ball.draw();
}
var canMoveHere = function(col, row)
{
if(map[row][col] == 1)
{
return false;
}
else
{
return true;
}
}
var moveAll = function()
{
nextBallX = `ball.x` + ball.velocityX;
nextBallY = `ball.y` + ball.velocityY;
nextBallCol = Math.floor(nextBallX / TILE_W);
nextBallRow = Math.floor(nextBallY / TILE_H);
var canMove = canMoveHere(nextBallCol, nextBallRow);
ball.velocityY += gravity;
`ball.y` += ball.velocityY;
if(ball.velocityY >= ball.terminalVel)
{
ball.velocityY = ball.terminalVel;
}
if(canMove === false)
{
ball.velocityY *= -1;
}
if(leftKey)
{
`ball.x` -= ball.velocityX;
}
if(rightKey)
{
`ball.x` += ball.velocityX;
}
}
</script>
</head>
<body>
</body>
</html>
You can't just say "if the ball can or cannot move over certain tile", you have to tell the game how to respond when an obstacle is hit and that depends on two factors: current ball direction and shape of the obstacle.
I modified your canMoveHere function to evaluate that:
var directionChange = function(nextCol, nextRow)
{
var currentRow = Math.floor(ball.y / TILE_H);
var currentCol = Math.floor(ball.x / TILE_W);
var resultDirection = { x: 1, y: 1 };
if (map[nextRow][nextCol] == 1) {
if (map[nextRow][currentCol] == 1 &&
map[currentRow][nextCol] == 0) {
// horizontal obstacle
resultDirection.x = 1;
resultDirection.y = -1;
} else if (map[nextRow][currentCol] == 0 &&
map[currentRow][nextCol] == 1) {
// vertical obstacle
resultDirection.x = -1;
resultDirection.y = 1;
} else {
// corner obstacle
resultDirection.x = -1;
resultDirection.y = -1;
}
}
return resultDirection;
}
at this point we also modify the moveAll function accordingly
var moveAll = function()
{
nextBallX = ball.x + ball.velocityX;
nextBallY = ball.y + ball.velocityY;
nextBallCol = Math.floor(nextBallX / TILE_W);
nextBallRow = Math.floor(nextBallY / TILE_H);
let dir = directionChange(nextBallCol, nextBallRow);
ball.velocityY *= dir.y;
ball.velocityX *= dir.x;
ball.velocityY += gravity;
if(ball.velocityY >= ball.terminalVel)
{
ball.velocityY = ball.terminalVel;
}
ball.y += ball.velocityY;
if(leftKey) {
ball.x -= ball.velocityX;
}
if(rightKey) {
ball.x += ball.velocityX;
}
}
Now you just have to find a way to let the keys drive the ball smoothly, because changing the velocity using positive/negative values has an effect to the actual direction of the ball, because it will go to the opposite direction of the pressed key when values are negatives;
I tried using absolute values
if(leftKey) {
ball.x -= Math.abs(ball.velocityX);
}
if(rightKey) {
ball.x += Math.abs(ball.velocityX);
}
but as soon as the ball hits an obstacle, the pressed key will keep pushing the ball against the obstacle changing again the velocity and - for how it is built now - the ball will go through the walls.
Even though this isn't a bug-free solution, I hope this can help you on solving the main problem.

Javascript Conway's Game of Life Issues

I'm trying to make Conway's Game of Life in javascript. I made a function to count neighbors, and a function that produces the next generation of cells. However, I tried a test input, and the result isn't coming out right, and I can't find where the error is. Please help.
Here's the code:
(code attached)
/* Draws grid */
for (var i = 0; i < 15; i++) {
for (var j = 0; j < 15; j++) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FFFFFF";
ctx.strokeStyle = "grey";
ctx.strokeRect(10 * j, 10 * i, 10, 10);
}
}
/* draws live cells */
function drawSquares(a) {
for (var i = 0; i < 15; i++) {
for (var j = 0; j < 15; j++) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#000000";
if (a[i][j] === 1) {
ctx.fillRect(10 * j, 10 * i, 10, 10);
}
}
}
}/* Counts neighbors */
function neighborCount(a, i, j, height, width){
var lifes = 0;
var neighbors = [
[-1, 1],
[0, 1],
[1, 1],
[-1, 0],
[1, 0],
[-1, -1],
[0, -1],
[1, -1]
];
/* loops through a cell's neighbors */
for (var z = 0; z < 8; z++){
/*checks if the neighbor isn't off the grid*/
if ((i + neighbors[z][0]) >=0 && (i + neighbors[z][0]) < height && (j + neighbors[z][1]) >=0 && (j + neighbors[z][1]) < width){
/*checks if it's alive*/
if (a[i + neighbors[z][0]][j + neighbors[z][1]] === 1){
lifes++;
}
}
}
return lifes;
}
/* game of life */
function life(a) {
var n = a; /*new generation of life */
var lifes = 0; /*neighbor counter*/
var height = a.length;
var width = a[0].length;
/*loops through all cells*/
for (var i = 0; i < height; i++){
for (var j = 0; j < width; j++){
lifes = neighborCount(a, i, j, height, width);
/* kills alive cells */
if(a[i][j] === 1 && (lifes < 2 || lifes > 3)){
n[i][j] = 0;
}
/* brings dead cells to life */
else if (a[i][j] === 0 && lifes ===3){
n[i][j] = 1;
}
}
}
drawSquares(n);
return(n);
}
/* test input */
var a = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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