Can't figure out how to add a little space between blocks - javascript

I wrote the little snake game at the bottom of this post.
Now I would like to separate each block of snake body by a little bit of (black) space between the blocks so that the green blocks are clearly a bit apart from each other.
Something like [s] [s] [s] [s]. [s] is what it's now a single green block of snake body, but I don't know how to add the space in between.
I am comfortable in JS, but these specifics of CSS are still a mystery to me. I'm not even sure I'm using the right approach to "draw" the snake in the first place.
let _game;
var gameLoopHandle;
var pollingHandle;
let Snake = function(forGame,startingDirection, startingBody){
this.going = startingDirection || "RIGHT";
this.go = function(direction){
let snakeHead = {x:this.getHead().x,y:this.getHead().y};
switch(direction.toLowerCase()){
case "left":
snakeHead.y--;
this.going = "LEFT";
break;
case "right":
snakeHead.y++;
this.going = "RIGHT";
break;
case "up":
snakeHead.x--;
this.going = "UP";
break;
case "down":
snakeHead.x++;
this.going = "DOWN";
break;
}
let newBlock =
generateBlock(snakeHead.x,snakeHead.y,
this.gameInstance.boardSizeX,this.gameInstance.boardSizeY);
if (this.posIsApple(newBlock)) {
this.gameInstance.score++;
this.gameInstance.genApple = true;
} else {
this.removeBockTailFromSnake();
}
if (this.posIsTail(newBlock)){
this.gameInstance.ended = true;
}
this.addBlockHeadToSnake(newBlock);
};
this.body = startingBody || [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11}
];
this.gameInstance = forGame;
this.getHead = function(){
return this.body[this.body.length-1];
};
this.posIsTail = function(pos){
for (let i = 0; i<this.body.length;i++){
if (pos.x === this.body[i].x && pos.y === this.body[i].y) {
return true;
}
}
return false;
};
this.posIsApple = function(pos){
return pos.x === this.gameInstance.apple.x && pos.y === this.gameInstance.apple.y;
};
this.addBlockHeadToSnake = function(block){
this.body.push(block);
}
this.removeBockTailFromSnake = function(){
this.body.shift();
}
}
let serverListener = function(keyEvents){
console.log(keyEvents);
for (let i = 0; i<keyEvents.length;i++) {
var event = new Event('keydown');
event.key="Arrow" + capitalizeFirstLetter(keyEvents[i].toLowerCase());
document.dispatchEvent(event);
}
}
let SnakeGame = function(){
this.board = [];
this.snake = {};
this.apple = {};
this.score = 0;
this.speed = 500;
this.ended = false;
this.genApple = true;
this.boardSizeX = 20;
this.boardSizeY = 20;
this.manager = {};
}
SnakeGame.prototype.init = function(options){
options = options || {};
this.boardSizeX = options.boardSizeX || 20;
this.boardSizeY = options.boardSizeY || 20;
this.snake = options.snake || new Snake(this);
}
SnakeGame.prototype.setSnake = function(){
// sets snake to provided params
}
SnakeGame.prototype.generateBoard = function(){
this.board = [];
for (let i=0;i<this.boardSizeX;i++){
let boardRow=[];
for (let j = 0; j < this.boardSizeY; j++) {
let havePixel = false;
for (let k = 0; k<this.snake.body.length;k++){
if (this.snake.body[k].x === i && this.snake.body[k].y === j ){
havePixel = true;
}
}
if (havePixel) {
boardRow.push(1);
} else {
boardRow.push(0);
}
}
this.board.push(boardRow);
}
}
SnakeGame.prototype.setSpeed = function(speed){
this.speed = speed;
}
SnakeGame.prototype.setScore = function(score){
this.score = score;
}
let generateBlock = function(x,y,limitX,limitY){
let block = {};
if (x===limitX) {
block.x = 0;
} else if (x == -1) {
block.x = limitX-1;
} else {
block.x = x;
}
if (y===limitY) {
block.y = 0;
} else if (y == -1) {
block.y = limitY-1;
} else {
block.y = y;
}
return block;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let genericDiv = function(color){
let returnDiv = document.createElement("div");
returnDiv.style.height = "10px";
returnDiv.style.width = "10px";
returnDiv.style.background = color;
return returnDiv;
}
let snakeDiv = function(){
return genericDiv("lime");
}
let emptyDiv = function(){
return genericDiv("black");
}
let appleDiv = function(){
return genericDiv("red");
}
function updateDOM(game) {
var el = document.getElementById("gameboard");
el.innerHTML = "";
el.style.position = "relative";
var scoreEl = document.getElementById("score");
scoreEl.innerText = game.score;
if (game.genApple) {
generateAppleNoCollision(game);
}
for (let i =0;i<game.board.length;i++){
let snakeRowDiv = document.createElement("div");
//snakeRowDiv.style.position = "absolute";
for (let j=0;j<game.board[i].length;j++){
let whichDiv = null;
if (game.board[i][j]){
whichDiv = snakeDiv();
} else if (i==game.apple.x && j == game.apple.y){
whichDiv = appleDiv();
}
if (whichDiv == null){
whichDiv = emptyDiv();
}
whichDiv.style.position = "absolute";
whichDiv.style.left = j * (parseInt(whichDiv.style.width)) + "px";
whichDiv.style.top = (i * (parseInt(whichDiv.style.height)) + 100) + "px";
snakeRowDiv.appendChild(whichDiv);
}
el.appendChild(snakeRowDiv);
}
}
function generateDomListener(game){
return function(event){
switch (event.key) {
case "ArrowUp":
if (game.snake.going != "DOWN"){
game.snake.going = "UP";
}
break;
case "ArrowDown":
if (game.snake.going != "UP"){
game.snake.going = "DOWN";
}
break;
case "ArrowLeft":
if (game.snake.going != "RIGHT") {
game.snake.going = "LEFT";
}
break;
case "ArrowRight":
if (game.snake.going != "LEFT") {
game.snake.going = "RIGHT";
}
break;
}
}
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function decreaseDifficulty(game){
if (game.speed <= 900) {
game.speed += 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function restart(game){
game.ended = false;
game.genApple = true;
game.score = 0;
game.speed = 500;
game.apple = {x:null,y:null}
game.snake.body = [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11},
]
game.snake.going = "RIGHT";
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function generateAppleNoCollision(game){
while(true){
game.apple.x = getRandomInt(0,game.board.length-1);
game.apple.y = getRandomInt(0,game.board.length-1);
let hasCollision = false;
for (let i = 0; i<game.snake.body.length;i++){
if(game.apple.x === game.snake.body[i].x &&
game.apple.y === game.snake.body[i].y) {
hasCollision = true;
}
}
if (!hasCollision) {
console.log("no collision, continuing with this apple")
break;
}
console.error("found collision, searching once more")
}
game.genApple = false;
}
function increaseDifficulty(game){
if (game.speed >= 100) {
game.speed -= 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function gameLoop(game){
return function(){
if (!game.ended) {
game.snake.go(game.snake.going);
game.generateBoard();
updateDOM(game);
} else {
clearInterval(gameLoopHandle);
alert ("GAME OVER");
}
}
}
function polling(game){
return function(){
var scriptsDiv = document.getElementById("scripts");
var script = document.createElement('script');
script.src="http://172.168.1.22/snake_relay/?command=get&callbackname=serverListener";
if (game.scripts) {
if (game.scripts.length == 100){
let msg = "too many scripts, clearing the div";
scriptsDiv.innerHTML = ""
}
game.scripts.push(script);
} else {
game.scripts = [script];
}
scriptsDiv.appendChild(script);
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var game = new SnakeGame();
_game =game;
game.init();
game.generateBoard()
updateDOM(game);
document.addEventListener("keydown", generateDomListener(game));
//pollingHandle = setInterval(polling(game), 100);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
})
<div id="gameboard"></div>
<div>
<h1>Score: <span id="score">0</span></h1>
<button onclick="increaseDifficulty(_game)">Increase difficulty</button>
<button onclick="decreaseDifficulty(_game)">Decrease difficulty</button>
<button onclick="restart(_game)">Restart</button>
</div>
<div id="scripts"></div>

You can set border in genericDiv and pass the necessary values into snakeDiv.
let snakeDiv = function(){
return genericDiv("lime", "1px solid #000000");
}
You can set the border size to whichever size you need.
let _game;
var gameLoopHandle;
var pollingHandle;
let Snake = function(forGame,startingDirection, startingBody){
this.going = startingDirection || "RIGHT";
this.go = function(direction){
let snakeHead = {x:this.getHead().x,y:this.getHead().y};
switch(direction.toLowerCase()){
case "left":
snakeHead.y--;
this.going = "LEFT";
break;
case "right":
snakeHead.y++;
this.going = "RIGHT";
break;
case "up":
snakeHead.x--;
this.going = "UP";
break;
case "down":
snakeHead.x++;
this.going = "DOWN";
break;
}
let newBlock =
generateBlock(snakeHead.x,snakeHead.y,
this.gameInstance.boardSizeX,this.gameInstance.boardSizeY);
if (this.posIsApple(newBlock)) {
this.gameInstance.score++;
this.gameInstance.genApple = true;
} else {
this.removeBockTailFromSnake();
}
if (this.posIsTail(newBlock)){
this.gameInstance.ended = true;
}
this.addBlockHeadToSnake(newBlock);
};
this.body = startingBody || [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11}
];
this.gameInstance = forGame;
this.getHead = function(){
return this.body[this.body.length-1];
};
this.posIsTail = function(pos){
for (let i = 0; i<this.body.length;i++){
if (pos.x === this.body[i].x && pos.y === this.body[i].y) {
return true;
}
}
return false;
};
this.posIsApple = function(pos){
return pos.x === this.gameInstance.apple.x && pos.y === this.gameInstance.apple.y;
};
this.addBlockHeadToSnake = function(block){
this.body.push(block);
}
this.removeBockTailFromSnake = function(){
this.body.shift();
}
}
let serverListener = function(keyEvents){
console.log(keyEvents);
for (let i = 0; i<keyEvents.length;i++) {
var event = new Event('keydown');
event.key="Arrow" + capitalizeFirstLetter(keyEvents[i].toLowerCase());
document.dispatchEvent(event);
}
}
let SnakeGame = function(){
this.board = [];
this.snake = {};
this.apple = {};
this.score = 0;
this.speed = 500;
this.ended = false;
this.genApple = true;
this.boardSizeX = 20;
this.boardSizeY = 20;
this.manager = {};
}
SnakeGame.prototype.init = function(options){
options = options || {};
this.boardSizeX = options.boardSizeX || 20;
this.boardSizeY = options.boardSizeY || 20;
this.snake = options.snake || new Snake(this);
}
SnakeGame.prototype.setSnake = function(){
// sets snake to provided params
}
SnakeGame.prototype.generateBoard = function(){
this.board = [];
for (let i=0;i<this.boardSizeX;i++){
let boardRow=[];
for (let j = 0; j < this.boardSizeY; j++) {
let havePixel = false;
for (let k = 0; k<this.snake.body.length;k++){
if (this.snake.body[k].x === i && this.snake.body[k].y === j ){
havePixel = true;
}
}
if (havePixel) {
boardRow.push(1);
} else {
boardRow.push(0);
}
}
this.board.push(boardRow);
}
}
SnakeGame.prototype.setSpeed = function(speed){
this.speed = speed;
}
SnakeGame.prototype.setScore = function(score){
this.score = score;
}
let generateBlock = function(x,y,limitX,limitY){
let block = {};
if (x===limitX) {
block.x = 0;
} else if (x == -1) {
block.x = limitX-1;
} else {
block.x = x;
}
if (y===limitY) {
block.y = 0;
} else if (y == -1) {
block.y = limitY-1;
} else {
block.y = y;
}
return block;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let genericDiv = function(color, border){
let returnDiv = document.createElement("div");
returnDiv.style.height = "10px";
returnDiv.style.width = "10px";
returnDiv.style.background = color;
returnDiv.style.border = border;
return returnDiv;
}
let snakeDiv = function(){
return genericDiv("lime", "1px solid #000000");
}
let emptyDiv = function(){
return genericDiv("black");
}
let appleDiv = function(){
return genericDiv("red");
}
function updateDOM(game) {
var el = document.getElementById("gameboard");
el.innerHTML = "";
el.style.position = "relative";
var scoreEl = document.getElementById("score");
scoreEl.innerText = game.score;
if (game.genApple) {
generateAppleNoCollision(game);
}
for (let i =0;i<game.board.length;i++){
let snakeRowDiv = document.createElement("div");
//snakeRowDiv.style.position = "absolute";
for (let j=0;j<game.board[i].length;j++){
let whichDiv = null;
if (game.board[i][j]){
whichDiv = snakeDiv();
} else if (i==game.apple.x && j == game.apple.y){
whichDiv = appleDiv();
}
if (whichDiv == null){
whichDiv = emptyDiv();
}
whichDiv.style.position = "absolute";
whichDiv.style.left = j * (parseInt(whichDiv.style.width)) + "px";
whichDiv.style.top = (i * (parseInt(whichDiv.style.height)) + 100) + "px";
snakeRowDiv.appendChild(whichDiv);
}
el.appendChild(snakeRowDiv);
}
}
function generateDomListener(game){
return function(event){
switch (event.key) {
case "ArrowUp":
if (game.snake.going != "DOWN"){
game.snake.going = "UP";
}
break;
case "ArrowDown":
if (game.snake.going != "UP"){
game.snake.going = "DOWN";
}
break;
case "ArrowLeft":
if (game.snake.going != "RIGHT") {
game.snake.going = "LEFT";
}
break;
case "ArrowRight":
if (game.snake.going != "LEFT") {
game.snake.going = "RIGHT";
}
break;
}
}
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function decreaseDifficulty(game){
if (game.speed <= 900) {
game.speed += 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function restart(game){
game.ended = false;
game.genApple = true;
game.score = 0;
game.speed = 500;
game.apple = {x:null,y:null}
game.snake.body = [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11},
]
game.snake.going = "RIGHT";
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function generateAppleNoCollision(game){
while(true){
game.apple.x = getRandomInt(0,game.board.length-1);
game.apple.y = getRandomInt(0,game.board.length-1);
let hasCollision = false;
for (let i = 0; i<game.snake.body.length;i++){
if(game.apple.x === game.snake.body[i].x &&
game.apple.y === game.snake.body[i].y) {
hasCollision = true;
}
}
if (!hasCollision) {
console.log("no collision, continuing with this apple")
break;
}
console.error("found collision, searching once more")
}
game.genApple = false;
}
function increaseDifficulty(game){
if (game.speed >= 100) {
game.speed -= 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function gameLoop(game){
return function(){
if (!game.ended) {
game.snake.go(game.snake.going);
game.generateBoard();
updateDOM(game);
} else {
clearInterval(gameLoopHandle);
alert ("GAME OVER");
}
}
}
function polling(game){
return function(){
var scriptsDiv = document.getElementById("scripts");
var script = document.createElement('script');
script.src="http://172.168.1.22/snake_relay/?command=get&callbackname=serverListener";
if (game.scripts) {
if (game.scripts.length == 100){
let msg = "too many scripts, clearing the div";
scriptsDiv.innerHTML = ""
}
game.scripts.push(script);
} else {
game.scripts = [script];
}
scriptsDiv.appendChild(script);
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var game = new SnakeGame();
_game =game;
game.init();
game.generateBoard()
updateDOM(game);
document.addEventListener("keydown", generateDomListener(game));
//pollingHandle = setInterval(polling(game), 100);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
})
<div id="gameboard"></div>
<div>
<h1>Score: <span id="score">0</span></h1>
<button onclick="increaseDifficulty(_game)">Increase difficulty</button>
<button onclick="decreaseDifficulty(_game)">Decrease difficulty</button>
<button onclick="restart(_game)">Restart</button>
</div>
<div id="scripts"></div>

You need to do the following
css:
#gameboard > div > div {
box-sizing: border-box;
}
And update snakeDiv as follows:
// pass extra parameter to track the snake blocks
let snakeDiv = function(){
return genericDiv("lime", 'snake');
}
// depending on the extra parameter add extra css property to snake blocks only
let genericDiv = function(color, snake){
let returnDiv = document.createElement("div");
returnDiv.style.height = "10px";
returnDiv.style.width = "10px";
returnDiv.style.background = color;
if(snake){
returnDiv.style.borderWidth = "1px";
returnDiv.style.borderColor = "black";
returnDiv.style.borderStyle = "solid";
}
return returnDiv;
}
Working fiddle:
let _game;
var gameLoopHandle;
var pollingHandle;
let Snake = function(forGame,startingDirection, startingBody){
this.going = startingDirection || "RIGHT";
this.go = function(direction){
let snakeHead = {x:this.getHead().x,y:this.getHead().y};
switch(direction.toLowerCase()){
case "left":
snakeHead.y--;
this.going = "LEFT";
break;
case "right":
snakeHead.y++;
this.going = "RIGHT";
break;
case "up":
snakeHead.x--;
this.going = "UP";
break;
case "down":
snakeHead.x++;
this.going = "DOWN";
break;
}
let newBlock =
generateBlock(snakeHead.x,snakeHead.y,
this.gameInstance.boardSizeX,this.gameInstance.boardSizeY);
if (this.posIsApple(newBlock)) {
this.gameInstance.score++;
this.gameInstance.genApple = true;
} else {
this.removeBockTailFromSnake();
}
if (this.posIsTail(newBlock)){
this.gameInstance.ended = true;
}
this.addBlockHeadToSnake(newBlock);
};
this.body = startingBody || [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11}
];
this.gameInstance = forGame;
this.getHead = function(){
return this.body[this.body.length-1];
};
this.posIsTail = function(pos){
for (let i = 0; i<this.body.length;i++){
if (pos.x === this.body[i].x && pos.y === this.body[i].y) {
return true;
}
}
return false;
};
this.posIsApple = function(pos){
return pos.x === this.gameInstance.apple.x && pos.y === this.gameInstance.apple.y;
};
this.addBlockHeadToSnake = function(block){
this.body.push(block);
}
this.removeBockTailFromSnake = function(){
this.body.shift();
}
}
let serverListener = function(keyEvents){
console.log(keyEvents);
for (let i = 0; i<keyEvents.length;i++) {
var event = new Event('keydown');
event.key="Arrow" + capitalizeFirstLetter(keyEvents[i].toLowerCase());
document.dispatchEvent(event);
}
}
let SnakeGame = function(){
this.board = [];
this.snake = {};
this.apple = {};
this.score = 0;
this.speed = 500;
this.ended = false;
this.genApple = true;
this.boardSizeX = 20;
this.boardSizeY = 20;
this.manager = {};
}
SnakeGame.prototype.init = function(options){
options = options || {};
this.boardSizeX = options.boardSizeX || 20;
this.boardSizeY = options.boardSizeY || 20;
this.snake = options.snake || new Snake(this);
}
SnakeGame.prototype.setSnake = function(){
// sets snake to provided params
}
SnakeGame.prototype.generateBoard = function(){
this.board = [];
for (let i=0;i<this.boardSizeX;i++){
let boardRow=[];
for (let j = 0; j < this.boardSizeY; j++) {
let havePixel = false;
for (let k = 0; k<this.snake.body.length;k++){
if (this.snake.body[k].x === i && this.snake.body[k].y === j ){
havePixel = true;
}
}
if (havePixel) {
boardRow.push(1);
} else {
boardRow.push(0);
}
}
this.board.push(boardRow);
}
}
SnakeGame.prototype.setSpeed = function(speed){
this.speed = speed;
}
SnakeGame.prototype.setScore = function(score){
this.score = score;
}
let generateBlock = function(x,y,limitX,limitY){
let block = {};
if (x===limitX) {
block.x = 0;
} else if (x == -1) {
block.x = limitX-1;
} else {
block.x = x;
}
if (y===limitY) {
block.y = 0;
} else if (y == -1) {
block.y = limitY-1;
} else {
block.y = y;
}
return block;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let genericDiv = function(color, border){
let returnDiv = document.createElement("div");
returnDiv.style.height = "10px";
returnDiv.style.width = "10px";
returnDiv.style.background = color;
if(border){
returnDiv.style.borderWidth = "1px";
returnDiv.style.borderColor = "black";
returnDiv.style.borderStyle = "solid";
}
//returnDiv.style.border = border;
return returnDiv;
}
let snakeDiv = function(){
return genericDiv("lime", "1px solid #000000");
}
let emptyDiv = function(){
return genericDiv("black");
}
let appleDiv = function(){
return genericDiv("red");
}
function updateDOM(game) {
var el = document.getElementById("gameboard");
el.innerHTML = "";
el.style.position = "relative";
var scoreEl = document.getElementById("score");
scoreEl.innerText = game.score;
if (game.genApple) {
generateAppleNoCollision(game);
}
for (let i =0;i<game.board.length;i++){
let snakeRowDiv = document.createElement("div");
//snakeRowDiv.style.position = "absolute";
for (let j=0;j<game.board[i].length;j++){
let whichDiv = null;
if (game.board[i][j]){
whichDiv = snakeDiv();
} else if (i==game.apple.x && j == game.apple.y){
whichDiv = appleDiv();
}
if (whichDiv == null){
whichDiv = emptyDiv();
}
whichDiv.style.position = "absolute";
whichDiv.style.left = j * (parseInt(whichDiv.style.width)) + "px";
whichDiv.style.top = (i * (parseInt(whichDiv.style.height)) + 100) + "px";
snakeRowDiv.appendChild(whichDiv);
}
el.appendChild(snakeRowDiv);
}
}
function generateDomListener(game){
return function(event){
switch (event.key) {
case "ArrowUp":
if (game.snake.going != "DOWN"){
game.snake.going = "UP";
}
break;
case "ArrowDown":
if (game.snake.going != "UP"){
game.snake.going = "DOWN";
}
break;
case "ArrowLeft":
if (game.snake.going != "RIGHT") {
game.snake.going = "LEFT";
}
break;
case "ArrowRight":
if (game.snake.going != "LEFT") {
game.snake.going = "RIGHT";
}
break;
}
}
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function decreaseDifficulty(game){
if (game.speed <= 900) {
game.speed += 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function restart(game){
game.ended = false;
game.genApple = true;
game.score = 0;
game.speed = 500;
game.apple = {x:null,y:null}
game.snake.body = [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11},
]
game.snake.going = "RIGHT";
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function generateAppleNoCollision(game){
while(true){
game.apple.x = getRandomInt(0,game.board.length-1);
game.apple.y = getRandomInt(0,game.board.length-1);
let hasCollision = false;
for (let i = 0; i<game.snake.body.length;i++){
if(game.apple.x === game.snake.body[i].x &&
game.apple.y === game.snake.body[i].y) {
hasCollision = true;
}
}
if (!hasCollision) {
console.log("no collision, continuing with this apple")
break;
}
console.error("found collision, searching once more")
}
game.genApple = false;
}
function increaseDifficulty(game){
if (game.speed >= 100) {
game.speed -= 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function gameLoop(game){
return function(){
if (!game.ended) {
game.snake.go(game.snake.going);
game.generateBoard();
updateDOM(game);
} else {
clearInterval(gameLoopHandle);
alert ("GAME OVER");
}
}
}
function polling(game){
return function(){
var scriptsDiv = document.getElementById("scripts");
var script = document.createElement('script');
script.src="http://172.168.1.22/snake_relay/?command=get&callbackname=serverListener";
if (game.scripts) {
if (game.scripts.length == 100){
let msg = "too many scripts, clearing the div";
scriptsDiv.innerHTML = ""
}
game.scripts.push(script);
} else {
game.scripts = [script];
}
scriptsDiv.appendChild(script);
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var game = new SnakeGame();
_game =game;
game.init();
game.generateBoard()
updateDOM(game);
document.addEventListener("keydown", generateDomListener(game));
//pollingHandle = setInterval(polling(game), 100);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
})
<div id="gameboard"></div>
<div>
<h1>Score: <span id="score">0</span></h1>
<button onclick="increaseDifficulty(_game)">Increase difficulty</button>
<button onclick="decreaseDifficulty(_game)">Decrease difficulty</button>
<button onclick="restart(_game)">Restart</button>
</div>
<div id="scripts"></div>
<style>
#gameboard > div > div {
box-sizing: border-box;
}
</style>

Related

Javascript: Global Variables Aren't Defined In Other Functions

I have three variables that I need to put in the innerHTML of four spans. The variables I use are seconds, accurateclick, and inaccurateclick. The process I use to get these variables is fine. The problem is I can't figure out how to bring them over to another function. I will make a replica of what I have. This will be a simpler version.
var x;
var y;
var z;
function A(){
x = 1;
y = 2;
z = 3;
B();
}
function B(){
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
}
What would happen is, instead of a being equal to 1, b being equal to 2, and c being equal to 3, they would all equal to undefined. I don't know why that is happening when x, y, and z are global variables. I thought they should change when set to a different value.
Here is my actual code:
var seconds;
var accurateclicks;
var inaccurateclicks;
var windowheight = window.innerHeight;
var windowwidth = window.innerWidth;
var colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"];
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
function BeginGameLoad(){
var BottomLabel1 = document.getElementById("bl1");
var BeginGameContainer = document.getElementById("BGC1");
var RightClick = false;
BottomLabel1.addEventListener("mousedown", BL1MD);
BottomLabel1.addEventListener("mouseup", BL1MU);
BottomLabel1.style.cursor = "pointer";
window.addEventListener("resize", BeginGameResize);
window.addEventListener("contextmenu", BeginGameContextMenu);
function BeginGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL1MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel1.style.color = randomcolor;
RightClick = false;
}
}
function BL1MU(){
if(RightClick == false){
window.location.href = "Game.html";
GameLoad();
}
else{
RightClick = false;
}
}
if(windowheight < 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
BeginGameContainer.style.width = "800px";
}
function BeginGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
BeginGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
BeginGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
BeginGameContainer.style.width = "100%";
}
}
}
function GameLoad(){
var LeftPanel2 = document.getElementById("lp2");
var LeftColorPanel2 = document.getElementById("lcp2");
var TopPanel2 = document.getElementById("tp2");
var TopLabel2 = document.getElementById("tl2");
var RightPanel2 = document.getElementById("rp2")
var RightLabel2 = document.getElementById("rl2");
var GameContainer = document.getElementById("GC2");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var clickedRightName = false;
var clickedRightColor = false;
var clickedRightNameColor = false;
var RightClick = false;
var ClickedLeftColorPanel = false;
var ClickedRightLabel = false;
var ClickedTopLabel = false;
var Timer;
TopPanel2.addEventListener("mouseup", TP2MU);
TopLabel2.addEventListener("mousedown", TL2MD);
TopLabel2.addEventListener("mouseup", TL2MU);
TopLabel2.style.cursor = "pointer";
LeftPanel2.addEventListener("mouseup", LP2MU);
LeftColorPanel2.addEventListener("mouseup", LCP2MU);
LeftColorPanel2.addEventListener("mousedown", LCP2MD);
LeftColorPanel2.style.cursor = "pointer";
RightPanel2.addEventListener("mouseup", RP2MU);
RightLabel2.addEventListener("mouseup", RL2MU);
RightLabel2.addEventListener("mousedown", RL2MD);
RightLabel2.style.cursor = "pointer";
window.addEventListener("resize", GameResize);
window.addEventListener("contextmenu", GameContextMenu);
function AddSeconds(){
seconds++;
}
function GameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function TL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true){
TopLabel2.style.color = randomcolor;
RightClick = false;
}
}
function TP2MU(){
if(ClickedTopLabel == false){
inaccurateclicks++;
}
else{
ClickedTopLabel = false;
}
}
function TL2MU(){
ClickedTopLabel = true;
if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
accurateclicks++;
window.location.href = "EndGame.html";
EndGameLoad();
}
else if (!clickedRightName == true && !clickedRightColor == true && !clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
Timer = setInterval(AddSeconds, 1000);
seconds = 0;
accurateclicks = 0;
inaccurateclicks = 0;
TopLabel2.innerHTML = randomcolor;
RightClick = false;
}
else{
inaccurateclicks++;
}
RightClick == false
}
function LCP2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function LCP2MU(){
ClickedLeftColorPanel = true;
if(clickedRightColor == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == LeftColorPanel2.style.backgroundColor){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.color){
LeftColorPanel2.style.backgroundColorr = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.backgroundColor){
LeftColorPanel2.style.backgroundColor = randomcolor2;
accurateclicks++;
}
if (LeftColorPanel2.style.backgroundColor == randomcolor.toLowerCase()){
clickedRightColor = true;
LeftColorPanel2.style.cursor = "auto";
}
randomcolor2 = null;
RightClick = false;
}
else if(clickedRightColor == true && RightClick == false){
inaccurateclicks++;
}
}
function LP2MU(){
if(ClickedLeftColorPanel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
function RL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function RL2MU(){
ClickedRightLabel = true;
if(clickedRightName == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2 == RightLabel2.innerHTML){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2 != RightLabel2.innerHTML){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2 != RightLabel2.color){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
}
if (RightLabel2.innerHTML == randomcolor){
clickedRightName = true;
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == false && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == RightLabel2.style.color){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
}
if (RightLabel2.style.color == randomcolor.toLowerCase()){
clickedRightNameColor = true;
RightLabel2.style.cursor = "auto";
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == true && RightClick == false){
inaccurateclicks++;
}
}
function RP2MU(){
if(ClickedRightLabel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
if(windowheight < 600)
{
GameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
GameContainer.style.width = "800px";
}
function GameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
GameContainer.style.height = "600px";
}
if(windowheight > 600)
{
GameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
GameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
GameContainer.style.width = "100%";
}
}
}
function EndGameLoad(){
var BottomLabel3 = document.getElementById("bl3");
var EndGameContainer = document.getElementById("EGC3");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var RightClick = false;
BottomLabel3.addEventListener("mousedown", BL3MD);
BottomLabel3.addEventListener("mouseup", BL3MU);
BottomLabel3.style.cursor = "pointer";
window.addEventListener("resize", EndGameResize);
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
window.addEventListener("contextmenu", EndGameContextMenu);
function EndGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL3MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true
}
else{
randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel3.style.color = randomcolor;
RightClick = false;
}
}
function BL3MU(){
if(RightClick == false){
MiddleLabelTwo.innerHTML = "Time (Seconds): "
MiddleLabelThree.innerHTML = "Accurate Clicks: "
MiddleLabelFour.innerHTML = "Inaccurate Clicks: "
MiddleLabelFive.innerHTML = "Score: "
window.location.href = "Game.html";
}
}
if(windowheight < 600)
{
EndGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
EndGameContainer.style.width = "800px";
}
function EndGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
EndGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
EndGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
EndGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
EndGameContainer.style.width = "100%";
}
}
}
Whenever I run it, it works up to this point
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
It says seconds, accurateclicks, and inaccurateclicks are all undefined. I don't know why this would happen given that they were defined in the previous function [Game()].
try writing,
x = 1;
y = 2;
z = 3;
function A() {
B();
}
function B() {
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
console.log(a, b, c, d);
}
A();
Reason: 'var' defines variables locally!
You did make two html files and this caused the js file to reload. This is why the global variables are declared again and are renewed to undefined.The solution is to work with one html file and to only reload the body.
My syntax was right, but as #Julie mentioned, the variables were being reloaded. How to get JS variable to retain value after page refresh? this helped me solve my problem.

how to programming the code in Xcalc.js

function Operator(input) {
this.operator = input;
if (!input) {
console.log("Operator has no input.");
}
this.solve = function(segment1, segment2, x) {
var v1 = segment1.coefficient;
if (segment1.type=="variable") {
v1 = x;
}
var v2 = segment2.coefficient;
if (segment2.type=="variable") {
v2 = x;
}
if (this.operator=="+") {
return new Segment(v1 + v2);
} else if (this.operator=="-") {
return new Segment(v1 - v2);
} else if (this.operator=="*") {
return new Segment(v1 * v2);
} else if (this.operator=="/") {
return new Segment(v1 / v2);
} else if (this.operator=="^") {
return new Segment(Math.pow(v1, v2));
}
};
}//Class for special functions
function MathFunction(input) {
this.f=input;
if (!input) {
console.log("Math function has no input.");
}
this.solve = function(segment) {
var v = segment.coefficient;
if (this.f=="sin") {
return new Segment(Math.sin(v));
} else if (this.f=="cos") {
return new Segment(Math.cos(v));
} else if (this.f=="tan") {
return new Segment(Math.tan(v));
} else if (this.f=="asin") {
return new Segment(Math.asin(v));
} else if (this.f=="acos") {
return new Segment(Math.acos(v));
} else if (this.f=="atan") {
return new Segment(Math.atan(v));
} else if (this.f=="abs") {
return new Segment(Math.abs(v));
}
};
}
//Class for a segment of math (a container)
function Segment(input) {
this.sections = [];
this.type="section";
this.operator=0;
this.coefficient=0;
this.mathFunction=0;
this.variable="";
var removeBrackets = function(value) {
if (!value) return "";
//While there are brackets around the string
while (value.substr(0, 1)=="(" && value.substr(value.length-1, 1)==")") { var openBrackets=1;
//See if the end bracket closes the opening bracket or not
for (var i=1; i<value.length&&openBrackets>0; i++) {
if (value.substr(i, 1)=="(") openBrackets++;
if (value.substr(i, 1)==")") openBrackets--;
}
i-=1;
//If it corresponds to different brackets, do nothing
if (openBrackets!==0 || i!=value.length-1) {
break
pue.substr(i, 1)=="(") {
openBrackets++;
} else if (value.substr(i, 1)==")") {
openBrackets--;
}
if (i==index) {
//If no brackets are open (and if the operator is actually - and not just a minus sign), break the loop.
var r=0;
if (trig=="sin") {
r=/(a)?sin/g;
} else if (trig=="cos") {
r=/(a)?cos/g;
} else if (trig=="tan") {
r=/(a)?tan/g;
} else {
return -1;
}
for (matches=r.exec(value); matches; matches=r.exec(value)) if (RegExp.$1 != "a") index=matches.index;
var inBrackets=true;
while (inBrackets && index!=-1) {
var openBrackets=0;
//Find how many brackets are opened or closed at a given point in the string
for (var i=0; i<value.length; i++) {
if (value.substr(i, 1)=="(") {
openBrackets++;
} else if (value.substr(i, 1)==")") {
openBrackets--;
}
if (i==index) {
//If no brackets are open (and if the operator is actually - and not just a minus sign), break the loop.
if (openBrackets===0) {
inBrackets=false;
break;
}
}
str+="<div class='answer'>= " + this.solve().coefficient + "</div>";
str+="</div>";
return str;
};
//constructor
if (input!==undefined) {
if (typeof(input)=="string") {
//Remove excess whitespace
input = input.replace(/\s/g, "");
//get rid of unnecessary brackets surrounding the section
input = removeBrackets(input);
//Find the last instance of each operator in the string
var addition = findLast("+", input);
var subtraction = findLast("-", input);
var division = findLast("/", input);
var exponent = findLast("^", input); //Find the first exponent, since those work in reverse
var bracket1 = findLast("(", input);
var sin = findLastTrig("sin", input);
var cos = findLastTrig("cos", input);
var tan = findLastTrig("tan", input);
var asin = findLast("asin", input);
var acos = findLast("acos", input);
var atan = findLast("atan", input);
var abs = findLast("abs", input);
var multiplication = findLast("*", input);
var multiplication2 = findMultiplicationBrackets(input); //Find brackets that are the same as multiplication
var functionMultiplication = -1;
if (sin>multiplication) functionMultiplication=sin;
if (cos>multiplication) functionMultiplication=cos;
if (tan>multiplication) functionMultiplication=tan;
if (asin>multiplication) functionMultiplication=asin;
if (acos>multiplication) functionMultiplication=acos;
if (atan>multiplication) functionMultiplication=atan;
if (abs>multiplication) functionMultiplication=abs;
//Push back each half of the equation into a section, in reverse order of operations
if (addition != -1 && (subtraction == -1 || addition>subtraction)) {
this.sections.push(new Segment(input.substring(0, addition)));
this.sections.push(new Segment(input.substring(addition+1)));
this.operator = new Operator("+");
} else if (subtraction != -1) {
if (subtraction>0) {
this.sections.push(new Segment(input.substring(0, subtraction)));
} else {
this.sections.push(new Segment(0));
}
this.sections.push(new Segment(input.substring(subtraction+1)));
this.operator = new Operator("-");
} else if (functionMultiplication >0 && functionMultiplication > multiplication && functionMultiplication > division) {
this.sections.push(new Segment(input.substring(0, functionMultiplication)));
this.sections.push(new Segment(input.substring(functionMultiplication)));
this.operator = new Operator("*");
} else if (multiplication2 != -1 && (division == -1 || multiplication>division) && (multiplication == -1 || multiplication2>multiplication)) {
this.sections.push(new Segment(input.substring(0, multiplication2)));
this.sections.push(new Segment(input.substring(multiplication2)));
this.operator = new Operator("*");
} else if (multiplication != -1 && (division == -1 || multiplication>division)) {
this.sections.push(new Segment(input.substring(0, multiplication)));
this.sections.push(new Segment(input.substring(multiplication+1)));
this.operator = new Operator("*");
} else if (division != -1) {
this.sections.push(new Segment(input.substring(0, division)));
this.sections.push(new Segment(input.substring(division+1)));
this.operator = new Operator("/");
} else if (exponent != -1) {
this.sections.push(new Segment(input.substring(0, exponent)));
this.sections.push(new Segment(input.substring(exponent+1)));
this.operator = new Operator("^");
} else if (sin != -1 && (cos == -1 || sin>cos) && (tan == -1 || sin>tan) && (asin == -1 || sin>asin) && (acos == -1 || sin>acos) && (atan == -1 || sin>atan) && (abs == -1 || sin>abs)) {
this.sections.push(new Segment(input.substring(sin+3)));
this.mathFunction = new MathFunction("sin");
this.type = "function";
} else if (cos != -1 && (tan == -1 || cos>tan) && (asin == -1 || cos>asin) && (acos == -1 || cos>acos) && (atan == -1 || cos>atan) && (abs == -1 || cos>abs)) {
this.sections.push(new Segment(input.substring(cos+3)));
this.mathFunction = new MathFunction("cos");
this.type = "function";
} else if (tan != -1 && (asin == -1 || tan>asin) && (acos == -1 || tan>acos) && (atan == -1 || tan>atan) && (abs == -1 || tan>abs)) {
this.sections.push(new Segment(input.substring(tan+3)));
this.mathFunction = new MathFunction("tan");
this.type = "function";
} else if (asin != -1 && (acos == -1 || asin>acos) && (atan == -1 || asin>atan) && (abs == -1 || asin>abs)) {
this.sections.push(new Segment(input.substring(asin+4)));
this.mathFunction = new MathFunction("asin");
this.type = "function";
} else if (acos != -1 && (atan == -1 || acos>atan) && (abs == -1 || acos>abs)) {
this.sections.push(new Segment(input.substring(acos+4)));
this.mathFunction = new MathFunction("acos");
this.type = "function";
} else if (atan != -1 && (abs == -1 || atan>abs)) {
this.sections.push(new Segment(input.substring(atan+4)));
this.mathFunction = new MathFunction("atan");
this.type = "function";
} else if (abs != -1) {
this.sections.push(new Segment(input.substring(abs+3)));
this.mathFunction = new MathFunction("abs");
this.type = "function";
} else if (bracket1 != -1) {
var openBrackets=1;
for (var i=bracket1+1; i<input.length&&openBrackets>0; i++) {
if (input.substr(i, 1)=="(") openBrackets++;
if (input.substr(i, 1)==")") openBrackets--;
}
if (openBrackets===0) {
var bracket2=i-1;
if (bracket1>0) this.sections.push(new Segment(input.substring(0, bracket1)));
if (bracket2-bracket1!=1) this.sections.push(new Segment(input.substring(bracket1+1, bracket2)));
if (bracket2!=input.length-1) this.sections.push(new Segment(input.substring(bracket2+1)));
this.operator = new Operator("*");
} else {
console.log("Brackets nesting error: " + input);
}
//If there are no operators, just push the input itself
} else {
var xLocation=input.toLowerCase().indexOf("x");
if (xLocation!=-1) {
if (xLocation>0) {
this.sections.push(new Segment(input.substring(0, xLocation)));
this.sections.push(new Segment("x"));
this.operator=new Operator("*");
} else {
this.variable="x";
this.type="variable";
}
} else {
this.coefficient = parseFloat(input);
this.type = "value";
}
}
} else if (typeof(input)=="number") {
this.coefficient = input;
this.type = "value";
}
} else {
console.log("Segment has no input.");
}
}
//One point on a graph
function Point(x, y) {
this.x = x || 0;
this.y = y || 0;
}
//MathFunction to create graphs
function Graph(value, width, height, rangeX, rangeY) {
var autoRange=false;
//Default params
if (rangeX===undefined) {
rangeX=10;
}
if (rangeY===undefined) {
autoRange = true;
}
//Properties
this.expression = new Segment(value);
this.points = [];
this.canvas = document.createElement("canvas");
this.canvas.width=width || 400;
this.canvas.height=height || 400;
this.min=undefined;
this.max=undefined;
this.x1 = 0-Math.abs(rangeX);
this.x2 = 0+Math.abs(rangeX);
this.y1 = 0-Math.abs(rangeY);
this.y2 = 0+Math.abs(rangeY);
var startMouse = new Point(0, 0);
var mousePos = new Point(0, 0);
var timer=0;
var stage=0;
var img=0;
var magnitudeX = 0;
var magnitudeY = 0;
//Gets minimum y value in the set of points
this.getMin = function() {
if (this.min===undefined) {
if (this.points.length>0) {
var min = this.points[0].y;
for (var i=1; i<this.points.length; i++) {
if (this.points[i].y<min) min = this.points[i].y;
}
this.min=min;
return min;
} else {
return 0;
}
} else {
return this.min;
}
};
//Gets maximum y value in the set of points
this.getMax = function() {
if (this.max===undefined) {
if (this.points.length>0) {
var max = this.points[0].y;
for (var i=1; i<this.points.length; i++) {
if (this.points[i].y>max) max = this.points[i].y;
}
this.max=max;
return max;
} else {
return 0;
}
} else {
return this.max;
}
};
//Updates the points and graph
this.update = function() {
var accuracy = (this.x2-this.x1)/this.canvas.width;
this.points = [];
for (var i=this.x1; i<=this.x2; i+=accuracy) {
this.points.push(new Point(i, this.expression.result(i)));
}
if (autoRange) {
if (this.getMax()-this.getMin()>100000) {
this.y1=-100;
this.y2=100;
} else {
this.y1=this.getMin()-5;
this.y2=this.getMax()+5;
}
autoRange = false;
}
magnitudeX = Math.ceil(Math.log(this.x2-this.x1));
magnitudeY = Math.ceil(Math.log(this.y2-this.y1));
this.redraw();
};
var drawAxes = function(_x1, _x2, _y1, _y2, redraw) {
stage.strokeStyle="#bdc3c7";
stage.fillStyle="#bdc3c7";
var limit=0;
var i=0;
//Draw the y axis if it is in the view
if (0>=_x1-30 && 0<=_x2+30) {
stage.lineWidth=2;
stage.beginPath();
stage.moveTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width, 0);
stage.lineTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width, this.canvas.height);
stage.closePath();
stage.stroke();
stage.textAlign = "right";
stage.textBaseline="middle";
stage.lineWidth=1;
limit = (Math.abs(_y2)>Math.abs(_y1))?Math.abs(_y2):Math.abs(_y1);
for (i=0; i<=limit; i+=Math.pow(10, Math.floor(Math.log(_y2-_y1) / Math.LN10))/4) {
if (i===0) continue;
if (i<=_y2+50) {
if (redraw || (i>=this.y2-50)) {
stage.beginPath();
stage.moveTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width-5, this.canvas.height-((i-_y1)/(_y2-_y1))*this.canvas.height);
stage.lineTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width+5, this.canvas.height-((i-_y1)/(_y2-_y1))*this.canvas.height);
stage.closePath();
stage.stroke();
stage.fillText(""+(Math.round(i*100)/100), this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width-8, this.canvas.height-((i-_y1)/(_y2-_y1))*this.canvas.height);
}
}
if (i>=_y1-50) {
if (redraw || (-i<=this.y1+50)) {
stage.beginPath();
stage.moveTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width-5, this.canvas.height-((-i-_y1)/(_y2-_y1))*this.canvas.height);
stage.lineTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width+5, this.canvas.height-((-i-_y1)/(_y2-_y1))*this.canvas.height);
stage.closePath();
stage.stroke();
stage.fillText(""+(Math.round(-i*100)/100), this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width-8, this.canvas.height-((-i-_y1)/(_y2-_y1))*this.canvas.height);
}
}
}
}
//Draw the x axis if it is in the view
if (0>=_y1-50 && 0<=_y2+50) {
stage.lineWidth=2;
stage.beginPath();
stage.moveTo(0, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height);
stage.lineTo(this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height);
stage.closePath();
stage.stroke();
stage.textAlign = "center";
stage.textBaseline="top";
stage.lineWidth=1;
limit = (Math.abs(_x2)>Math.abs(_x1))?Math.abs(_x2):Math.abs(_x1);
for (i=0; i<=limit; i+=Math.pow(10, Math.floor(Math.log(_x2-_x1) / Math.LN10))/4) {
if (i===0) continue;
if (i<=_x2+50) {
if (redraw || (i>=this.x2-50)) {
stage.beginPath();
stage.moveTo(((i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height-5);
stage.lineTo(((i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height+5);
stage.closePath();
stage.stroke();
stage.fillText(""+(Math.round(i*100)/100), ((i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height+8);
}
}
if (i>=_x1-50) {
if (redraw || (-i<=this.x1+50)) {
stage.beginPath();
stage.moveTo(((-i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height-5);
stage.lineTo(((-i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height+5);
stage.closePath();
stage.stroke();
stage.fillText(""+(Math.round(-i*100)/100), ((-i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height+8);
}
}
}
}
}.bind(this);
//Updates the canvas
this.redraw = function() {
if (this.points.length>1) {
stage.clearRect(0, 0, this.canvas.width, this.canvas.height);
stage.lineCap="round";
var offsetY = -this.y1;
drawAxes(this.x1, this.x2, this.y1, this.y2, true);
//Draw all the points
stage.strokeStyle="#2980b9";
stage.lineWidth=1;
stage.beginPath();
stage.moveTo(0, this.canvas.height-((this.points[0].y+offsetY)/(this.y2-this.y1))*this.canvas.height);
for (var i=1; i<this.points.length; i++) {
if (Math.abs((this.canvas.height-((this.points[i].y+offsetY)/(this.y2-this.y1))*this.canvas.height)-(this.canvas.height-((this.points[i-1].y+offsetY)/(this.y2-this.y1))*this.canvas.height))<=this.canvas.height) {
stage.lineTo((i/this.points.length)*this.canvas.width, this.canvas.height-((this.points[i].y+offsetY)/(this.y2-this.y1))*this.canvas.height);
}
stage.moveTo((i/this.points.length)*this.canvas.width, this.canvas.height-((this.points[i].y+offsetY)/(this.y2-this.y1))*this.canvas.height);
}
stage.closePath();
stage.stroke();
img = stage.getImageData(0, 0, this.canvas.width, this.canvas.height);
} else {
console.log("Not enough points to graph.");
}
};
this.setRange = function(_x1, _x2, _y1, _y2) {
this.x1=_x1;
this.x2=_x2;
this.y1=_y1;
this.y2=_y2;
this.update();
};
var getMousePos = function(evt) {
var rect = this.canvas.getBoundingClientRect();
var root = document.documentElement;
// return relative mouse position
var mouseX = evt.clientX - rect.left - root.scrollLeft;
var mouseY = evt.clientY - rect.top - root.scrollTop;
return new Point(mouseX, mouseY);
}.bind(this);
var startDrag = function(event) {
document.addEventListener("mousemove", dragMouse, false);
document.addEventListener("mouseup", endDrag, false);
this.canvas.removeEventListener("mouseover", startMouseOver, false);
this.canvas.removeEventListener("mousemove", moveMouse, false);
startMouse = getMousePos(event);
}.bind(this);
var redrawLine = function() {
var offsetX = ((mousePos.x-startMouse.x)/this.canvas.width)*(this.x2-this.x1);
var offsetY = ((mousePos.y-startMouse.y)/this.canvas.height)*(this.y2-this.y1);
this.setRange(this.x1-offsetX, this.x2-offsetX, this.y1+offsetY, this.y2+offsetY);
startMouse = mousePos;
}.bind(this);
var dragMouse = function(event) {
stage.clearRect(0, 0, this.canvas.width, this.canvas.height);
mousePos = getMousePos(event);
var newx1 = this.x1-((mousePos.x-startMouse.x)/this.canvas.width)*(this.x2-this.x1);
var newx2 = this.x2-((mousePos.x-startMouse.x)/this.canvas.width)*(this.x2-this.x1);
var newy1 = this.y1+((mousePos.y-startMouse.y)/this.canvas.height)*(this.y2-this.y1);
var newy2 = this.y2+((mousePos.y-startMouse.y)/this.canvas.height)*(this.y2-this.y1);
if (Math.abs(newx1-this.x1)>this.canvas.width/2 || Math.abs(newy1-this.y1)>this.canvas.height/2) {
redrawLine();
} else {
drawAxes(newx1, newx2, newy1, newy2, false);
stage.putImageData(img, mousePos.x-startMouse.x, mousePos.y-startMouse.y);
}
}.bind(this);
var endDrag = function(event) {
document.removeEventListener("mousemove", dragMouse, false);
document.removeEventListener("mouseup", endDrag, false);
this.canvas.addEventListener("mouseover", startMouseOver, false);
this.canvas.addEventListener("mousemove", moveMouse, false);
mousePos = getMousePos(event);
var offsetX = ((mousePos.x-startMouse.x)/this.canvas.width)*(this.x2-this.x1);
var offsetY = ((mousePos.y-startMouse.y)/this.canvas.height)*(this.y2-this.y1);
this.setRange(this.x1-offsetX, this.x2-offsetX, this.y1+offsetY, this.y2+offsetY);
}.bind(this);
var startMouseOver = function(event) {
this.canvas.addEventListener("mousemove", moveMouse, false);
this.canvas.addEventListener("mouseout", endMouseOver, false);
}.bind(this);
var moveMouse = function(event) {
stage.clearRect(0, 0, this.canvas.width, this.canvas.height);
stage.putImageData(img, 0, 0);
mousePos = getMousePos(event);
var offsetY = -this.y1;
//Draw the coordinate
stage.fillStyle="#2980b9";
stage.beginPath();
stage.arc(mousePos.x, this.canvas.height-((this.points[Math.round(mousePos.x/this.canvas.width*this.points.length)].y+offsetY)/(this.y2-this.y1))*this.canvas.height, 4, 0, 2*Math.PI);
stage.closePath();
stage.fill();
stage.fillStyle="#000";
stage.strokeStyle="#FFF";
stage.lineWidth=4;
stage.textBaseline="alphabetic";
var txt="(" + (Math.round(this.points[Math.round(mousePos.x/this.canvas.width*this.points.length)].x*100)/100).toFixed(2) + ", " + (Math.round(this.points[Math.round(mousePos.x/this.canvas.width*this.points.length)].y*100)/100).toFixed(2) + ")";
if (mousePos.x<stage.measureText(txt).width/2+2) {
stage.textAlign = "left";
} else if (mousePos.x>this.canvas.width-stage.measureText(txt).width/2-2) {
stage.textAlign = "right";
} else {
stage.textAlign = "center";
}
stage.strokeText(txt, mousePos.x, -10+this.canvas.height-((this.points[Math.round(mousePos.x/this.canvas.width*this.points.length)].y+offsetY)/(this.y2-this.y1))*this.canvas.height);
stage.fillText(txt, mousePos.x, -10+this.canvas.height-((this.points[Math.round(mousePos.x/this.canvas.width*this.points.length)].y+offsetY)/(this.y2-this.y1))*this.canvas.height);
}.bind(this);
var endMouseOver = function(event) {
this.canvas.removeEventListener("mousemove", moveMouse, false);
this.canvas.removeEventListener("mouseout", endMouseOver, false);
stage.clearRect(0, 0, this.canvas.width, this.canvas.height);
stage.putImageData(img, 0, 0);
}.bind(this);
//Returns the canvas element
this.getCanvas = function() {
return this.canvas;
};
//If canvas drawing is supported
if (this.canvas.getContext) {
//Get the canvas context to draw onto
stage = this.canvas.getContext("2d");
stage.font = "12px sans-serif";
this.canvas.style.backgroundColor="#FFF";
//Make points
this.update();
this.canvas.addEventListener("mousedown", startDrag, false);
this.canvas.addEventListener("mouseover", startMouseOver, false);
} else {
console.log("Canvas not supported in this browser.");
this.canvas = document.createElement("div");
this.canvas.innerHTML="Canvas is not supported in this browser.";
}
}
ntById("wrapper").className="";
var timer = setTimeout(function() {
var graph = XCalc.graphExpression(input, 400, 400);
document.getElementById("result").innerHTML = "";
document.getElementById("result").appendChild(graph.getCanvas());
document.getElementById("wrapper").className="solved";
}, 800);
} else {
document.getElementById("result").innerHTML = "<div class='error'>Error: Improperly nested brackets. Remember to only use round brackets and close all opened brackets.</div>";
}
}
window.onload = function() {
document.getElementById("simplify").addEventListener("click", simplifyText);
simplifyText();
};
<html>
<head>
<script src="exmath.js"></script>
</head>
<body>
<div id="top"><h1>Maths equation plotter</h1>
f(x) = <input type="text" value="(x+4)^2*(x-6)+60sinx" id="input" /><input type="button" value="Graph" id="simplify" />
</div>
<div id="wrapper">
<div id="result"></div>
</div>
</body>
</html>
I have some code in XCalc.js i want to support particular equation in(algebra equation,quadratic,linear,nonlinear equation) in based on equation how to programming in XCalc.js and how to show the steps based on equation so please help me to improve my code.refer this link:https://github.com/davepagurek/XCalc

snake game collision with itself

I have made a snake game with processign.js and im trying to make the collision with itself. The problem is that it isnt working as it should.
var screen = 0;
var bg = color(60,150,60);
var snake;
var apple;
var bonus;
var nBonus = 0;
var gameOver = false;
var appleSize = 10;
var applePosX = round(random(10,width-appleSize)/10)*10;
var applePosY = round(random(10,height-appleSize)/10)*10;
var keys = [];
void keyPressed() {
keys[keyCode] = true;
};
void keyReleased() {
keys[keyCode] = false;
};
frameRate(10);
// collision with itself
// -----------------------------------------------------------------------
// ------------------------------- THE SNAKE -----------------------------
var Snake = function(x, y) {
this.x = x;
this.y = y;
this.len = 1;
this.size = 10;
this.snakePosX = 0;
this.snakePosY = 0;
this.points = 0;
this.positions = [];
this.moving = false;
this.apples = 0;
for(var i=0; i<this.len; i++) {
var posX = this.x-i*10;
var posY = this.y;
this.positions[i] = {x:posX, y:posY};
}
};
Snake.prototype.draw = function() {
fill(0);
stroke(255,255,255);
for(var i=0; i<this.positions.length; i++) {
rect(this.positions[i].x, this.positions[i].y, this.size, this.size);
}
};
Snake.prototype.move = function() {
if(gameOver === false) {
if(keys[UP]) {
this.snakePosY = -this.size;
this.snakePosX = 0;
this.moving = true;
}
if(keys[DOWN]) {
this.snakePosY = this.size;
this.snakePosX = 0;
this.moving = true;
}
if(keys[LEFT]) {
this.snakePosX = -this.size;
this.snakePosY = 0;
this.moving = true;
}
if(keys[RIGHT]) {
this.snakePosX = this.size;
this.snakePosY = 0;
this.moving = true;
}
}
if(this.moving == true) {
if(snake.positions.length == 1) {
this.positions[0].x += this.snakePosX;
this.positions[0].y += this.snakePosY;
}
else {
for(var i=1; i<this.positions.length; i++) {
this.positions[i-1].x = this.positions[i].x;
this.positions[i-1].y = this.positions[i].y;
this.positions[i].x += this.snakePosX;
this.positions[i].y += this.snakePosY;
}
}
}
};
Snake.prototype.checkColl = function() {
// collision with itself
if(this.positions.length>1) {
for(var i=0; i<this.positions.length; i++) {
if(this.positions[0].x > 350) {
text('holly crap', 100, 100);
}
}
}
// collision with walls
if(this.positions[0].x > width-this.size || this.positions[0].x < 0 || this.positions[0].y > height-this.size || this.positions[0].y < 0) {
gameOver = true;
gameIsOver();
}
// collision with apples
for(var i=0; i<this.positions.length; i++) {
if(this.positions[i].x >= apple.x && this.positions[i].x+10 <= apple.x+10 && this.positions[i].y >= apple.y && this.positions[i].y+10 <= apple.y+10) {
apple.draw();
this.apples ++;
this.points += 10;
this.positions.unshift({x:apple.x, y:apple.y});
apple.x = round(random(10,width-appleSize)/10)*10;
apple.y = round(random(10,height-appleSize)/10)*10;
if(this.apples > 1 && this.apples % 5 == 0) {
nBonus = 1;
}
}
}
// collision with bonus
if(this.positions[0].x >= bonus.x && this.positions[0].x+10 <= bonus.x+10 && this.positions[0].y >= bonus.y && this.positions[0].y+10 <= bonus.y+10) {
if(this.moving) {
bonus.x = round(random(10,width-appleSize)/10)*10;
bonus.y = round(random(10,height-appleSize)/10)*10;
nBonus = 0;
this.points += 10;
}
}
};
// ------------------------ THE APPLES -----------------------------------
var Apple = function(x, y) {
this.x = x;
this.y = y;
};
Apple.prototype.draw = function() {
fill(255,0,0);
noStroke();
rect(this.x, this.y, appleSize, appleSize);
};
// ------------------------ THE BONUS -----------------------------------
var Bonus = function(x, y) {
this.x = x;
this.y = y;
}
Bonus.prototype.draw = function() {
fill(150,0,0);
stroke(255,255,255)
rect(this.x, this.y, appleSize, appleSize);
};
// -----------------------------------------------------------------------
snake = new Snake(width/2, height/2);
apple = new Apple(applePosX, applePosY);
bonus = new Bonus(width/2, height/2);
// -----------------------------------------------------------------------
void gameIsOver() {
fill(0);
textAlign(CENTER);
text("Game Over\nPress 'S' to play again", width/2, height/2);
textAlign(LEFT);
if(keys[83]) {
screen = 2;
gameOver = false;
}
}
void playGame() {
if(screen === 0) {
if(mouseX >= width/2-50 && mouseY <= width/2+50 && mouseY >= height/2-15 && mouseY <= height/2+15) {
if(mousePressed) {
screen = 1;
}
}
}
}
void makeScreen() {
if(screen === 0) {
textAlign(CENTER);
textSize(30);
text('SNAKE GAME', width/2, 100);
stroke(255,255,255);
noFill();
rectMode(CENTER);
rect(width/2, height/2, 100, 30);
textSize(15);
text('Play', width/2, height/2+5);
textSize(11);
text('By Eskimopest', width/2, height-20);
textAlign(LEFT);
rectMode(LEFT);
playGame();
}
if(screen === 1) {
snake.draw();
snake.move();
snake.checkColl();
apple.draw();
if(nBonus === 1) {
bonus.draw();
}
fill(0);
text('POINTS : '+ snake.points, 10, 20);
text('APPLES : '+ snake.apples, 10, 40);
}
if(screen === 2) {
snake.points = 0;
snake.apples = 0;
snake.x = width/2;
snake.y = height/2;
snake.len = 1;
snake.positions = [{x:snake.x, y:snake.y}];
snake.snakePosX = 0;
snake.snakePosY = 0;
applePosX = round(random(10,width-appleSize)/10)*10;
applePosY = round(random(10,height-appleSize)/10)*10;
screen = 1;
}
}
// -----------------------------------------------------------------------
void draw() {
background(bg);
makeScreen();
for(var i=0; i<snake.positions.length; i++) {
text(i + 'x:'+snake.positions[i].x + ' y:'+snake.positions[i].y, 600, 20+i*10);
}
}
The problem is in snake.prototype.checkColl and I'm trying to make this work but with no results. When I try to make
if(this.positions[0].x = this.positions[i].x)
nothing happens. If anyone could help me I would be very appreciated.
That should be:
if(this.positions[0].x == this.positions[i].x)
Using a single = is doing an assignment. You want to do a comparison, so you need double ==.

Image stops for a second while switching arrow keys

I have another question. When I move the main player image Left or Right it moves great except for when you are moving right and then you hurry and press the left key while the right key is still down, the image stops for a second and then it decides to move left. Vise-Versa.
Main.js
var getPlatF1POSX = 0;
var getPlatF1POSY = 0;
var addVar = 0;
var addVar2 = 0;
var addVar3 = 0;
function loadGame() {
document.getElementsByTagName("DIV")[4].style.visibility = "visible";
addEventListener('mousemove', getData, false);
addEventListener('keydown', movePlayer, false);
addEventListener('keyup', stopPlayer, false);
movePlat();
moveP();
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
}
function getData(gData) {
}
var thisThis = 1;
var moveBlock1 = 350;
var stLandT = 0;
var gPos = "";
var rightPos = false;
var leftPos = false;
function movePlat() {
}
function movePlayer(mPlayer) {
switch (mPlayer.keyCode) {
case 39: // RIGHT
if (stLandT == 0 && gPos == "" && rightPos == false) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
gPos = "RIGHT";
rightPos = true;
leftPos = false;
break;
case 37: // LEFT
if (stLandT == 0 && gPos == "" && leftPos == false) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
gPos = "LEFT";
rightPos = false;
leftPos = true;
break;
case 38: // UP
break;
case 40: // DOWN
break;
}
}
function stopPlayer(sPlayer) {
switch (sPlayer.keyCode) {
case 39:
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
gPos = "";
rightPos = false;
leftPos = false;
break;
case 37:
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
gPos = "";
rightPos = false;
leftPos = false;
break;
}
}
Move Land And Player
var cTAdd = 0;
var setThis = 1;
var GAPlayer = 3;
function landT() {
setThis = setTimeout(landT, 500);
if (xPos >= 500) {
cTAdd = Math.floor(Math.random() * 100 + 1);
var block00 = document.createElement("img");
if (cTAdd > 0 && cTAdd < 25) {
block00.src = "images/sep2.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block00.src = "images/sep1.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block00.src = "images/platform00.png";
}
document.getElementById("land01").appendChild(block00);
var block01 = document.createElement("img");
var getB = block01.getBoundingClientRect();
if (cTAdd > 0 && cTAdd < 25) {
block01.src = "images/platform00.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block01.src = "images/sep2.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block01.src = "images/sep1.png";
}
document.getElementById("land00").appendChild(block01);
GAPlayer = GAPlayer + 2;
}
}
var thisSet = 1;
var cPlayer = 0;
var moveSpeed = 5;
var xPos = 50;
var yPos = 300;
function moveLand() {
thisSet = setTimeout(moveLand, 30);
if (xPos >= 500) {
moveBlock1 = moveBlock1 - 10;
document.getElementById("land00").style.left = moveBlock1 + "px";
document.getElementById("land01").style.left = moveBlock1 + "px";
}
cPlayer++;
if (cPlayer >= 4)
cPlayer = 0;
document.images[GAPlayer].src = gPlayer[cPlayer].src;
}
function moveP() {
var setThis = setTimeout(moveP, 10);
if (leftPos == false) {
xPos = xPos + moveSpeed;
}
if (rightPos == false) {
xPos = xPos - moveSpeed;
}
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
if (xPos >= 500) {
xPos = 500;
}
if (xPos <= 50) {
xPos = 50;
}
}
This is because you stop your player no matter what key is up. You should store what key down is last pressed, than on key up you need to check if last key is released.
It was hard to me to debug your code, so I made it in jQuery (and had same troubles as you had):
var game = {
settings: {
moveSpeed: 5, // 5 milliseconds, 200fps
moveBy: 2 // 2 pixels
},
land: null,
landWidth: null,
landLeft: null,
viewport: null,
viewportWidth: null,
landMinLeft: null,
init: function() {
game.land = $('.land');
game.landWidth = game.land.width();
game.landLeft = game.land.position().left;
game.viewport = $('.viewport');
game.viewportWidth = game.viewport.width();
game.landMinLeft = -(game.landWidth-game.viewportWidth);
},
movingInterval: null,
lastKey: null,
keyDown: function (e) {
switch (e.keyCode) {
case 39: // RIGHT
game.lastKey = e.keyCode;
clearInterval( game.movingInterval );
game.movingInterval = setInterval( function() {
game.move('right');
}, game.settings.moveSpeed);
break;
case 37: // LEFT
game.lastKey = e.keyCode;
clearInterval( game.movingInterval );
game.movingInterval = setInterval( function() {
game.move('left');
}, game.settings.moveSpeed);
break;
}
},
keyUp: function(e) {
if( e.keyCode==game.lastKey ) {
game.stopMoving();
};
},
move: function( direction ) {
switch( direction ) {
case 'left':
var newLeft = game.land.position().left+game.settings.moveBy;
if( newLeft>0 ) newLeft=0;
game.land.css({
'left': newLeft+'px'
});
break;
case 'right':
var newLeft = game.land.position().left-game.settings.moveBy;
if( newLeft<game.landMinLeft ) newLeft=game.landMinLeft;
game.land.css({
'left': newLeft+'px'
});
break;
};
},
stopMoving: function() {
clearInterval( game.movingInterval );
}
};
game.init();
$(window).on('keydown', game.keyDown);
$(window).on('keyup', game.keyUp);
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body, html, .viewport {
width: 100%;
height: 100%;
}
.viewport {
position: relative;
overflow: hidden;
}
.land {
position: absolute;
left: 0;
top: 0;
width: 2300px;
height: 200px;
background: url('//dummyimage.com/2300x400/000/fff&text=Mario+is+great!+Mario+is+our+hero!+We+love+you+mario!') no-repeat center center;
background-size: cover;
will-change: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="viewport">
<div class="land"></div>
</div>
Also on Playground.
This is how you do it in Javascript/HTML5
theGame.js
var getPlatF1POSX = 0;
var getPlatF1POSY = 0;
var addVar = 0;
var addVar2 = 0;
var addVar3 = 0;
var thisThis = 1;
var moveBlock1 = 350;
var stLandT = 0;
var moveRight = false;
var moveLeft = false;
var movePL = 0;
var movePR = 0;
//////////////////////////////////////////////////////////
//
// LOAD PLATFORMS/SET KEY UP AND DOWN/SET PLAYER POS
function loadGame() {
document.getElementsByTagName("DIV")[4].style.visibility = "visible";
addEventListener('mousemove', getData, false);
addEventListener('keydown', movePlayer, false);
addEventListener('keyup', stopPlayer, false);
moveP();
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
}
function getData(gData) {
}
//////////////////////////////////////////////////////////
//
// KEY DOWN TO MOVE PLAYER
function movePlayer(mPlayer) {
switch (mPlayer.keyCode) {
case 39: // RIGHT
if (stLandT == 0) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
movePL = 0;
movePR = 1;
break;
case 37: // LEFT
if (stLandT == 0) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
movePL = 1;
movePR = 0;
break;
case 38: // UP
break;
case 40: // DOWN
break;
}
}
//////////////////////////////////////////////////////////
//
// KEY UP TO STOP PLAYER/VOID STOP AND GO GLITCH
function stopPlayer(sPlayer) {
if (sPlayer.keyCode == 39) {
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
movePR = 0;
}
if (sPlayer.keyCode == 37) {
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
movePL = 0;
}
}
landThis.js/ MOVE PLAYER AND PLATFORMS
var cTAdd = 0;
var setThis = 1;
var GAPlayer = 3;
//////////////////////////////////////////////////////////
//
// SHOW PLATFORMS TO MOVE
function landT() {
setThis = setTimeout(landT, 500);
if (xPos >= 500) {
cTAdd = Math.floor(Math.random() * 100 + 1);
var block00 = document.createElement("img");
if (cTAdd > 0 && cTAdd < 25) {
block00.src = "images/sep2.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block00.src = "images/sep1.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block00.src = "images/platform00.png";
}
document.getElementById("land01").appendChild(block00);
var block01 = document.createElement("img");
var getB = block01.getBoundingClientRect();
if (cTAdd > 0 && cTAdd < 25) {
block01.src = "images/platform00.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block01.src = "images/sep2.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block01.src = "images/sep1.png";
}
document.getElementById("land00").appendChild(block01);
GAPlayer = GAPlayer + 2;
}
}
//////////////////////////////////////////////////////////
//
// MOVE PLATFORMS
var thisSet = 1;
var cPlayer = 0;
var moveSpeed = 5;
var xPos = 50;
var yPos = 300;
function moveLand() {
thisSet = setTimeout(moveLand, 30);
if (xPos >= 500) {
moveBlock1 = moveBlock1 - 10;
document.getElementById("land00").style.left = moveBlock1 + "px";
document.getElementById("land01").style.left = moveBlock1 + "px";
}
}
//////////////////////////////////////////////////////////
//
// MOVE PLAYER
var setP = 1;
function moveP() {
setP = setTimeout(moveP, 10);
if (movePR == 1) {
xPos = xPos + moveSpeed;
cPlayer++;
if (cPlayer >= 4)
cPlayer = 0;
document.images[GAPlayer].src = gPlayer[cPlayer].src;
}
if (movePL == 1) {
xPos = xPos - moveSpeed;
cPlayer++;
if (cPlayer >= 4)
cPlayer = 0;
document.images[GAPlayer].src = gPlayer[cPlayer].src;
}
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
if (xPos >= 500) {
xPos = 500;
}
if (xPos <= 50) {
xPos = 50;
}
}

JS/JSp issue in IE 10 for scrollbar and sorting

I am facing issue in table where we are using scroll bar and sorting.
In compatible mode sorting option is coming where as not coming in non compatible mode
Please suggest changes in js or jsp
function makeScrollableTable(tbl, scrollFooter, height, hasSelectAllButton, hasAddButton, columnNo) {
var c, pNode, hdr, ftr, wrapper, rect;
//alert("Shree");
if (typeof tbl == 'string') tbl = document.getElementById(tbl);
pNode = tbl.parentNode;
fixTableWidth(tbl);
c = container.length;
container[c] = document.createElement('<SPAN style="height: 100; overflow: auto;">');
container[c].id = tbl.id + "Container";
pNode.insertBefore(container[c], tbl);
container[c].appendChild(tbl);
container[c].style.width = tbl.clientWidth + 2 * tbl.clientLeft + scrollbarWidth();
hdr = tbl.cloneNode(false);
hdr.id += 'Header';
hdr.appendChild(tbl.tHead.cloneNode(true));
tbl.tHead.style.display = 'none';
if (!scrollFooter || !tbl.tFoot) {
ftr = document.createElement('<SPAN style="width:1;height:1;clip: rect(0 1 1 0);background-color:transparent;">');
ftr.id = tbl.id + 'Footer';
ftr.style.border = tbl.style.border;
ftr.style.width = getActualWidth(tbl) + 2 * tbl.clientLeft;
ftr.style.borderBottom = ftr.style.borderLeft = ftr.style.borderRight = 'none';
} else {
ftr = tbl.cloneNode(false);
ftr.id += 'Footer';
ftr.appendChild(tbl.tFoot.cloneNode(true));
ftr.style.borderTop = 'none';
tbl.tFoot.style.display = 'none';
}
wrapper = document.createElement('<table border=0 cellspacing=0 cellpadding=0>');
wrapper.id = tbl.id + 'Wrapper';
pNode.insertBefore(wrapper, container[c]);
wrapper.insertRow(0).insertCell(0).appendChild(hdr);
wrapper.insertRow(1).insertCell(0).appendChild(container[c]);
wrapper.insertRow(2).insertCell(0).appendChild(ftr);
wrapper.align = tbl.align;
tbl.align = hdr.align = ftr.align = 'left';
hdr.style.borderBottom = 'none';
tbl.style.borderTop = tbl.style.borderBottom = 'none';
// adjust page size
if (c == 0 && height == 'auto') {
onResizeAdjustTable();
onResizeHandler = window.onresize;
window.onresize = onResizeAdjustTable;
} else {
container[c].style.height = height;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
//alert("");
if (hasSelectAllButton) {
//include select all button
var selButton = document.createElement('<input id="_myButton11" type="button" value="Select All" onClick="selectAll();">');
insertNode(selButton);
}
if (hasAddButton) {
var btext = '<input id="_myButton12" type="button" value="Add" onClick="posCursor(\'' + tbl.id + '\',\'' + columnNo + '\');">';
var addButton = document.createElement(btext);
insertNode(addButton);
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function insertNode(toInsert) {
var tbs = document.getElementsByTagName('input');
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "button") {
var backButton = tbs[i];
var text = backButton.value.toUpperCase();
if (text == "BACK") {
var pNode = backButton.parentNode;
pNode.insertBefore(toInsert, backButton);
var textNode = document.createTextNode(" ");
pNode.insertBefore(textNode, backButton);
return;
}
}
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function posCursor(tbl, columnNo) {
var table = document.getElementById(tbl);
var rows = table.rows;
for (var i = 0; i < rows.length; i++) {
//cells = rows[i].cells;
//if(columnNo > cells.length) continue;
var cell = rows[i].cells[columnNo];
if (getFocus(cell) == true) {
selectCheckBox(rows[i].cells[0]);
return;
}
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function selectCheckBox(node) {
var children = node.children;
//check if this is a leaf node
if (children.length == 0) {
//if so then see if this is a checkbox input node
if (node.tagName == "INPUT" && node.type == "checkbox") {
node.checked = true;
return true;
} else {
return false;
}
} else {
//this is a parent node
for (var i = 0; i < children.length; i++) {
if (selectCheckBox(children[i]) == true) return true;
}
}
return false;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function getFocus(node) {
var children = node.children;
//check if this is a leaf node
if (children.length == 0) {
//if so then see if this is a text input node
if (node.tagName == "INPUT" && node.type == "text" && node.value == "") {
node.focus();
return true;
} else {
return false;
}
} else {
//this is a parent node
for (var i = 0; i < children.length; i++) {
if (getFocus(children[i]) == true) return true;
}
}
return false;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function selectAll() {
//added by Venkatesh Bhat e-mail:vb106#dcx
var button = document.getElementById('_myButton11');
var butText = button.value;
var tbs = document.getElementsByTagName('input');
if (butText == 'Deselect All') {
button.value = "Select All";
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "checkbox") {
tbs[i].checked = false;
}
}
} else {
button.value = "Deselect All";
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "checkbox") {
tbs[i].checked = true;
}
}
}
}
function onResizeAdjustTable() {
if (onResizeHandler) onResizeHandler();
var rect = container[0].getClientRects()(0);
var h = document.body.clientHeight - (rect.top + (document.body.scrollHeight - rect.bottom));
container[0].style.height = (h > 0) ? h : 1;
}
function printPage() {
var tbs = document.getElementsByTagName('TABLE');
var e;
for (var i = 0; i < container.length; i++) container[i].style.overflow = '';
window.print();
for (var i = 0; i < container.length; i++) container[i].style.overflow = 'auto';
}

Categories

Resources