JavaScript and a Matrix
Screenshot of the code a 10 by 10 matrix
Update 5/11/2021
Creating a Matrix flex grid:
I was tasked in a mock interview to create the game minesweeper. In an hour I had barely touched the logic of the problem. While making supper that same day, I remembered doing a Python problem that involved rotating a matrix and realized that I could use a matrix for my MineSweeper map.
My current minesweeper does not dynamically add the elements or cells. They are coded into the HTML. When I decided to write up the code and this post, I wanted to make the code reusable and functional for other projects, or perhaps one of my readers can have fun with it and make something new.
Think of the coordinates inside the matrix just like the coordinates on a page. The top left box is (0, 0). The x, y of the bottom right cell is going to be (HEIGHT, WIDTH).
I find it easier to learn code by playing with it, so feel free to scroll down to “Gimme the code!”.
As with my other experiments, you can copy and paste each of the pieces of code onto a file,
The names of the files I used are in the HTML, so if you change the javascript or stylesheet names, remember to change them in the HTML. Once all three of these files are in a folder together, you can double click on the HTML file and your browser will open it up and run it for you.
HTML/CSS
A few notes on this setup. I created the styles I wanted for the cells in the stylesheet, and then on the creation of the cell element in the Javascript, I am adding the class to its classList.
This can be created hardcoded also but is a timely task to write out the HTML for 100 cells. And yes you can copy-paste, but in order to access the data in the matrix, I use the id of the cell to get the location. The cells id “3:7” for example. I can split that string on the colon, and the results will be [‘3’, ‘7’]. Now to get my data, I can use 3 as my x coordinate, and 7 as my y coordinate in the matrix list. So doing MATRIX[x][y][0] will give me the item in the x-th row, y-th column and in that list, the [0] is the first item.
JAVASCRIPT
*populate():
This function is going to use the global ROWS and COLUMNS to fill our MATRIX = [] with what are going to be the lists/arrays holding the cell data. To get an item in the matrix, we can use MATRIX[x] to get the row in which the item is in. We add [y] to this to dig a little deeper, MATRIX[x][y] to get the item in x row, and the y-th item in that row (this could be seen as the column also). Now to access what's in the [y], I am only pushing one piece of data into these cells, so it should always be the first item. Or [0].
Populate uses a for loop to create the row, an empty array, and then a nested for loop will fill that row with a set number of empty arrays, or columns, that are going to be the cells holding our data.
*createHTMLmatrix():
This function is going to loop in the same way our populate() did. This time, we are creating the row element, then we are creating the cell element, and attaching the cell_id to it on creation. I also add an event listener to each cell in the loop to listen for our “reveal()”. Later I can use the id of the cell to get the data from our matrix. Since the for loops i and j are also the locations within the matrix, I can stick some data into the cells by pushing it into the array that is the i-th row, j-th column’s array. *reminder the grid layout of this is accomplished through the CSS, flexbox class attributes.*
The last few functions, reveal(), window.onload, and setDOM() tie it all together once the page is loaded.
As always with the code here, feel free to copy/paste. Experiment, use it, toss it, improve it, burn it in the pits, and have fun.
GIMME THE CODE
-- HTML ---
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head> <meta charset="utf-8"></meta> <meta content="width=device-width, minimum-scale=1.0, maximum-scale=5.0, user-scalable=yes" name="viewport"></meta> <meta content="Nellie Tobey" name="author"></meta> <meta content="Creating a Matrix" name="description"></meta> <script src="matrix.js" type="text/javascript"></script> <link href="demo_matrix.css" rel="stylesheet"></link> <title>Matrix</title></head><body> <header>Matrix</header> <main> <h2>Click on any cell to reveal it's data.</h2>
<div class="field" id="field"> </div>
</main></body></html>
--CSS--
body
{
padding: 10px;
margin: 0;
}
.main {
background: black;
display: flex;
align-items: center;
justify-content: center;
}
.field {
display: flex;
align-content: center;
justify-content: center;
text-align: center;
background-color: darkolivegreen;
}
.cell {
color: white;
background: black;
height: 50px;
width: 70px;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
border: 1px solid green;
}
-- JAVASCRIPT --
// JavaScript source code
let FIELD
let MATRIX = []
let ROWS = 10
let COLUMNS = 10
/* visual of a 10 by 10 matrix
* [
[[], [], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], [], []],
]
*/
function setDOM() {
//This will help us access the field throughout our code
FIELD = document.querySelector('#field')
populate()
createHTMLmatrix();
}
function populate(rows = ROWS, columns = COLUMNS) {
for (i = 0; i < rows; i++) {
let row = []
for (j = 0; j < columns; j++) {
column = []
row.push(column)
}
MATRIX.push(row)
}
}
function createHTMLmatrix(rows = ROWS, columns = COLUMNS) {
for (i = 0; i < rows; i++) {
let row = document.createElement('div')
row.classList.add('row')
for (j = 0; j < columns; j++) {
let cell = document.createElement('div')
cell.classList.add('cell')
// this id will help us locate the cell or data in the matrix
let cell_id = i + ":" + j
cell.id = cell_id
row.appendChild(cell)
cell.addEventListener('click', reveal)
let data = "Data(" + i + "," + j + ")"
let container = MATRIX[i][j]
container.push(data)
}
FIELD.appendChild(row)
}
}
function reveal(event) {
let location = event.target.id
let xy = location.split(':')
let x = xy[0]
let y = xy[1]
let data = MATRIX[x][y][0]
event.target.innerHTML = data
}
function test() {
createHTMLmatrix();
}
window.onload = (function () {
setDOM()
//test()
})
Comments
Post a Comment