array.every() isn't affecting any of the array's elements? - javascript

So I'm making a Tetris game and right now I'm trying to clear a row when each square is filled by a tetromino piece. So far I am able to determine if that row is filled up using the every() method on the row. It looks like this
function checkForPoints() {
for(let r = 0; r < row; r++) {
if(board[r].every(squareCheck)) {
alert('yo');
board[r].every(clearSquare);
}
}
function squareCheck(sq) {
if(sq !== vacant) return true;
else return false;
}
function clearSquare(sq) {
sq = vacant;
}
}
If every square in the row is filled up then the condition is true and it should proceed to make all squares black or vacant in this case. However this doesn't happen. I have no clue why? My every() method works in determining if every square is not vacant, but that same method won't work in changing that array's elements to equal "black" or vacant?
// //create your globals
// const canvas = document.querySelector('#canvas');
// const ctx = canvas.getContext('2d');
// const row = 20;
// const col = 10;
// const sq = 40;
// const vacant = 'black';
// //-----------------------Why can't I initialize the tetrominos??
// //create and draw board
// let board = [];
// for(let r = 0; r < row; r++) {
// board[r] = [];
// for(let c = 0; c < col; c++) {
// board[r][c] = vacant;
// draw(c, r, board[r][c]);
// }
// }
// //define a function to draw to the canvas
// function draw(x, y, color) {
// ctx.fillStyle = color;
// ctx.fillRect(x * sq, y * sq, sq, sq);
// ctx.strokeStyle = 'white';
// ctx.strokeRect(x * sq, y * sq, sq, sq);
// }
// //create an object for the tetrominos
// function Tetromino(tetromino, color) {
// this.tetromino = tetromino;
// this.color = color;
// this.tetrominoN = 0;
// this.activeTetromino = this.tetromino[this.tetrominoN];
// this.x = 0;
// this.y = 0;
// }
// //create an array for the pieces
// const pieces = [
// [Z, 'red'],
// [S, 'limegreen'],
// [T, 'yellow'],
// [O, 'blue'],
// [L, '#b938ff'],
// [I, 'cyan'],
// [J, 'orange']
// ]
// //create a new instance of Tetromino
// function randomPiece() {
// let r = Math.floor(Math.random() * pieces.length);
// return new Tetromino(pieces[r][0], pieces[r][1]);
// }
// let p = randomPiece();
// //draw the piece
// function drawPiece(piece) {
// //loop through the tetromino
// for(let r = 0; r < piece.length; r++) {
// for(let c = 0; c < piece.length; c++) {
// //if the tetromino index is zero skip it
// if(!piece[r][c]) continue;
// //else draw it
// else draw(p.x + c, p.y + r, p.color);
// }
// }
// }
// //undrawdraw the piece
// function undrawPiece(piece) {
// //loop through the tetromino
// for(let r = 0; r < piece.length; r++) {
// for(let c = 0; c < piece.length; c++) {
// //if the tetromino index is zero skip it
// if(!piece[r][c]) continue;
// //else draw it
// else draw(p.x + c, p.y + r, vacant);
// }
// }
// }
// drawPiece(p.activeTetromino);
// //control the piece
// document.addEventListener('keydown', (event) => {
// if(event.keyCode === 37) p.moveLeft();
// else if (event.keyCode === 38) p.rotate();
// else if (event.keyCode === 39) p.moveRight();
// else if (event.keyCode === 40) p.moveDown();
// });
// Tetromino.prototype.moveDown = function() {
// if(!this.collision(0, 1, this.activeTetromino)) {
// undrawPiece(this.activeTetromino);
// this.y++;
// drawPiece(this.activeTetromino);
// } else {
// //lock piece and generate a new one
// this.lock();
// p = randomPiece();
// }
// }
// Tetromino.prototype.moveLeft = function() {
// if(!this.collision(-1, 0, this.activeTetromino)) {
// undrawPiece(this.activeTetromino);
// this.x--;
// drawPiece(this.activeTetromino);
// }
// }
// Tetromino.prototype.moveRight = function() {
// if(!this.collision(1, 0, this.activeTetromino)) {
// undrawPiece(this.activeTetromino);
// this.x++;
// drawPiece(this.activeTetromino);
// }
// }
// Tetromino.prototype.rotate = function() {
// let nextPattern = this.tetromino[(this.tetrominoN + 1) % 4];
// if(!this.collision(0, 0, nextPattern)) {
// if(this.tetromino.length > 1) {
// undrawPiece(this.activeTetromino);
// this.tetrominoN = (this.tetrominoN + 1) % 4; // take paranthesis off
// this.activeTetromino = this.tetromino[this.tetrominoN];
// drawPiece(this.activeTetromino);
// }
// }
// }
// //create a function to check for collisions
// Tetromino.prototype.collision = function(x, y, piece) {
// for(let r = 0; r < piece.length; r++) {
// for(let c = 0; c < piece.length; c++) {
// //skip index if it is 0
// if(!piece[r][c]) continue;
// //create vars for the future piece position
// let newX = this.x + c + x;
// let newY = this.y + r + y;
// //see if new position collides with border
// if(newX < 0 || newX >= col || newY >= row) return true;
// //see if there's a locked piece on the board
// if(board[newY][newX] !== vacant) return true;
// }
// }
// return false;
// }
// Tetromino.prototype.lock = function() {
// for(let r = 0; r < this.activeTetromino.length; r++) {
// for(let c = 0; c < this.activeTetromino.length; c++) {
// if(!this.activeTetromino[r][c]) continue;
// //if piece reaches the top its gameover
// if(this.y + r < 0) {
// gameover = true;
// alert('Game Over!');
// }
// //lock the piece by updating the board
// board[this.y + r][this.x + c] = this.color;
// }
// }
// }
// let dropStart = Date.now();
// //drop the piece every 1s
// function drop() {
// let now = Date.now();
// let delta = now - dropStart;
// //if delta is greater than 1s drop the piece
// if(delta > 800) {
// p.moveDown();
// dropStart = Date.now();
// }
// requestAnimationFrame(drop);
// }
// drop();
//declare globals
const col = 10;
const row = 20;
const sq = 40;
const vacant = 'black';
const cvs = document.querySelector('#canvas');
const ctx = cvs.getContext('2d');
let gameOver = false;
//create and draw the board
let board = [];
for(let r = 0; r < row; r++) {
board[r] = [];
for(let c = 0; c < col; c++) {
board[r][c] = vacant;
draw(c, r, board[r][c]);
}
}
//create a blueprint function to draw to the board
function draw(x, y, color) {
//set the drawing specifications
ctx.fillStyle = color;
ctx.fillRect(x * sq, y * sq, sq, sq);
ctx.strokeStyle = 'white';
ctx.strokeRect(x * sq, y * sq, sq, sq);
}
//create a blueprint object for the tetrominos
function Piece(tetromino, color) {
//create the properties
this.tetromino = tetromino;
this.color = color;
this.tetrominoN = 0;
this.activeTetromino = this.tetromino[this.tetrominoN];
this.x = 0;
this.y = -1;
if (this.tetromino === pieces[5][0]) this.y = -2;
}
//create an array to hold all of the tetrominos
const pieces = [
[Z, 'red'],
[S, 'limegreen'],
[T, 'yellow'],
[O, 'blue'],
[L, '#b938ff'],
[I, 'cyan'],
[J, 'orange']
]
function randomPiece() {
let r = Math.floor(Math.random()*pieces.length);
return new Piece(pieces[r][0], pieces[r][1]);
}
//grab a piece
let p = randomPiece();
//draw a piece to the board
// drawPiece(p.activeTetromino, p.color);
//create a blueprint function to draw tetrominos to the board
function drawPiece(piece, color) {
for(let r = 0; r < piece.length; r++) {
for(let c = 0; c < piece.length; c++) {
if (!piece[r][c]) continue;
draw(c + p.x, r + p.y, color);
}
}
}
//control the piece
document.addEventListener('keydown', (e) => {
//check user's input
if(e.keyCode === 37) p.moveLeft();
else if(e.keyCode === 38) p.rotate();
else if(e.keyCode === 39) p.moveRight();
else if (e.keyCode === 40) p.moveDown();
});
Piece.prototype.moveDown = function() {
if(!this.collision(0, 1, this.activeTetromino)) {
drawPiece(this.activeTetromino, vacant);
this.y++;
drawPiece(this.activeTetromino, this.color);
} else {
this.lockPiece(this.activeTetromino);
checkForPoints();
p = randomPiece();
}
}
Piece.prototype.moveLeft = function() {
if(!this.collision(-1, 0, this.activeTetromino)) {
drawPiece(this.activeTetromino, vacant);
this.x--;
drawPiece(this.activeTetromino, this.color);
}
}
Piece.prototype.moveRight = function() {
if(!this.collision(1, 0, this.activeTetromino)) {
drawPiece(this.activeTetromino, vacant);
this.x++;
drawPiece(this.activeTetromino, this.color);
}
}
Piece.prototype.rotate = function() {
let nextPattern = this.tetromino[(this.tetrominoN + 1) % 4];
let kick = 0;
if (this.collision(0, 0, nextPattern)) {
if(this.x < col/2) {
if(this.x === -2) {
kick = 2;
} else {
kick = 1; //kick from right
}
}
if(this.x > col/2) {
if(this.tetromino === pieces[5][0]) {
kick = -2;
} else {
kick = -1; //kick from left
}
}
}
if(!this.collision(kick, 0, nextPattern)) {
drawPiece(this.activeTetromino, vacant);
this.x += kick;
this.tetrominoN = (this.tetrominoN + 1) % 4;
this.activeTetromino = this.tetromino[this.tetrominoN];
drawPiece(this.activeTetromino, this.color);
}
}
Piece.prototype.collision = function(x, y, piece) {
for (let r = 0; r < piece.length; r++) {
for(let c = 0; c < piece.length; c++) {
if(!piece[r][c]) continue;
let newX = this.x + c + x;
let newY = this.y + r + y;
if(newX < 0 || newX >= col || newY >= row) return true;
if(board[newY][newX] !== vacant) return true;
}
}
return false;
}
Piece.prototype.lockPiece = function(piece) {
for (let r = 0; r < piece.length; r++) {
for(let c = 0; c < piece.length; c++) {
if(!piece[r][c]) continue;
if(this.y + r === 1) alert('yo');
if(this.y + r <= 0) {
alert('Game Over');
gameOver = true;
break;
}
board[this.y + r][this.x + c] = this.color;
}
}
}
function checkForPoints() {
for(let r = 0; r < row; r++) {
if(board[r].every(squareCheck)) {
alert('yo');
board[r].every(clearSquare);
}
}
function squareCheck(sq) {
if(sq !== vacant) return true;
else return false;
}
function clearSquare(sq) {
sq = vacant;
}
}
//start a time to set as a refrence for the dropstart
let dropStart = Date.now();
//create a blueprint function to drop the piece
function drop() {
//grab the current time
let now = Date.now();
//create a var to hold the difference of the current time
let delta = now - dropStart; //------Why can't these be switched------
if(delta > 800) {
dropStart = Date.now();
p.moveDown();
//------put request animation here------
}
if (!gameOver) requestAnimationFrame(drop);
}
drop();
<!-- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tetris</title>
<link href="https://fonts.googleapis.com/css?family=Orbitron&display=swap" rel="stylesheet">
</head>
<style>
body {
background-color: #595959;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
overflow-y: hidden;
}
canvas {
outline: 1px solid white;
}
.canvas-wrap {
padding-left: 50px;
padding-top: 50px;
position: relative;
}
.num-top, .num-bottom {
position: absolute;
top: -1px;
left: 0;
}
.num-top {
width: 100%;
height: 50px;
}
.num-bottom {
height: 100%;
width: 50px;
}
.nb {
font-family: 'Orbitron';
color: white;
}
.num-wrap-t {
display: flex;
justify-content: space-around;
margin-left: 50px;
width: 400px;
}
.num-wrap-b {
display: flex;
flex-direction: column;
justify-content: space-around;
margin-top: 50px;
height: 800px;
}
.num-wrap-b .nb {
text-align: right;
margin-right: 3px;
}
.num-wrap-t .nb {
position: relative;
top: 31px;
}
</style>
<body>
<div class="canvas-wrap">
<div class="num-top">
<div class="num-wrap-t">
<div class="nb">0</div>
<div class="nb">1</div>
<div class="nb">2</div>
<div class="nb">3</div>
<div class="nb">4</div>
<div class="nb">5</div>
<div class="nb">6</div>
<div class="nb">7</div>
<div class="nb">8</div>
<div class="nb">9</div>
</div>
</div>
<canvas id="canvas" width="400" height="800"></canvas>
<div class="num-bottom">
<div class="num-wrap-b">
<div class="nb">0</div>
<div class="nb">1</div>
<div class="nb">2</div>
<div class="nb">3</div>
<div class="nb">4</div>
<div class="nb">5</div>
<div class="nb">6</div>
<div class="nb">7</div>
<div class="nb">8</div>
<div class="nb">9</div>
<div class="nb">10</div>
<div class="nb">11</div>
<div class="nb">12</div>
<div class="nb">13</div>
<div class="nb">14</div>
<div class="nb">15</div>
<div class="nb">16</div>
<div class="nb">17</div>
<div class="nb">18</div>
<div class="nb">19</div>
</div>
</div>
</div>
<script src="tetrominos.js"></script>
<script src="tetris.js"></script>
</body>
</html> -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tetris</title>
<link href="https://fonts.googleapis.com/css?family=Orbitron&display=swap" rel="stylesheet">
</head>
<style>
body, html {
padding: 0;
margin: 0;
}
body {
background-color: #595959;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
canvas {
outline: 1px solid white;
}
.canvas-wrap {
padding-left: 50px;
padding-top: 50px;
position: relative;
}
.num-top, .num-bottom {
position: absolute;
top: -1px;
left: 0;
}
.num-top {
width: 100%;
height: 50px;
}
.num-bottom {
height: 100%;
width: 50px;
}
.nb {
font-family: 'Orbitron';
color: white;
}
.num-wrap-t {
display: flex;
justify-content: space-around;
margin-left: 50px;
width: 400px;
}
.num-wrap-b {
display: flex;
flex-direction: column;
justify-content: space-around;
margin-top: 50px;
height: 800px;
}
.num-wrap-b .nb {
text-align: right;
margin-right: 3px;
}
.num-wrap-t .nb {
position: relative;
top: 31px;
}
</style>
<body>
<div class="canvas-wrap">
<div class="num-top">
<div class="num-wrap-t">
<div class="nb">0</div>
<div class="nb">1</div>
<div class="nb">2</div>
<div class="nb">3</div>
<div class="nb">4</div>
<div class="nb">5</div>
<div class="nb">6</div>
<div class="nb">7</div>
<div class="nb">8</div>
<div class="nb">9</div>
</div>
</div>
<canvas id="canvas" width="400" height="800"></canvas>
<div class="num-bottom">
<div class="num-wrap-b">
<div class="nb">0</div>
<div class="nb">1</div>
<div class="nb">2</div>
<div class="nb">3</div>
<div class="nb">4</div>
<div class="nb">5</div>
<div class="nb">6</div>
<div class="nb">7</div>
<div class="nb">8</div>
<div class="nb">9</div>
<div class="nb">10</div>
<div class="nb">11</div>
<div class="nb">12</div>
<div class="nb">13</div>
<div class="nb">14</div>
<div class="nb">15</div>
<div class="nb">16</div>
<div class="nb">17</div>
<div class="nb">18</div>
<div class="nb">19</div>
</div>
</div>
</div>
<script src="tetrominos.js"></script>
<script src="tetris.js"></script>
</body>
</html>

JavaScript has call by sharing so if you do sq = that will only affect the local sq variable, not the value in the array. You have to directly assign the new value to the array, e.g. board[r][i] = vacant; ...
Additionally .every is the wrong tool then, use .forEach or for(let i = 0; i < board[r].length; i++) , and then reassign the values.
Or could just create a new array and reassign it:
board[r] = new Array(board[r].length).fill(vacant);
that could also be done with .map.

From documentation:
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
The passed function is a TEST function, I imagine that behind the scenes it creates a copy of your array element and activates the function on it.

Related

I'm trying to get localisation in multidimensional array which is equal to mouse coord and put the tile id on it but array refresh everytime

I'm new to dev and i'm trying to learn JS doing game on canvas.
This is a Tile Map Editor project
I'm looking to create a multidimensional array with the ID's of the tiles i drew in the canvas. So when i go to export the JSON i can handle the colissions easily on my game.
But I'm stuck, I can detect the mouse position and put my tile id in the right place, but I don't know how to save the information in my array. Every time i try the array does not save the tile id and replaces with the new one.
//////////////////////////////
//// TO RESOLVE !!!!! ///////
////////////////////////////
let array = [];
function saveIdexedTiledMap() {
for (let l = 0; l < canvas.height / 32; l++) {
array[l] = [];
for (let c = 0; c < canvas.width / 32; c++) {
array[l][c] = 0;
}
}
array[mouseCanvasGrids.y / 32][mouseCanvasGrids.x / 32] =
selectedTile[0].index;
console.log(array);
}
Thanks :D
////////////////////////////////////////////////////////////
/////////// GET INPUT VALUES AND BUTTONS //////////////////
//////////////////////////////////////////////////////////
const clearCanvas = document.querySelector("#btn-clearCanvas");
const exportImage = document.querySelector("#btn-exportImage");
const form = document.querySelector("#form");
const submit = document.querySelector("#submit");
const elems = Array.from(form.elements);
submit.addEventListener("click", (e) => {
e.preventDefault();
elems.forEach((el) => localStorage.setItem(`${el.id}`, `${el.value}`));
});
/////////////////////////////////////////////////////////////
/////////// GET BOTH CANVAS AND VARIABLES //////////////////
///////////////////////////////////////////////////////////
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const canvasImg = document.querySelector("#canvasImg");
const ctxImg = canvasImg.getContext("2d");
let gridsPosX;
let gridsPosY;
let tileSizeW = 32;
let tileSizeH = 32;
let gridsColor = "#bad1f5";
//////////////////////////////////////////////////////////
/////////// DRAW ON CANVAS TILE GRIDS //////////////////
////////////////////////////////////////////////////////
class DrawGrids {
constructor(x, y, canvasW, canvasH, tileW, tileH, color) {
this.x = x;
this.y = y;
this.canvasW = canvasW;
this.canvasH = canvasH;
this.tileSizeW = tileW;
this.tileSizeH = tileH;
this.color = color;
}
draw() {
let tileGridsX;
let tileGridsY;
for (let l = 0; l < this.canvasH / this.tileSizeH; l++) {
for (let c = 0; c < this.canvasW / this.tileSizeW; c++) {
tileGridsX = c * this.tileSizeW;
tileGridsY = l * this.tileSizeH;
const variables = [ctx, ctxImg];
variables.forEach((el) => {
el.strokeStyle = this.color;
el.rect(tileGridsX, tileGridsY, this.tileSizeH, this.tileSizeW);
el.stroke();
});
}
}
}
}
const canvasImgGrids = new DrawGrids(
gridsPosX,
gridsPosY,
canvasImg.width,
canvasImg.height,
tileSizeW,
tileSizeH,
gridsColor
);
const canvasMapGrids = new DrawGrids(
gridsPosX,
gridsPosY,
canvas.width,
canvas.height,
tileSizeW,
tileSizeH,
gridsColor
);
/////////////////////////////////////////////////////////////////////
/////////// GET/SHOW FILE AND CUT IMAGE INTO ARRAY//////////////////
///////////////////////////////////////////////////////////////////
const tileImage = new Image();
tileImage.src = "./images/tileset_32x32(new).png";
tileImage.onload = cutImage;
let imageTileParts = [];
function cutImage() {
let index = 1;
for (let l = 0; l < tileImage.height / 32; l++) {
for (let c = 0; c < tileImage.width / 32; c++) {
imageTileParts.push({
index,
tileImage,
x: c * tileSizeW,
y: l * tileSizeH,
w: tileSizeW,
h: tileSizeH,
x_draw: c * tileSizeW,
y_draw: l * tileSizeH,
});
index++;
}
}
showSpreadSheetImg();
}
function showSpreadSheetImg() {
imageTileParts.forEach((el) => {
ctxImg.drawImage(
el.tileImage,
el.x,
el.y,
el.w,
el.h,
el.x_draw,
el.y_draw,
el.w,
el.h
);
});
canvasImgGrids.draw();
canvasMapGrids.draw();
getMouseCanvasImgPos();
getMouseCanvasPos();
}
//////////////////////////////////////////////////////////////////
/////////// GET MOUSE POSITION AND EVENT CLICK //////////////////
////////////////////////////////////////////////////////////////
let mouseCanvasImg = {};
let mouseCanvasGrids = {};
function getMouseCanvasImgPos() {
const canvasImgPos = canvasImg.getBoundingClientRect();
canvasImg.addEventListener("click", (e) => {
mouseCanvasImg = {
x: Math.floor((e.clientX - canvasImgPos.left) / tileSizeW) * tileSizeW,
y: Math.floor((e.clientY - canvasImgPos.top) / tileSizeH) * tileSizeH,
};
compareMouseIdWithTiles();
});
}
function getMouseCanvasPos() {
const canvasGridsPos = canvas.getBoundingClientRect();
canvas.addEventListener("mousedown", (e) => {
mouseCanvasGrids = {
x: Math.floor((e.clientX - canvasGridsPos.left) / tileSizeW) * tileSizeW,
y: Math.floor((e.clientY - canvasGridsPos.top) / tileSizeH) * tileSizeH,
};
if (e.button == 0) {
drawSelectedTileInGrids();
} else if (e.button == 2) {
deleteSelectedTile();
}
saveIdexedTiledMap();
});
}
/////////////////////////////////////////////////////////////////
/////////// COMPARE MOUSE WITH TILES POSITION //////////////////
///////////////////////////////////////////////////////////////
let selectedTile = [];
function compareMouseIdWithTiles() {
for (let i = 0; i < imageTileParts.length; i++) {
if (
mouseCanvasImg.x == imageTileParts[i].x &&
mouseCanvasImg.y == imageTileParts[i].y
) {
// Delete last tile clicked in the array
if (selectedTile.length >= 1) {
selectedTile.shift();
}
selectedTile.push(imageTileParts[i]);
}
}
}
///////////////////////////////////////////////////////////
/////////// DRAW/DELETE SELECTED TILE IN GRIDS ///////////
/////////////////////////////////////////////////////////
// :: DRAW :: //
function drawSelectedTileInGrids() {
if (selectedTile <= 0) {
console.log("Veuillez choisir une Tile !!!");
} else {
ctx.drawImage(
selectedTile[0].tileImage,
selectedTile[0].x,
selectedTile[0].y,
selectedTile[0].w,
selectedTile[0].h,
mouseCanvasGrids.x,
mouseCanvasGrids.y,
tileSizeW,
tileSizeH
);
}
}
///////////////////////////////
//////////////////////////////
//// TO RESOLVE ON !!!!! ////
////////////////////////////
let array = [];
function saveIdexedTiledMap() {
for (let l = 0; l < canvas.height / 32; l++) {
array[l] = [];
for (let c = 0; c < canvas.width / 32; c++) {
array[l][c] = 0;
}
}
array[mouseCanvasGrids.y / 32][mouseCanvasGrids.x / 32] =
selectedTile[0].index;
console.log(array);
}
// :: DELETE :: //
function deleteSelectedTile() {
ctx.clearRect(mouseCanvasGrids.x, mouseCanvasGrids.y, tileSizeW, tileSizeH);
}
////////////////////////////////////////////////
/////////// CLEAR/SAVE CANVAS IMAGE ///////////
//////////////////////////////////////////////
clearCanvas.addEventListener("click", () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvasMapGrids.draw();
});
////////////////////////////////////////////
/////////// EXPORT CANVAS IMAGE ///////////
//////////////////////////////////////////
* {
box-sizing: border-box;
}
body {
margin: 0;
margin-bottom: 50px;
padding: 0;
}
.body {
width: 900px;
margin-bottom: 50px;
background-color: #ccdaf0;
margin: 20px auto;
border-radius: 8px;
background: linear-gradient(145deg, #dae9ff, #b8c4d8);
box-shadow: 7px 7px 12px #818997, -7px -7px 12px #ffffff;
}
header {
margin: 0 30px;
display: flex;
justify-content: space-between;
align-items: baseline;
}
.content {
display: flex;
}
aside {
flex-grow: 1;
}
.canvas-content {
margin: 0 30px;
border-radius: 8px;
background: #ccdaf0;
box-shadow: inset 7px 7px 12px #818997, inset -7px -7px 12px #ffffff;
}
.img-container {
padding: 10px;
height: 200px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tile Map Editor</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<div class="body">
<header>
<h1>Tile Map Editor</h1>
<div>
<button id="btn-clearCanvas">clear canvas</button>
<button id="btn-exportImage">Export Map</button>
</div>
</header>
<div class="content">
<aside>
<form id="form">
<label>Config : </label>
<div class="config-container">
<div class="mapSize">
<label>Map Size : </label>
<label>width</label>
<input type="number" id="mapSizeW" />
<label>height</label>
<input type="number" id="mapSizeH" />
</div>
<div class="tileSize">
<label>Tile Size</label>
<input type="number" id="tileSize" />
</div>
<input id="submit" type="submit" value="Valider" />
</div>
</form>
</aside>
<div class="canvas-content">
<canvas
oncontextmenu="return false;"
width="608"
height="416"
></canvas>
</div>
</div>
<div id="img-container">
<canvas
oncontextmenu="return false;"
id="canvasImg"
width="600"
height="200"
></canvas>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
This mistake is in this function, you are clearing the array on every save:
let array = [];
function saveIdexedTiledMap() {
for (let l = 0; l < canvas.height / 32; l++) {
array[l] = [];
for (let c = 0; c < canvas.width / 32; c++) {
array[l][c] = 0;
}
}
array[mouseCanvasGrids.y / 32][mouseCanvasGrids.x / 32] =
selectedTile[0].index;
console.log(array);
}
So you need to move the clearing outside like this:
let array = [];
for (let l = 0; l < canvas.height / 32; l++) {
array[l] = [];
for (let c = 0; c < canvas.width / 32; c++) {
array[l][c] = 0;
}
}
function saveIdexedTiledMap() {
array[mouseCanvasGrids.y / 32][mouseCanvasGrids.x / 32] =
selectedTile[0].index;
console.log(array);
}

How to add a game menu

I am trying to add a generic game menu with "start" to initiate the game. How do I go about doing this? Here is the code:
var LEFT_KEY = 37;
var UP_KEY = 38;
var RIGHT_KEY = 39;
var DOWN_KEY = 40;
var SPACE_KEY = 32;
var HERO_MOVEMENT = 3;
var lastLoopRun = 0;
var score = 0;
var iterations = 0;
var controller = new Object();
var enemies = new Array();
function createSprite(element, x, y, w, h) {
var result = new Object();
result.element = element;
result.x = x;
result.y = y;
result.w = w;
result.h = h;
return result;
}
function toggleKey(keyCode, isPressed) {
if (keyCode == LEFT_KEY) {
controller.left = isPressed;
}
if (keyCode == RIGHT_KEY) {
controller.right = isPressed;
}
if (keyCode == UP_KEY) {
controller.up = isPressed;
}
if (keyCode == DOWN_KEY) {
controller.down = isPressed;
}
if (keyCode == SPACE_KEY) {
controller.space = isPressed;
}
}
function intersects(a, b) {
return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
}
function ensureBounds(sprite, ignoreY) {
if (sprite.x < 20) {
sprite.x = 20;
}
if (!ignoreY && sprite.y < 20) {
sprite.y = 20;
}
if (sprite.x + sprite.w > 480) {
sprite.x = 480 - sprite.w;
}
if (!ignoreY && sprite.y + sprite.h > 480) {
sprite.y = 480 - sprite.h;
}
}
function setPosition(sprite) {
var e = document.getElementById(sprite.element);
e.style.left = sprite.x + 'px';
e.style.top = sprite.y + 'px';
}
function handleControls() {
if (controller.up) {
hero.y -= HERO_MOVEMENT;
}
if (controller.down) {
hero.y += HERO_MOVEMENT;
}
if (controller.left) {
hero.x -= HERO_MOVEMENT;
}
if (controller.right) {
hero.x += HERO_MOVEMENT;
}
if (controller.space) {
var laser = getFireableLaser();
if (laser) {
laser.x = hero.x + 9;
laser.y = hero.y - laser.h;
}
}
ensureBounds(hero);
}
function getFireableLaser() {
var result = null;
for (var i = 0; i < lasers.length; i++) {
if (lasers[i].y <= -120) {
result = lasers[i];
}
}
return result;
}
function getIntersectingLaser(enemy) {
var result = null;
for (var i = 0; i < lasers.length; i++) {
if (intersects(lasers[i], enemy)) {
result = lasers[i];
break;
}
}
return result;
}
function checkCollisions() {
for (var i = 0; i < enemies.length; i++) {
var laser = getIntersectingLaser(enemies[i]);
if (laser) {
var element = document.getElementById(enemies[i].element);
element.style.visibility = 'hidden';
element.parentNode.removeChild(element);
enemies.splice(i, 1);
i--;
laser.y = -laser.h;
score += 100;
} else if (intersects(hero, enemies[i])) {
gameOver();
} else if (enemies[i].y + enemies[i].h >= 500) {
var element = document.getElementById(enemies[i].element);
element.style.visibility = 'hidden';
element.parentNode.removeChild(element);
enemies.splice(i, 1);
i--;
}
}
}
function gameOver() {
var element = document.getElementById(hero.element);
element.style.visibility = 'hidden';
element = document.getElementById('gameover');
element.style.visibility = 'visible';
}
function showSprites() {
setPosition(hero);
for (var i = 0; i < lasers.length; i++) {
setPosition(lasers[i]);
}
for (var i = 0; i < enemies.length; i++) {
setPosition(enemies[i]);
}
var scoreElement = document.getElementById('score');
scoreElement.innerHTML = 'SCORE: ' + score;
}
function updatePositions() {
for (var i = 0; i < enemies.length; i++) {
enemies[i].y += 4;
enemies[i].x += getRandom(7) - 3;
ensureBounds(enemies[i], true);
}
for (var i = 0; i < lasers.length; i++) {
lasers[i].y -= 12;
}
}
function addEnemy() {
var interval = 50;
if (iterations > 1500) {
interval = 5;
} else if (iterations > 1000) {
interval = 20;
} else if (iterations > 500) {
interval = 35;
}
if (getRandom(interval) == 0) {
var elementName = 'enemy' + getRandom(10000000);
var enemy = createSprite(elementName, getRandom(450), -40, 35, 35);
var element = document.createElement('div');
element.id = enemy.element;
element.className = 'enemy';
document.children[0].appendChild(element);
enemies[enemies.length] = enemy;
}
}
function getRandom(maxSize) {
return parseInt(Math.random() * maxSize);
}
function loop() {
if (new Date().getTime() - lastLoopRun > 40) {
updatePositions();
handleControls();
checkCollisions();
addEnemy();
showSprites();
lastLoopRun = new Date().getTime();
iterations++;
}
setTimeout('loop();', 2);
}
document.onkeydown = function(evt) {
toggleKey(evt.keyCode, true);
};
document.onkeyup = function(evt) {
toggleKey(evt.keyCode, false);
};
var hero = createSprite('hero', 250, 460, 20, 20);
var lasers = new Array();
for (var i = 0; i < 3; i++) {
lasers[i] = createSprite('laser' + i, 0, -120, 2, 50);
}
loop();
#hero {
/* background: #ff0000; */
background-image: url("man-of-space.png");
width: 40px;
height: 40px;
position: absolute;
}
#background {
background-image: url("space.png");
/* background: #000000; */
width: 500px;
height: 500px;
position: absolute;
left: 0px;
top: 0px;
}
.laser {
background: #00ff00;
width: 2px;
height: 50px;
position: absolute;
}
.enemy {
background-image: url("spaceship.png");
background-size: 40px 40px;
width: 40px;
height: 40px;
position: absolute;
}
#score {
color: #ffffff;
font-size: 18pt;
position: absolute;
left: 20px;
top: 20px;
}
#gameover {
color: #ff0000;
font-size: 20px;
position: absolute;
left: 160px;
top: 200px;
visibility: hidden;
}
<div id="background"></div>
<div id="hero"></div>
<div class="laser" id="laser0"></div>
<div class="laser" id="laser1"></div>
<div class="laser" id="laser2"></div>
<div id="score"></div>
<div id="gameover">GAME OVER</div>
You could wrap your game UI in a <div id="game" style="display: none;"> element so it will be hidden when the page is loaded. Then wrap your start menu in a <div id="startMenu"> element with a <button id="startButton">Start</button> that will be used to hide the start menu and show the game UI.
In your JS code you could wrap your game in a function so it can be started when you call it.
HTML:
<div id="startMenu">
<button id="startButton">Start</button>
</div>
<div id="game" style="display: none;">
<div id="background"></div>
<div id="hero"></div>
<div class="laser" id="laser0"></div>
<div class="laser" id="laser1"></div>
<div class="laser" id="laser2"></div>
<div id="score"></div>
<div id="gameover">GAME OVER</div>
</div>
JS:
function startGame() {
var LEFT_KEY = 37;
var UP_KEY = 38;
var RIGHT_KEY = 39;
var DOWN_KEY = 40;
var SPACE_KEY = 32;
var HERO_MOVEMENT = 3;
[...Your game code...]
loop();
}
document.getElementById('startButton').onclick = function() {
document.getElementById('startMenu').style.display = "none";
document.getElementById('game').style.display = "";
startGame();
};
Now you have a start menu (<div id="startMenu">) that you can customize however you like, and a game UI (<div id="game">) that will be shown only after the start button is pressed.
Add more HTML would be my suggestion. Maybe make a div that has all the start screen elements you need in it. When the start function happens, set that div's innerHTML to "".
Example:
document.getElementById('yourDivIdHere').innerHTML = '';

Retrieve an element inside an object collection

I'm making board game, and I want that when I click in one of the places I turn them red. I have this array of divs, but I don't know how to retrieve the element given the number to turn it red. How can I do that, I'm trying to use .element but it's not working
var number = 3;
const board = [];
const boardWidth = boardHeight = 10;
(function() {
const boardElement = document.getElementById('board');
for (var y = 0; y < boardHeight; ++y) {
var row = [];
for (var x = 0; x < boardWidth; ++x) {
var cell = {};
cell.element = document.createElement('div');
boardElement.appendChild(cell.element);
row.push(cell);
}
board.push(row);
}
painting();
})();
function painting() {
board[number][number].element.style.backgroundcolor = 'red';
}
#board {
width: calc(10 * 30px);
margin: auto;
}
#board div {
background-color: black;
border: 1px solid white;
box-sizing: border-box;
float: left;
width: 30px;
height: 30px;
}
<div id="board"></div>
Your code look very confusing. board is an element and you are using it as an array.
Next come some code. I hope this is what you need:
let cellW = 100;
let cellH = 100;
function init(){
let boardArray = [];
let bStyle = window.getComputedStyle(board, null);
let bWidth = parseInt(bStyle.getPropertyValue("width"));
let bHeight = parseInt(bStyle.getPropertyValue("height"));
for (let y = 0; y < bHeight; y+=cellH) {
let row = [];
for (let x = 0; x < bWidth; x+=cellW) {
let cell = {};
cell.element = document.createElement('div');
cell.element.style.width = cellW +"px";
cell.element.style.height = cellH +"px";
board.appendChild(cell.element);
row.push(cell);
}
boardArray.push(row);
}
}
init();
let cells = Array.from(document.querySelectorAll("#board div"));
cells.map( cell => {
cell.addEventListener("click", e =>{
cell.style.background = "red"
})
})
#board{width: 1000px; height:500px; display:flex;flex-wrap:wrap;}
#board div{outline:1px solid;}
<div id="board"></div>
UPDATE:
I understand that you need to make the 4-th cell in the cells array red:
var number = 3;
const board = [];
const boardWidth = 10, boardHeight = 10;
function init() {
const boardElement = document.getElementById('board');
for (var y = 0; y < boardHeight; ++y) {
var row = [];
for (var x = 0; x < boardWidth; ++x) {
var cell = {};
cell.element = document.createElement('div');
boardElement.appendChild(cell.element);
row.push(cell);
}
board.push(row);
}
board[number][number].element.style.background = "red"
}
window.addEventListener("load", init);
#board {
width: calc(10 * 30px);
margin: auto;
}
#board div {
background-color: black;
border: 1px solid white;
box-sizing: border-box;
float: left;
width: 30px;
height: 30px;
}
<div id="board"></div>
I've addressed all of your issues but thought you might be interested in making things configurable. I reworked your code to make things config driven.
This will:
Take a config (or not) and merge it with a default config.
Build your board dynamically based on config values v. setting the dimensions via CSS
Allows for cell toggle (select/unselect) and matric position assignments
document.addEventListener('DOMContentLoaded', function(){
const extend = function(target, config, defaults){
defaults && extend(target, defaults);
if(target && config && typeof(config) === 'object'){
for(const i in config){
target[i] = config[i];
}
}
return target;
};
function Game(config){
const defaultConfig = {
boardElement: '#board',
// if a single digit is passed it will be duplicated for pos y 3 => 3,3
startPosition: 3,
cellSize: 30,
boardWidth: 10,
boardHeight: 10
};
// merge the default and user-defined config into a new config
this.config = extend({}, config || {}, defaultConfig);
// cache ref to your board element
this.boardElement = document.querySelector(this.config.boardElement);
// stores our collection of board items
this.board = [];
// draw the board
this.draw();
// set initial marker
if(this.config.startPosition){
if(this.config.startPosition instanceof Array){
this.paint.apply(this, this.config.startPosition);
}else{
this.paint(this.config.startPosition);
}
}
return this;
}
extend(Game.prototype, {
draw(){
for (let y = 0; y < this.config.boardHeight; ++y) {
const row = [];
for (var x = 0; x < this.config.boardWidth; ++x) {
const element = document.createElement('div');
const cell = {
element,
position: {
x: x + 1,
y: y + 1
}
};
// set cell width and height
element.style.height = element.style.width = `${this.config.cellSize}px`;
// handle selecting/unselecting cells
element.addEventListener('click', () => this.paint(cell.position.x, cell.position.y));
this.boardElement.appendChild(cell.element);
row.push(cell);
}
this.board.push(row);
}
// set board width and height
this.boardElement.style.width = `${this.config.boardWidth * this.config.cellSize}px`;
},
paint(x, y){
if(y === undefined){
y = x;
}
const element = this.board[y-1][x-1].element;
if(element){
const isSelcted = element.style.backgroundColor === 'red';
element.style.backgroundColor = isSelcted ? 'black' : 'red';
}
}
});
new Game({
startPosition: [5,4],
boardWidth: 8,
boardHeight: 8
});
});
#board {
margin: auto;
}
#board div {
background-color: black;
border: 1px solid white;
box-sizing: border-box;
float: left;
}
<div id="board"></div>

How can I fix height, container with scrollbar

I'm using a simple JavaScript. I change the container's height and width. I think I need to fix the JavaScript, because it is working on the container which as height set in px, but I have set the height as %. The problem is appearing when you resize (you can't see full img or there is too much space) on bottom of the container.
Or maybe I'm wrong... Any tips?
function jsScroller (o, w, h) {
var self = this;
var list = o.getElementsByTagName("div");
for (var i = 0; i < list.length; i++) {
if (list[i].className.indexOf("Scroller-Container") > -1) {
o = list[i];
}
}
//Private methods
this._setPos = function (x, y) {
if (x < this.viewableWidth - this.totalWidth)
x = this.viewableWidth - this.totalWidth;
if (x > 0) x = 0;
if (y < this.viewableHeight - this.totalHeight)
y = this.viewableHeight - this.totalHeight;
if (y > 0) y = 0;
this._x = x;
this._y = y;
with (o.style) {
left = this._x +"px";
top = this._y +"px";
}
};
//Public Methods
this.reset = function () {
this.content = o;
this.totalHeight = o.offsetHeight;
this.totalWidth = o.offsetWidth;
this._x = 0;
this._y = 0;
with (o.style) {
left = "0px";
top = "0px";
}
};
this.scrollBy = function (x, y) {
this._setPos(this._x + x, this._y + y);
};
this.scrollTo = function (x, y) {
this._setPos(-x, -y);
};
this.stopScroll = function () {
if (this.scrollTimer) window.clearInterval(this.scrollTimer);
};
this.startScroll = function (x, y) {
this.stopScroll();
this.scrollTimer = window.setInterval(
function(){ self.scrollBy(x, y); }, 40
);
};
this.swapContent = function (c, w, h) {
o = c;
var list = o.getElementsByTagName("div");
for (var i = 0; i < list.length; i++) {
if (list[i].className.indexOf("Scroller-Container") > -1) {
o = list[i];
}
}
if (w) this.viewableWidth = w;
if (h) this.viewableHeight = h;
this.reset();
};
//variables
this.content = o;
this.viewableWidth = w;
this.viewableHeight = h;
this.totalWidth = o.offsetWidth;
this.totalHeight = o.offsetHeight;
this.scrollTimer = null;
this.reset();
};
function jsScrollbar (o, s, a, ev) {
var self = this;
this.reset = function () {
//Arguments that were passed
this._parent = o;
this._src = s;
this.auto = a ? a : false;
this.eventHandler = ev ? ev : function () {};
//Component Objects
this._up = this._findComponent("Scrollbar-Up", this._parent);
this._down = this._findComponent("Scrollbar-Down", this._parent);
this._yTrack = this._findComponent("Scrollbar-Track", this._parent);
this._yHandle = this._findComponent("Scrollbar-Handle", this._yTrack);
//Height and position properties
this._trackTop = findOffsetTop(this._yTrack);
this._trackHeight = this._yTrack.offsetHeight;
this._handleHeight = this._yHandle.offsetHeight;
this._x = 0;
this._y = 0;
//Misc. variables
this._scrollDist = 5;
this._scrollTimer = null;
this._selectFunc = null;
this._grabPoint = null;
this._tempTarget = null;
this._tempDistX = 0;
this._tempDistY = 0;
this._disabled = false;
this._ratio = (this._src.totalHeight - this._src.viewableHeight)/(this._trackHeight - this._handleHeight);
this._yHandle.ondragstart = function () {return false;};
this._yHandle.onmousedown = function () {return false;};
this._addEvent(this._src.content, "mousewheel", this._scrollbarWheel);
this._removeEvent(this._parent, "mousedown", this._scrollbarClick);
this._addEvent(this._parent, "mousedown", this._scrollbarClick);
this._src.reset();
with (this._yHandle.style) {
top = "0px";
left = "0px";
}
this._moveContent();
if (this._src.totalHeight < this._src.viewableHeight) {
this._disabled = true;
this._yHandle.style.visibility = "hidden";
if (this.auto) this._parent.style.visibility = "hidden";
} else {
this._disabled = false;
this._yHandle.style.visibility = "visible";
this._parent.style.visibility = "visible";
}
};
this._addEvent = function (o, t, f) {
if (o.addEventListener) o.addEventListener(t, f, false);
else if (o.attachEvent) o.attachEvent('on'+ t, f);
else o['on'+ t] = f;
};
this._removeEvent = function (o, t, f) {
if (o.removeEventListener) o.removeEventListener(t, f, false);
else if (o.detachEvent) o.detachEvent('on'+ t, f);
else o['on'+ t] = null;
};
this._findComponent = function (c, o) {
var kids = o.childNodes;
for (var i = 0; i < kids.length; i++) {
if (kids[i].className && kids[i].className == c) {
return kids[i];
}
}
};
//Thank you, Quirksmode
function findOffsetTop (o) {
var t = 0;
if (o.offsetParent) {
while (o.offsetParent) {
t += o.offsetTop;
o = o.offsetParent;
}
}
return t;
};
this._scrollbarClick = function (e) {
if (self._disabled) return false;
e = e ? e : event;
if (!e.target) e.target = e.srcElement;
if (e.target.className.indexOf("Scrollbar-Up") > -1) self._scrollUp(e);
else if (e.target.className.indexOf("Scrollbar-Down") > -1) self._scrollDown(e);
else if (e.target.className.indexOf("Scrollbar-Track") > -1) self._scrollTrack(e);
else if (e.target.className.indexOf("Scrollbar-Handle") > -1) self._scrollHandle(e);
self._tempTarget = e.target;
self._selectFunc = document.onselectstart;
document.onselectstart = function () {return false;};
self.eventHandler(e.target, "mousedown");
self._addEvent(document, "mouseup", self._stopScroll, false);
return false;
};
this._scrollbarDrag = function (e) {
e = e ? e : event;
var t = parseInt(self._yHandle.style.top);
var v = e.clientY + document.body.scrollTop - self._trackTop;
with (self._yHandle.style) {
if (v >= self._trackHeight - self._handleHeight + self._grabPoint)
top = self._trackHeight - self._handleHeight +"px";
else if (v <= self._grabPoint) top = "0px";
else top = v - self._grabPoint +"px";
self._y = parseInt(top);
}
self._moveContent();
};
this._scrollbarWheel = function (e) {
e = e ? e : event;
var dir = 0;
if (e.wheelDelta >= 120) dir = -1;
if (e.wheelDelta <= -120) dir = 1;
self.scrollBy(0, dir * 20);
e.returnValue = false;
};
this._startScroll = function (x, y) {
this._tempDistX = x;
this._tempDistY = y;
this._scrollTimer = window.setInterval(function () {
self.scrollBy(self._tempDistX, self._tempDistY);
}, 40);
};
this._stopScroll = function () {
self._removeEvent(document, "mousemove", self._scrollbarDrag, false);
self._removeEvent(document, "mouseup", self._stopScroll, false);
if (self._selectFunc) document.onselectstart = self._selectFunc;
else document.onselectstart = function () { return true; };
if (self._scrollTimer) window.clearInterval(self._scrollTimer);
self.eventHandler (self._tempTarget, "mouseup");
};
this._scrollUp = function (e) {this._startScroll(0, -this._scrollDist);};
this._scrollDown = function (e) {this._startScroll(0, this._scrollDist);};
this._scrollTrack = function (e) {
var curY = e.clientY + document.body.scrollTop;
this._scroll(0, curY - this._trackTop - this._handleHeight/2);
};
this._scrollHandle = function (e) {
var curY = e.clientY + document.body.scrollTop;
this._grabPoint = curY - findOffsetTop(this._yHandle);
this._addEvent(document, "mousemove", this._scrollbarDrag, false);
};
this._scroll = function (x, y) {
if (y > this._trackHeight - this._handleHeight)
y = this._trackHeight - this._handleHeight;
if (y < 0) y = 0;
this._yHandle.style.top = y +"px";
this._y = y;
this._moveContent();
};
this._moveContent = function () {
this._src.scrollTo(0, Math.round(this._y * this._ratio));
};
this.scrollBy = function (x, y) {
this._scroll(0, (-this._src._y + y)/this._ratio);
};
this.scrollTo = function (x, y) {
this._scroll(0, y/this._ratio);
};
this.swapContent = function (o, w, h) {
this._removeEvent(this._src.content, "mousewheel", this._scrollbarWheel, false);
this._src.swapContent(o, w, h);
this.reset();
};
this.reset();
};
#no-template-pager {
width: 34%;
height: 25vw;
overflow: hidden;
white-space: nowrap;
float: left;
}
.Scroller-Container {
position: relative;
width: 100%;
height: 100%;
}
#Scrollbar-Container {
position: relative;
top: 0px;
left: 0%;
background: green;
width: 1%;
height: 100%;
overflow: hidden;
}
.Scrollbar-Track {
width: 100%;
height: 100%;
position: absolute;
background: #222;
}
.Scrollbar-Handle {
position: absolute;
width: 100%;
height: 70%;
background: #8E8E8E;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
}
.Scrollbar-Handle:hover, .Scrollbar-Handle:active {
background: #fff;
}
#slider2 {
margin: 50px auto;
width: 60%;
height: 25vw;
background: #222;
}
#youtube {
width: 65%;
height: 25vw;
float: right;
background: blue;
}
.thumbs {
width: 100%;
height: 25%;
box-shadow: 0 -1px 0 #5A5A5A,
0 -1px 0 #707070;
}
.thumbs img {
margin: 3% 4%;
width: 80%;
height: 80%;
float: left;
}
<section id="slider2">
<div id="youtube">
</div>
<div id="no-template-pager" class="cycle-pager external">
<div class="Scroller-Container">
<!-- using thumbnail image files would be even better! -->
<div class="thumbs">
<img src="http://img.youtube.com/vi/Je7VuV9yHIw/mqdefault.jpg">
</div>
<div class="thumbs">
<img src="http://img.youtube.com/vi/uxps_fYUeJk/mqdefault.jpg">
</div>
<div class="thumbs">
<img src="http://img.youtube.com/vi/Zvr3cwbbqHU/mqdefault.jpg">
</div>
<div class="thumbs">
<img src="http://img.youtube.com/vi/Ka9xtXPD3BA/mqdefault.jpg">
</div>
<div class="thumbs">
<img src="http://img.youtube.com/vi/U8HVQXkeU8U/mqdefault.jpg">
</div>
<div class="thumbs">
<img src="http://img.youtube.com/vi/e7_UUfokexM/mqdefault.jpg">
</div>
</div>
</div>
<div id="Scrollbar-Container">
<div class="Scrollbar-Track">
<div class="Scrollbar-Handle"></div>
</div>
</div>
</section>
<script>
var scroller = null;
var scrollbar = null;
window.onload = function () {
scroller = new jsScroller(document.getElementById("no-template-pager"), 400, 200);
scrollbar = new jsScrollbar (document.getElementById("Scrollbar-Container"), scroller, true);
}
</script>
Link to CodePen 1. and to Javascript 2.:
[1]: http://codepen.io/psairidas/pen/RaVwzw
[2]: http://www.n-son.com/scripts/jsScrolling/jsScrollbar.html
You should probably set a max-height or max-width in pixels, so that it will resize but once it hits that max-height or max-width it won't get any smaller. Then if you want it to scroll, you can set overflow: scroll or overflow: auto (auto is generally recommended).

Why is this index html not displaying the game on my desk top?

I found this game online and am trying to get it to run from my desktop. Is there something special that a person has to do with the URL's or images to make the file recognize were everything is running and located at. I have all of the files and .png files in one folder and on the same level.
I would think that I should see the game on the screen. It is like a left to right horizontal scroll-er with enemy ships that come out of the right side of the screen and the main ship is on the right side of the screen. (Similar to that of the old style defender game)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="app.css">
</head>
<body>
<div id="game-over-overlay"></div>
<div id="game-over">
<h1>GAME OVER</h1>
<button id="play-again">Play Again</button>
</div>
<div class="wrapper">
<div id="instructions">
<div>
move with <span class="key">arrows</span> or <span class="key">wasd</span>
</div>
<div>
shoot with <span class="key">space</span>
</div>
</div>
<div id="score"></div>
</div>
<script type="text/javascript" src="resources.js"></script>
<script type="text/javascript" src="input.js"></script>
<script type="text/javascript" src="sprite.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
sprite.js
(function() {
function Sprite(url, pos, size, speed, frames, dir, once) {
this.pos = pos;
this.size = size;
this.speed = typeof speed === 'number' ? speed : 0;
this.frames = frames;
this._index = 0;
this.url = url;
this.dir = dir || 'horizontal';
this.once = once;
};
Sprite.prototype = {
update: function(dt) {
this._index += this.speed*dt;
},
render: function(ctx) {
var frame;
if(this.speed > 0) {
var max = this.frames.length;
var idx = Math.floor(this._index);
frame = this.frames[idx % max];
if(this.once && idx >= max) {
this.done = true;
return;
}
}
else {
frame = 0;
}
var x = this.pos[0];
var y = this.pos[1];
if(this.dir == 'vertical') {
y += frame * this.size[1];
}
else {
x += frame * this.size[0];
}
ctx.drawImage(resources.get(this.url),
x, y,
this.size[0], this.size[1],
0, 0,
this.size[0], this.size[1]);
}
};
window.Sprite = Sprite;
resources.js
(function() {
var resourceCache = {};
var loading = [];
var readyCallbacks = [];
// Load an image url or an array of image urls
function load(urlOrArr) {
if(urlOrArr instanceof Array) {
urlOrArr.forEach(function(url) {
_load(url);
});
}
else {
_load(urlOrArr);
}
}
function _load(url) {
if(resourceCache[url]) {
return resourceCache[url];
}
else {
var img = new Image();
img.onload = function() {
resourceCache[url] = img;
if(isReady()) {
readyCallbacks.forEach(function(func) { func(); });
}
};
resourceCache[url] = false;
img.src = url;
}
}
function get(url) {
return resourceCache[url];
}
function isReady() {
var ready = true;
for(var k in resourceCache) {
if(resourceCache.hasOwnProperty(k) &&
!resourceCache[k]) {
ready = false;
}
}
return ready;
}
function onReady(func) {
readyCallbacks.push(func);
}
window.resources = {
load: load,
get: get,
onReady: onReady,
isReady: isReady
};
input.js
(function() {
var pressedKeys = {};
function setKey(event, status) {
var code = event.keyCode;
var key;
switch(code) {
case 32:
key = 'SPACE'; break;
case 37:
key = 'LEFT'; break;
case 38:
key = 'UP'; break;
case 39:
key = 'RIGHT'; break;
case 40:
key = 'DOWN'; break;
default:
key = String.fromCharCode(code);
}
pressedKeys[key] = status;
}
document.addEventListener('keydown', function(e) {
setKey(e, true);
});
document.addEventListener('keyup', function(e) {
setKey(e, false);
});
window.addEventListener('blur', function() {
pressedKeys = {};
});
window.input = {
isDown: function(key) {
return pressedKeys[key.toUpperCase()];
}
};
apps.js
// A cross-browser requestAnimationFrame
// See https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/
var requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// The main game loop
var lastTime;
function main() {
var now = Date.now();
var dt = (now - lastTime) / 1000.0;
update(dt);
render();
lastTime = now;
requestAnimFrame(main);
};
function init() {
terrainPattern = ctx.createPattern(resources.get('terrain.png'), 'repeat');
document.getElementById('play-again').addEventListener('click', function() {
reset();
});
reset();
lastTime = Date.now();
main();
}
resources.load([
'sprites.png',
'terrain.png'
]);
resources.onReady(init);
// Game state
var player = {
pos: [0, 0],
sprite: new Sprite('sprites.png', [0, 0], [39, 39], 16, [0, 1])
};
var bullets = [];
var enemies = [];
var explosions = [];
var lastFire = Date.now();
var gameTime = 0;
var isGameOver;
var terrainPattern;
var score = 0;
var scoreEl = document.getElementById('score');
// Speed in pixels per second
var playerSpeed = 200;
var bulletSpeed = 500;
var enemySpeed = 100;
// Update game objects
function update(dt) {
gameTime += dt;
handleInput(dt);
updateEntities(dt);
// It gets harder over time by adding enemies using this
// equation: 1-.993^gameTime
if(Math.random() < 1 - Math.pow(.993, gameTime)) {
enemies.push({
pos: [canvas.width,
Math.random() * (canvas.height - 39)],
sprite: new Sprite('sprites.png', [0, 78], [80, 39],
6, [0, 1, 2, 3, 2, 1])
});
}
checkCollisions();
scoreEl.innerHTML = score;
};
function handleInput(dt) {
if(input.isDown('DOWN') || input.isDown('s')) {
player.pos[1] += playerSpeed * dt;
}
if(input.isDown('UP') || input.isDown('w')) {
player.pos[1] -= playerSpeed * dt;
}
if(input.isDown('LEFT') || input.isDown('a')) {
player.pos[0] -= playerSpeed * dt;
}
if(input.isDown('RIGHT') || input.isDown('d')) {
player.pos[0] += playerSpeed * dt;
}
if(input.isDown('SPACE') && !isGameOver && Date.now() - lastFire > 100) {
var x = player.pos[0] + player.sprite.size[0] / 2;
var y = player.pos[1] + player.sprite.size[1] / 2;
bullets.push({ pos: [x, y],
dir: 'forward',
sprite: new Sprite('sprites.png', [0, 39], [18, 8]) });
bullets.push({ pos: [x, y],
dir: 'up',
sprite: new Sprite('sprites.png', [0, 50], [9, 5]) });
bullets.push({ pos: [x, y],
dir: 'down',
sprite: new Sprite('sprites.png', [0, 60], [9, 5]) });
lastFire = Date.now();
}
}
function updateEntities(dt) {
// Update the player sprite animation
player.sprite.update(dt);
// Update all the bullets
for(var i=0; i<bullets.length; i++) {
var bullet = bullets[i];
switch(bullet.dir) {
case 'up': bullet.pos[1] -= bulletSpeed * dt; break;
case 'down': bullet.pos[1] += bulletSpeed * dt; break;
default:
bullet.pos[0] += bulletSpeed * dt;
}
// Remove the bullet if it goes offscreen
if(bullet.pos[1] < 0 || bullet.pos[1] > canvas.height ||
bullet.pos[0] > canvas.width) {
bullets.splice(i, 1);
i--;
}
}
// Update all the enemies
for(var i=0; i<enemies.length; i++) {
enemies[i].pos[0] -= enemySpeed * dt;
enemies[i].sprite.update(dt);
// Remove if offscreen
if(enemies[i].pos[0] + enemies[i].sprite.size[0] < 0) {
enemies.splice(i, 1);
i--;
}
}
// Update all the explosions
for(var i=0; i<explosions.length; i++) {
explosions[i].sprite.update(dt);
// Remove if animation is done
if(explosions[i].sprite.done) {
explosions.splice(i, 1);
i--;
}
}
}
// Collisions
function collides(x, y, r, b, x2, y2, r2, b2) {
return !(r <= x2 || x > r2 ||
b <= y2 || y > b2);
}
function boxCollides(pos, size, pos2, size2) {
return collides(pos[0], pos[1],
pos[0] + size[0], pos[1] + size[1],
pos2[0], pos2[1],
pos2[0] + size2[0], pos2[1] + size2[1]);
}
function checkCollisions() {
checkPlayerBounds();
// Run collision detection for all enemies and bullets
for(var i=0; i<enemies.length; i++) {
var pos = enemies[i].pos;
var size = enemies[i].sprite.size;
for(var j=0; j<bullets.length; j++) {
var pos2 = bullets[j].pos;
var size2 = bullets[j].sprite.size;
if(boxCollides(pos, size, pos2, size2)) {
// Remove the enemy
enemies.splice(i, 1);
i--;
// Add score
score += 100;
// Add an explosion
explosions.push({
pos: pos,
sprite: new Sprite('sprites.png',
[0, 117],
[39, 39],
16,
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
null,
true)
});
// Remove the bullet and stop this iteration
bullets.splice(j, 1);
break;
}
}
if(boxCollides(pos, size, player.pos, player.sprite.size)) {
gameOver();
}
}
}
function checkPlayerBounds() {
// Check bounds
if(player.pos[0] < 0) {
player.pos[0] = 0;
}
else if(player.pos[0] > canvas.width - player.sprite.size[0]) {
player.pos[0] = canvas.width - player.sprite.size[0];
}
if(player.pos[1] < 0) {
player.pos[1] = 0;
}
else if(player.pos[1] > canvas.height - player.sprite.size[1]) {
player.pos[1] = canvas.height - player.sprite.size[1];
}
}
// Draw everything
function render() {
ctx.fillStyle = terrainPattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Render the player if the game isn't over
if(!isGameOver) {
renderEntity(player);
}
renderEntities(bullets);
renderEntities(enemies);
renderEntities(explosions);
};
function renderEntities(list) {
for(var i=0; i<list.length; i++) {
renderEntity(list[i]);
}
}
function renderEntity(entity) {
ctx.save();
ctx.translate(entity.pos[0], entity.pos[1]);
entity.sprite.render(ctx);
ctx.restore();
}
// Game over
function gameOver() {
document.getElementById('game-over').style.display = 'block';
document.getElementById('game-over-overlay').style.display = 'block';
isGameOver = true;
}
// Reset game to original state
function reset() {
document.getElementById('game-over').style.display = 'none';
document.getElementById('game-over-overlay').style.display = 'none';
isGameOver = false;
gameTime = 0;
score = 0;
enemies = [];
bullets = [];
player.pos = [50, canvas.height / 2];
app.css
html, body {
margin: 0;
padding: 0;
background-color: #151515;
}
canvas {
display: block;
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.wrapper {
width: 512px;
margin: 0 auto;
margin-top: 2em;
}
#instructions {
float: left;
font-family: sans-serif;
color: #757575;
}
#score {
float: right;
color: white;
font-size: 2em;
}
.key {
color: #aaffdd;
}
#game-over, #game-over-overlay {
margin: auto;
width: 512px;
height: 480px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
display: none;
}
#game-over-overlay {
background-color: black;
opacity: .5;
}
#game-over {
height: 200px;
text-align: center;
color: white;
}
#game-over h1 {
font-size: 3em;
font-family: sans-serif;
}
#game-over button {
font-size: 1.5em;
}
Here is the original game link
http://jlongster.com/Making-Sprite-based-Games-with-Canvas
If someone could put up a fiddle to see why it is not working it would be most appreciated.
Errors from the console
Uncaught SyntaxError: Unexpected end of input resources.js:61
Uncaught SyntaxError: Unexpected end of input input.js:43
Uncaught SyntaxError: Unexpected end of input sprite.js:54
Uncaught SyntaxError: Unexpected end of input app.js:302
Are you running this on a webserver? The way that you phrased it makes me think you you downloaded those files and just double-clicked index.html.
You need to download something like https://www.apachefriends.org/index.html and start the Apache service up, then put your files in the /xampp/htdocs/ folder... then goto
http://localhost/index.html
to get it to load.

Categories