Tic Tac Toe javascript not working with board larger then 3x3 - javascript

I've been trying to work out this simple javascript tic tac toe game. I'm trying to make the board size a variable and number needed in a row a variable. I've created a global variable for board size and number in a row. However it doesn't seem to be working. It makes the board the size I want but only a few of the squares will actually result in a 'Win'. Could someone please help me out ;).
Here is an image of one of the issues: http://imgur.com/oNK9ErK
I imagine the error occurs here:
function checkWinner(mArr) {
var winner = [false, ""];
for (var i = 0; i < mArr.length; i++) {
var hor = [],
ver = [],
diag = [];
if (mArr[i][3] !== "") {
//horizontal
if (i % 3 === 0) {
for (var j = 0; j < 3; j++) {
hor.push([mArr[i + j][3], i + j]);
}
if (hor.length === numinrow) {
winner = isWinner(hor);
if (winner[0]) {
return winner;
}
}
}
//vertical && diag/anti diag
if (i < 3) {
for (var j = 0; j + i < mArr.length; j += 3) {
ver.push([mArr[i + j][3], i + j]);
}
if (ver.length === numinrow) {
winner = isWinner(ver);
if (winner[0]) {
return winner;
}
}
if (i !== 1) {
for (var z = 0; z + i < mArr.length - i; z += (4 - i)) {
diag.push([mArr[i + z][3], i + z]);
}
if (diag.length === numinrow) {
winner = isWinner(diag);
if (winner[0]) {
return winner;
}
}
}
}
}
}
return winner;
}
Here is the entire .js
(function () {
var bsize = 5;
var numinrow = 3;
function Board(id, c, r) {
if (this instanceof Board) {
this.CANVAS = document.getElementById(id);
this.CTX = this.CANVAS.getContext("2d");
this.WIDTH = this.CANVAS.width || 0;
this.HEIGHT = this.CANVAS.height || 0;
this.COLS = c || bsize;
this.ROWS = r || bsize;
this.TILEWIDTH = (this.WIDTH / this.COLS);
this.moveCount = 0;
this.board = this.gameBoard(this.TILEWIDTH, this.COLS, this.ROWS);
this.CANVAS.addEventListener('selectstart', function (e) {
e.preventDefault();
return false;
}, false);
this.winner = [false, ""];
this.boardDisabled = false;
} else {
return new Board(id, c, r);
}
}
Board.prototype.draw = function () {
var ctx = this.CTX;
ctx.beginPath();
ctx.lineWidth = 5;
ctx.strokeStyle = "#168dd9";
// Draw column dividers
for (var i = 1; i <= this.COLS - 1; i++) {
ctx.moveTo(this.TILEWIDTH * i, 0);
ctx.lineTo(this.TILEWIDTH * i, this.HEIGHT);
}
//Draw horizontal dividers
for (var i = 1; i <= this.ROWS - 1; i++) {
ctx.moveTo(0, this.TILEWIDTH * i);
ctx.lineTo(this.WIDTH, this.TILEWIDTH * i);
}
ctx.stroke();
};
Board.prototype.gameBoard = function (t, c, r) {
var b = [],
count = 0;
// Create gameboard array with the following data:
// [x pos, y pos, tile count, empty string for move symbol (x or o)]
for (var y = 0; y < r; y++) {
for (var x = 0; x < c; x++) {
b.push([x * t, y * t, count++, ""]);
}
}
return b;
};
Board.prototype.updateScore = function () {
if (supports_html5_storage()) {
var p = sessionStorage.score || {
"score_x": 0,
"score_o": 0,
"score_tie": 0
},
w = "score_" + (this.winner[1][0] || "tie");
if (sessionStorage.score) {
p = JSON.parse(p);
}
p[w] ++;
sessionStorage.score = JSON.stringify(p);
this.updateScoreBoard();
}
};
Board.prototype.updateScoreBoard = function () {
if (supports_html5_storage()) {
var p = sessionStorage.score ? JSON.parse(sessionStorage.score) : {
"score_x": 0,
"score_o": 0,
"score_tie": 0
};
for (var s in p) {
if (p.hasOwnProperty(s)) {
document.getElementById(s).innerHTML = p[s];
}
}
}
};
Board.prototype.reset = function (x) {
var timer = x || 4000;
window.setTimeout(function () {
window.location.reload(false);
}, timer);
};
Board.prototype.resetScore = function () {
if (supports_html5_storage()) {
sessionStorage.removeItem("score");
this.updateScoreBoard();
}
};
Board.prototype.move = function (coor) {
var width = this.TILEWIDTH,
ctx = this.CTX,
board = this.board,
blen = board.length;
//Loop through and find tile that click was detected on
for (var i = 0; i < blen; i++) {
if (coor.x > board[i][0] && coor.y > board[i][1] && coor.x < board[i][0] + width && coor.y < board[i][1] + width) {
var x = board[i][0],
y = board[i][1],
validTile = board[i][3] === "";
if (validTile) {
if (this.moveCount++ % 2 === 1) {
moveO(x, y, width, ctx);
board[i][3] = "o";
} else {
moveX(x, y, width, ctx);
board[i][3] = "x";
}
}
//Check board for winner if move count is 5 or more
if (this.moveCount > 4) {
this.winner = checkWinner(board);
var w = this.winner,
winner = w[0],
shape = w[1][0],
boardDisabled = this.boardDisabled;
//If there is a winner, redraw winning tiles in red
if (winner && !boardDisabled) {
if (shape === "o") {
for (var j = 1; j < 4; j++) {
moveO(board[w[j][1]][0], board[w[j][1]]
[1], width, ctx, "red", 5);
}
} else {
for (var j = 1; j < 4; j++) {
moveX(board[w[j][1]][0], board[w[j][1]]
[1], width, ctx, "red", 5);
}
}
}
if ((winner || this.moveCount === board.length) && !boardDisabled) {
if (!winner) {
//If tie, redraw all moves in red
for (var j = 0; j < board.length; j++) {
if (board[j][3] === "o") {
moveO(board[j][0], board[j][1], width, ctx, "red", 5);
} else {
moveX(board[j][0], board[j][1], width, ctx, "red", 5);
}
}
}
this.boardDisabled = true;
this.updateScore();
this.reset();
}
}
break;
}
}
};
function checkWinner(mArr) {
var winner = [false, ""];
for (var i = 0; i < mArr.length; i++) {
var hor = [],
ver = [],
diag = [];
if (mArr[i][3] !== "") {
//horizontal
if (i % 3 === 0) {
for (var j = 0; j < 3; j++) {
hor.push([mArr[i + j][3], i + j]);
}
if (hor.length === numinrow) {
winner = isWinner(hor);
if (winner[0]) {
return winner;
}
}
}
//vertical && diag/anti diag
if (i < 3) {
for (var j = 0; j + i < mArr.length; j += 3) {
ver.push([mArr[i + j][3], i + j]);
}
if (ver.length === numinrow) {
winner = isWinner(ver);
if (winner[0]) {
return winner;
}
}
if (i !== 1) {
for (var z = 0; z + i < mArr.length - i; z += (4 - i)) {
diag.push([mArr[i + z][3], i + z]);
}
if (diag.length === numinrow) {
winner = isWinner(diag);
if (winner[0]) {
return winner;
}
}
}
}
}
}
return winner;
}
function isWinner(arr) {
arr.sort();
var w = arr[0][0] && arr[0][0] === arr[arr.length - 1][0] ? [true].concat(arr) : [false, ""];
return w;
}
function moveO(x, y, r, ctx, fill, lineW) {
var x = x + r / 2,
y = y + r / 2,
r = r / 2 - (r * 0.15);
ctx.beginPath();
ctx.lineWidth = lineW || 3;
ctx.strokeStyle = fill || "#333";
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.stroke();
}
function moveX(x, y, w, ctx, fill, lineW) {
var pad = w * 0.15,
lineCoor = [
[
[x + pad, y + pad], //line 1 start
[x + w - pad, y + w - pad] //line 1 end
],
[
[x + pad, y + w - pad], //line 2 start
[x + w - pad, y + pad] //line 2 end
]
];
ctx.beginPath();
ctx.lineWidth = lineW || 3;
ctx.strokeStyle = fill || "#333";
for (var i = 0; i < 2; i++) {
ctx.moveTo(lineCoor[i][0][0], lineCoor[i][0][1]);
ctx.lineTo(lineCoor[i][1][0], lineCoor[i][1][1]);
}
ctx.stroke();
}
function clickTouch(e) {
var coor = b.CANVAS.relMouseCoords(e);
if (!b.winner[0]) {
b.move(coor);
}
}
function clickTouchReset(e) {
var target = e.target.id;
if (target === "resetScore" && confirm("Are you sure you want to reset the score?")) {
b.resetScore();
} else if (target === "resetGame") {
b.reset(1);
}
}
// Initialize Game
//BOARD SIZE
var b = new Board("game", bsize, bsize),
resetcon = document.getElementById("reset");
b.draw();
b.updateScoreBoard();
//Add event listeners for click or touch
window.addEventListener("click", clickTouch, false);
window.addEventListener("touchstart", clickTouch, false);
resetcon.addEventListener("click", clickTouchReset, false);
resetcon.addEventListener("touchstart", clickTouchReset, false);
})();
/*****
Get Mouse click coordinates within canvas
Modified to include touch events
Source: http://stackoverflow.com/a/9961416
******/
HTMLCanvasElement.prototype.relMouseCoords = function (event) {
var totalOffsetX = 0,
totalOffsetY = 0,
canvasX = 0,
canvasY = 0,
touch = event.touches,
currentElement = this;
do {
totalOffsetX += currentElement.offsetLeft;
totalOffsetY += currentElement.offsetTop;
}
while (currentElement = currentElement.offsetParent)
canvasX = (touch ? touch[0].pageX : event.pageX) - totalOffsetX;
canvasY = (touch ? touch[0].pageY : event.pageY) - totalOffsetY;
canvasX = Math.round(canvasX * (this.width / this.offsetWidth));
canvasY = Math.round(canvasY * (this.height / this.offsetHeight));
return {
x: canvasX,
y: canvasY
}
}
function supports_html5_storage() {
try {
return 'sessionStorage' in window && window.sessionStorage !== null;
} catch (e) {
return false;
}
}

Related

JavaScript value changes but canvas doesn't redraw with updated values

I am trying to implement John Conway's Game of Life in HTML using canvas and JavaScript.
In a 2D array I store the cell's x-y position and state (alive or dead).
I avoid the outer most cells to avoid having to worry about boundary conditions.
Using requestAnimationFrame, I clear the canvas, update the cells for the next generation based on the number of neighbors, then draw them.
I console log the states of the cells, which do change but for some reason they don't get updated in the canvas.
I have already used this link for reference, but to no avail:
Canvas: X value changing in console but not in canvas
Here is the JavaScript code:
var cv = document.querySelector('#cv');
var c = cv.getContext('2d');
var h = cv.height;
var w = cv.width;
//Cell class
function Cell(alive, x, y) {
this.alive = alive;
this.x = x;
this.y = y;
this.draw = function () {
//c.beginPath();
this.x = x;
this.y = y;
if(alive == true) {
c.fillStyle = 'black';
c.fillRect(this.x, this.y, 10, 10);
}
else if(alive == false){
c.fillStyle = 'white';
c.fillRect(this.x, this.y, 10, 10);
}
//c.stroke();
}
}
//2d array to contain Cell objects
var cellArray = new Array(100);
for (var i = 0; i < cellArray.length; i++) {
cellArray[i] = new Array(70);
}
//initial drawing
for(var i = 0; i < cellArray.length; i++) {
for(var j = 0; j < 100; j++) {
var b = Math.round(Math.random() - 0.4);
if(b == 1) {
cellArray[i][j] = new Cell(true, i * 10, j * 10);
cellArray[i][j].draw();
}
else {
cellArray[i][j] = new Cell(false, i * 10, j * 10);
cellArray[i][j].draw();
}
}
}
//find number of neghbor cells
function neighborSum(cell, i, j) {
this.cell = cell;
this.i = i;
this.j = j;
var sum = 0;
if(cellArray[i - 1][j - 1].alive == true) {
sum += 1;
}
if(cellArray[i][j - 1].alive == true) {
sum += 1;
}
if(cellArray[i - 1][j].alive == true) {
sum += 1;
}
if(cellArray[i + 1][j - 1].alive == true) {
sum += 1;
}
if(cellArray[i - 1][j + 1].alive == true) {
sum += 1;
}
if(cellArray[i + 1][j].alive == true) {
sum += 1;
}
if(cellArray[i][j + 1].alive == true) {
sum += 1;
}
if(cellArray[i + 1][j + 1].alive == true) {
sum += 1;
}
return sum;
}
//animate function
function play() {
requestAnimationFrame(play);
c.clearRect(0, 0, w, h);
//check surrounding neighbor cells
for(var i = 1; i < cellArray.length - 1; i++) {
for(var j = 1; j < 70 - 1; j++) {
if( cellArray[i][j].alive == true && ( neighborSum(cellArray[i][j], i, j) > 3 || neighborSum(cellArray[i][j], i, j) < 2 ) ) {
cellArray[i][j].alive = false;
}
else if( cellArray[i][j].alive == true && ( neighborSum(cellArray[i][j], i, j) == 3 || neighborSum(cellArray[i][j], i, j) == 2 ) ) {
cellArray[i][j].alive = true;
}
else if(cellArray[i][j].alive == false && neighborSum(cellArray[i][j], i, j) == 3 ) {
cellArray[i][j].alive = true;
}
}
}
//console.log(cellArray)
//redraw cells alive or dead
for(var i = 1; i < cellArray.length - 1; i++) {
for(var j = 1; j < 70 - 1; j++) {
cellArray[i][j].draw();
}
}
}
requestAnimationFrame(play);
Here is a JSFiddle: https://jsfiddle.net/ew3046st/1/
Okay, so I was able to fix the problem by removing the draw() function and instead I just directly call the fillRect() function in the requestAnimationFrame function. Also, fixed the behavior of the cells by adding another 2d array of the same size to store the state of the cells for the next generation:
...
for(var i = 1; i < cellArray.length - 1; i++) {
for(var j = 1; j < 70 - 1; j++) {
//cellArray[i][j].draw();
c.beginPath();
//cellArray[i][j].draw();
if(cellArray[i][j].alive == true) {
c.fillStyle = 'black';
c.fillRect(cellArray[i][j].x, cellArray[i][j].y, 10, 10);
}
else if(cellArray[i][j].alive == false){
c.fillStyle = 'white';
c.fillRect(cellArray[i][j].x, cellArray[i][j].y, 10, 10);
}
c.stroke();
}
}
...
Here is a working jsfiddle: https://jsfiddle.net/e7u19xpq/1/

Javascript not counting past 9

So I have this problem where I get my score to update, and then it turns the span text to the next number, but it always seems to stop at 9. I tried adding in more 0s into my original span text, but it just doesn't seem to want to go past 9. If anyone could help me fix this, it would greatly be appreciated.
EDIT: Here is where the problem likely lies:
let currentScore = document.getElementById('currentScore').value = score;
and
checkScore();
I don't really know how to shorten this further, but give pointers to what specifically is causing the problem.
<html>
<head>
</head>
<body onload ="checkScore">
<script>
</script>
<p><span style="color:red">Your</span> <span style="color:orange">current</span> <span style="color:gold">High</span> <span style="color:green">Score</span> <span style="color:blue">is:</span>
<span id="SCORES" style="color:purple">0</span>
<input id="currentScore" type="hidden">
<script>
var cookie;
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*365*7*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
cookie = encodeURI(cname + "=" + cvalue + ";" + expires + ";path=/");
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkScore() {
// get current score
let currentScore = document.getElementById('currentScore').value;
//get high score from the "cookie"
let highScore = getCookie('highscore');
// if current score is bigger then high score - set new high score and update cookie
if (highScore < currentScore) {
highScore = currentScore;
setCookie("highscore", highScore, 365);
}
// update DOM
document.getElementById("SCORES").innerHTML = highScore;
}
// set inital cookie for this example to work
setCookie("highscore", -1, 365);
var
COLS = 26,
ROWS = 26,
EMPTY = 0,
SNAKE = 1,
FRUIT = 2,
LEFT = 0,
UP = 1,
RIGHT = 2,
DOWN = 3,
KEY_LEFT = 65,
KEY_UP = 87,
KEY_RIGHT = 68,
KEY_DOWN = 83,
canvas,
ctx,
keystate,
frames,
score;
currentScore;
grid = {
width: null,
height: null,
_grid: null,
init: function(d, c, r) {
this.width = c;
this.height = r;
this._grid = [];
for (var x=0; x < c; x++) {
this._grid.push([]);
for (var y=0; y < r; y++) {
this._grid[x].push(d);
}
}
},
set: function(val, x, y) {
this._grid[x][y] = val;
},
get: function(x, y) {
return this._grid[x][y];
}
}
snake = {
direction: null,
last: null,
_queue: null,
init: function(d, x, y) {
this.direction = d;
this._queue = [];
this.insert(x, y);
},
insert: function(x, y) {
this._queue.unshift({x:x, y:y});
this.last = this._queue[0];
},
remove: function() {
return this._queue.pop();
}
};
function setFood() {
var empty = [];
for (var x=0; x < grid.width; x++) {
for (var y=0; y < grid.height; y++) {
if (grid.get(x, y) === EMPTY) {
empty.push({x:x, y:y});
}
}
}
var randpos = empty[Math.round(Math.random()*(empty.length - 1))];
grid.set(FRUIT, randpos.x, randpos.y);
}
function main() {
canvas = document.createElement("canvas");
canvas.width = COLS*20;
canvas.height = ROWS*20;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
ctx.font = "18px Helvetica";
frames = 0;
keystate = {};
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
});
init();
loop();
}
function init() {
score = 0;
currentScore = 0;
grid.init(EMPTY, COLS, ROWS);
var sp = {x:Math.floor(COLS/2), y:ROWS-1};
snake.init(UP, sp.x, sp.y);
grid.set(SNAKE, sp.x, sp.y);
setFood();
}
function loop() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
}
function update() {
frames++;
if (keystate[KEY_LEFT] && snake.direction !== RIGHT) {
snake.direction = LEFT;
}
if (keystate[KEY_UP] && snake.direction !== DOWN) {
snake.direction = UP;
}
if (keystate[KEY_RIGHT] && snake.direction !== LEFT) {
snake.direction = RIGHT;
}
if (keystate[KEY_DOWN] && snake.direction !== UP) {
snake.direction = DOWN;
}
if (frames%5 === 0) {
var nx = snake.last.x;
var ny = snake.last.y;
switch (snake.direction) {
case LEFT:
nx--;
break;
case UP:
ny--;
break;
case RIGHT:
nx++;
break;
case DOWN:
ny++;
break;
}
if (0 > nx || nx > grid.width-1 ||
0 > ny || ny > grid.height-1 ||
grid.get(nx, ny) === SNAKE
) {
return init();
}
if (grid.get(nx, ny) === FRUIT) {
score++;
let currentScore = document.getElementById('currentScore').value = score;
checkScore();
setFood();
} else {
var tail = snake.remove();
grid.set(EMPTY, tail.x, tail.y);
}
grid.set(SNAKE, nx, ny);
snake.insert(nx, ny);
}
}
function draw() {
var tw = canvas.width/grid.width;
var th = canvas.height/grid.height;
for (var x=0; x < grid.width; x++) {
for (var y=0; y < grid.height; y++) {
switch (grid.get(x, y)) {
case EMPTY:
ctx.fillStyle = "#000";
break;
case SNAKE:
ctx.fillStyle = "#4aa024";
break;
case FRUIT:
ctx.fillStyle = "#f00";
break;
}
ctx.fillRect(x*tw, y*th, tw, th);
}
}
ctx.fillStyle = "#49c2ff";
ctx.fillText("SCORE: " + score, 10, canvas.height-10);
}
main();
</script>
</body>
</html>
I am not sure why you are updating currentScore input it is a hidden input. I changed all document.getElementById('currentScore') selectors to document.getElementById('SCORES') because span is where you are actually showing the highscore.
I will post on why it was stopping at 9 with your previous code soon.
<html>
<head>
</head>
<body onload ="checkScore">
<script>
</script>
<p><span style="color:red">Your</span> <span style="color:orange">current</span> <span style="color:gold">High</span> <span style="color:green">Score</span> <span style="color:blue">is:</span>
<span id="SCORES" style="color:purple">0</span>
<input id="currentScore" type="hidden">
<script>
var cookie;
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*365*7*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
cookie = encodeURI(cname + "=" + cvalue + ";" + expires + ";path=/");
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkScore() {
// get current score
let currentScore = parseInt(document.getElementById('SCORES').innerHTML);
//get high score from the "cookie"
let highScore = getCookie('highscore');
// if current score is bigger then high score - set new high score and update cookie
if (highScore < currentScore) {
highScore = currentScore;
setCookie("highscore", highScore, 365);
}
// update DOM
document.getElementById("SCORES").innerHTML = highScore;
}
// set inital cookie for this example to work
setCookie("highscore", -1, 365);
var
COLS = 26,
ROWS = 26,
EMPTY = 0,
SNAKE = 1,
FRUIT = 2,
LEFT = 0,
UP = 1,
RIGHT = 2,
DOWN = 3,
KEY_LEFT = 65,
KEY_UP = 87,
KEY_RIGHT = 68,
KEY_DOWN = 83,
canvas,
ctx,
keystate,
frames,
score;
currentScore;
grid = {
width: null,
height: null,
_grid: null,
init: function(d, c, r) {
this.width = c;
this.height = r;
this._grid = [];
for (var x=0; x < c; x++) {
this._grid.push([]);
for (var y=0; y < r; y++) {
this._grid[x].push(d);
}
}
},
set: function(val, x, y) {
this._grid[x][y] = val;
},
get: function(x, y) {
return this._grid[x][y];
}
}
snake = {
direction: null,
last: null,
_queue: null,
init: function(d, x, y) {
this.direction = d;
this._queue = [];
this.insert(x, y);
},
insert: function(x, y) {
this._queue.unshift({x:x, y:y});
this.last = this._queue[0];
},
remove: function() {
return this._queue.pop();
}
};
function setFood() {
var empty = [];
for (var x=0; x < grid.width; x++) {
for (var y=0; y < grid.height; y++) {
if (grid.get(x, y) === EMPTY) {
empty.push({x:x, y:y});
}
}
}
var randpos = empty[Math.round(Math.random()*(empty.length - 1))];
grid.set(FRUIT, randpos.x, randpos.y);
}
function main() {
canvas = document.createElement("canvas");
canvas.width = COLS*20;
canvas.height = ROWS*20;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
ctx.font = "18px Helvetica";
frames = 0;
keystate = {};
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
});
init();
loop();
}
function init() {
score = 0;
currentScore = 0;
grid.init(EMPTY, COLS, ROWS);
var sp = {x:Math.floor(COLS/2), y:ROWS-1};
snake.init(UP, sp.x, sp.y);
grid.set(SNAKE, sp.x, sp.y);
setFood();
}
function loop() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
}
function update() {
frames++;
if (keystate[KEY_LEFT] && snake.direction !== RIGHT) {
snake.direction = LEFT;
}
if (keystate[KEY_UP] && snake.direction !== DOWN) {
snake.direction = UP;
}
if (keystate[KEY_RIGHT] && snake.direction !== LEFT) {
snake.direction = RIGHT;
}
if (keystate[KEY_DOWN] && snake.direction !== UP) {
snake.direction = DOWN;
}
if (frames%5 === 0) {
var nx = snake.last.x;
var ny = snake.last.y;
switch (snake.direction) {
case LEFT:
nx--;
break;
case UP:
ny--;
break;
case RIGHT:
nx++;
break;
case DOWN:
ny++;
break;
}
if (0 > nx || nx > grid.width-1 ||
0 > ny || ny > grid.height-1 ||
grid.get(nx, ny) === SNAKE
) {
return init();
}
if (grid.get(nx, ny) === FRUIT) {
score++;
let currentScore = document.getElementById('SCORES').innerHTML = score;
checkScore();
setFood();
} else {
var tail = snake.remove();
grid.set(EMPTY, tail.x, tail.y);
}
grid.set(SNAKE, nx, ny);
snake.insert(nx, ny);
}
}
function draw() {
var tw = canvas.width/grid.width;
var th = canvas.height/grid.height;
for (var x=0; x < grid.width; x++) {
for (var y=0; y < grid.height; y++) {
switch (grid.get(x, y)) {
case EMPTY:
ctx.fillStyle = "#000";
break;
case SNAKE:
ctx.fillStyle = "#4aa024";
break;
case FRUIT:
ctx.fillStyle = "#f00";
break;
}
ctx.fillRect(x*tw, y*th, tw, th);
}
}
ctx.fillStyle = "#49c2ff";
ctx.fillText("SCORE: " + score, 10, canvas.height-10);
}
main();
</script>
</body>
</html>

Prevent collisions with new paths

I'm building a program that runs through an matrix (nxn) avoiding collisions with certain obstacles. I'm having trouble implementing a generic algorithm that works for all possible collision situations, the ultimate goal is to go through all the points of the matrix.
The algorithm I built is looping and can not complete the matrix.
Note: The red square can move in any direction (horizontal, vertical and diagonal movements), but only one cell(square) at a time.
var WALL = 0;
var started = false;
var gridSize = 20;
class Agent {
constructor(x, y, charge, cap, distance) {
this.x = x;
this.y = y;
this.charge = charge;
this.cap = cap;
this.distance = distance;
}
}
$(function() {
var $grid = $("#search_grid");
var opts = {
gridSize: 20
};
var grid = new GraphSearch($grid, opts);
//Initializes the agent
$("#btnInit").click(function() {
if (!started) {
var agent = new Agent(0, 0, 100, 50, 0);
agent.initialize();
started = true;
}
});
});
//Initializes the matrix
function GraphSearch($graph, options) {
this.$graph = $graph;
this.opts = options;
this.initialize();
}
//Initializes the matrix
GraphSearch.prototype.initialize = function() {
this.grid = [];
$graph = this.$graph;
$graph.empty();
var cellWidth = ($graph.width() / this.opts.gridSize) - 2,
cellHeight = ($graph.height() / this.opts.gridSize) - 2,
lineHeight = (this.opts.gridSize >= 30 ? "9.px" : ($graph.height() / this.opts.gridSize) - 10 + "px"),
fontSize = (this.opts.gridSize >= 30 ? "10px" : "20px");
$cellTemplate = $("<span />").addClass("grid_item").width(cellWidth).height(cellHeight).css("line-height", lineHeight).css("font-size", fontSize);
for (var x = 0; x < this.opts.gridSize; x++) {
var $row = $("<div class='row' />");
for (var y = 0; y < this.opts.gridSize; y++) {
var id = "cell_" + x + "_" + y,
$cell = $cellTemplate.clone();
$cell.attr("id", id).attr("x", x).attr("y", y);
$row.append($cell);
var isWall = addWall(x, y, this.opts.gridSize);
if (isWall === 1) {
$cell.addClass("wall");
} else {
$cell.addClass('weight1');
}
}
$graph.append($row);
//Fix for stackoverflow snippet
if ($(window).width() < 700) {
$("#search_grid").css("width", "320px");
$("#main").css("width", "38%");
} else {
$("#search_grid").css("width", "300px");
$("#main").css("width", "20%");
}
}
};
//Where will be wall in the matrix
addWall = function(x, y, size) {
var limitPointLeftUp = [2, 3];
var limitPointRightUp = [2, size - 4];
var limitPointLeftDown = [size - 4, 2];
var limitPointRightDown = [size - 4, size - 4];
if ((x == 2 && y == 2) || (x == 2 && y == size - 3)) {
return 1;
}
if ((x == size - 3 && y == 2) || (x == size - 3 && y == size - 3)) {
return 1;
}
if (x >= 2 && (y == 3 && x >= limitPointLeftUp[0] && x <= limitPointLeftDown[0] + 1)) {
return 1;
}
if (x >= 2 && (y == size - 4 && x >= limitPointRightUp[0] && x <= limitPointRightDown[0] + 1)) {
return 1;
}
if ((x == 1 && y == 5) || (x == 9 && y == 17) || (x == 6 && y == 0) || (x == 9 && y == 7) || (x == 15 && y == 0) || (x == 15 && y == 2) || (x == 18 && y == 15)) {
return 1;
}
}
//Initializes the agent
Agent.prototype.initialize = function() {
var agent = this;
var lastDir = "right";
var tryTo = "";
var trying = false;
var right = true;
var up = false;
var down = false;
var left = false;
var timerId = 0;
//Simulates agent movement [Here is my problem]
timerId = setInterval(function() {
RemoveAgent();
var cell = $("#search_grid .row .grid_item[x=" + agent.x + "][y=" + agent.y + "]");
cell.css("background-color", "#e2e2e2");
cell.addClass("agent");
//start direction: right
if (right) {
lastDir = "right";
if (tryTo == "down" && trying) {
if (EmptySqm(agent.x + 1, agent.y)) {
trying = false;
right = false;
down = true;
agent.x++;
}
} else if (tryTo == "up" && trying) {
if (EmptySqm(agent.x - 1, agent.y)) {
trying = false;
right = false;
up = true;
agent.x--;
}
}
if (right) {
//check if is valid sqm
if (ValidSqm(agent.x, agent.y + 1)) {
//go right if empty
if (EmptySqm(agent.x, agent.y + 1)) {
agent.y++;
} else {
right = false;
//check up sqm
if (EmptySqm(agent.x - 1, agent.y)) {
up = true;
trying = true;
}
//check down
else if (EmptySqm(agent.x + 1, agent.y)) {
down = true;
trying = true;
}
}
} else {
agent.x++;
right = false;
left = true;
}
}
//left direction
} else if (left) {
lastDir = "left";
if (tryTo == "down" && trying) {
if (EmptySqm(agent.x + 1, agent.y)) {
trying = false;
left = false;
down = true;
agent.x++;
}
} else if (tryTo == "up" && trying) {
if (EmptySqm(agent.x - 1, agent.y)) {
trying = false;
left = false;
up = true;
agent.x--;
}
}
if (left) {
if (ValidSqm(agent.x, agent.y - 1)) {
if (EmptySqm(agent.x, agent.y - 1)) {
agent.y--;
} else {
left = false;
if (EmptySqm(agent.x + 1, agent.y)) {
down = true;
trying = true;
} else if (EmptySqm(agent.x - 1, agent.y)) {
up = true;
trying = true;
}
}
} else {
agent.x++;
right = true;
left = false;
}
}
//up direction
} else if (up) {
tryTo = "down";
if (lastDir == "left") {
if (EmptySqm(agent.x, agent.y - 1)) {
up = false;
left = true;
agent.y--;
}
} else if (lastDir == "right") {
if (EmptySqm(agent.x, agent.y + 1)) {
up = false;
right = true;
agent.y++;
}
}
if (up) {
if (ValidSqm(agent.x - 1, agent.y)) {
if (EmptySqm(agent.x - 1, agent.y)) {
agent.x--;
} else {
up = false;
//check left sqm
if (EmptySqm(agent.x, agent.y - 1)) {
left = true;
agent.y--;
}
//check right sqm
else if (EmptySqm(agent.x, agent.y + 1)) {
right = true;
agent.y++;
}
//check down sqm
else if (EmptySqm(agent.x + 1, agent.y)) {
down = true;
agent.x++;
}
}
} else {
agent.x++;
up = false;
down = true;
}
}
//down direction
} else if (down) {
tryTo = "up";
if (lastDir == "left") {
if (EmptySqm(agent.x, agent.y - 1)) {
down = false;
left = true;
agent.y--;
}
} else if (lastDir == "right") {
if (EmptySqm(agent.x, agent.y + 1)) {
down = false;
right = true;
agent.y++;
}
}
if (down) {
if (ValidSqm(agent.x + 1, agent.y)) {
if (EmptySqm(agent.x + 1, agent.y)) {
agent.x++;
} else {
down = false;
//check left sqm
if (EmptySqm(agent.x, agent.y - 1)) {
left = true;
agent.y--;
}
//check right sqm
else if (EmptySqm(agent.x, agent.y + 1)) {
right = true;
agent.y++;
}
//check up sqm
else if (EmptySqm(agent.x - 1, agent.y)) {
up = true;
agent.x--;
}
}
} else {
agent.x--;
up = true;
down = false;
}
}
}
}, 100);
var stopInterval = function() {
clearInterval(timerId);
};
};
EmptySqm = function(x, y) {
var bNotWall = !$("#search_grid .row .grid_item[x=" + x + "][y=" + y + "]").hasClass("wall");
return bNotWall;
}
RemoveAgent = function() {
$("#search_grid .row .grid_item").removeClass("agent");
}
ValidSqm = function(x, y) {
return ((x >= 0 && x < gridSize) && (y >= 0 && y < gridSize));
}
html,
body {
height: 100%;
margin: 0;
}
.buttons {
float: right;
position: relative;
right: 10px;
top: 10px;
}
.buttons a {
text-decoration: none;
}
#content {
margin: 0 auto;
width: 98%;
text-align: center;
}
#controls {
text-align: center;
margin-bottom: 25px;
padding: 5px;
}
#search_grid {
width: 320px;
height: 300px;
position: relative;
}
#main {
margin: auto;
width: 20%;
}
.grid_item {
display: block;
border: 1px solid #bbb;
float: left;
line-height: 12px;
font-size: 10px;
}
.grid_item.wall {
background-color: #000000;
}
.grid_item.weight1 {
background-color: #ffffff;
}
.agent {
text-align: center;
color: grey;
font-size: 20px;
background-color: red !important;
color: blue;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="content">
<input type="button" id="btnInit" value="Start" /><br><br>
<div id="main">
<div id="search_grid">Loading...</div>
</div>
</div>
<div id="footer"></div>
</body>
I solved my problem with the help of the a* algorithm, more specifically this implementation, the deviation of the obstacles is done with the move method, which returns the path to a certain cell
path = grid.move(currentCell, endCell);
var agentSpeed = 10;
var WALL = 0;
var started = false;
var gridSize = 20;
var x = 0;
var y = 0;
var runsSameLine = false;
class Agent {
constructor(x, y, charge, cap, distance) {
this.x = x;
this.y = y;
this.charge = charge;
this.cap = cap;
this.distance = distance;
}
}
$(function() {
var $grid = $("#search_grid");
var opts = {
gridSize: gridSize
};
var grid = new GraphSearch($grid, opts, astar.search);
//Initializes the agent
$("#btnInit").click(function() {
if (!started) {
var agent = new Agent(0, 0, 100, 50, 0);
agent.initialize();
started = true;
}
});
});
//Initializes the matrix
function GraphSearch($graph, options, implementation) {
this.$graph = $graph;
this.search = implementation;
this.opts = options;
this.initialize();
}
var grid;
GraphSearch.prototype.move = function($start, $end) {
var end = this.nodeFromElement($end);
if ($end.hasClass("wall")) {
return;
}
var start = this.nodeFromElement($start);
var path = this.search(this.graph.nodes, start, end, true);
if (!path || path.length == 0) {
//this.animateNoPath();
} else {
return path;
}
};
GraphSearch.prototype.nodeFromElement = function($cell) {
return this.graph.nodes[parseInt($cell.attr("x"))][parseInt($cell.attr("y"))];
};
//Initializes the matrix
GraphSearch.prototype.initialize = function() {
this.grid = [];
var self = this,
nodes = [],
$graph = this.$graph;
$graph.empty();
var cellWidth = ($graph.width() / this.opts.gridSize) - 2,
cellHeight = ($graph.height() / this.opts.gridSize) - 2,
lineHeight = (this.opts.gridSize >= 30 ? "9.px" : ($graph.height() / this.opts.gridSize) - 10 + "px"),
fontSize = (this.opts.gridSize >= 30 ? "10px" : "20px");
$cellTemplate = $("<span />").addClass("grid_item").width(cellWidth).height(cellHeight).css("line-height", lineHeight).css("font-size", fontSize);
for (var x = 0; x < this.opts.gridSize; x++) {
var $row = $("<div class='row' />");
nodeRow = [],
gridRow = [];
for (var y = 0; y < this.opts.gridSize; y++) {
var id = "cell_" + x + "_" + y,
$cell = $cellTemplate.clone();
$cell.attr("id", id).attr("x", x).attr("y", y);
$row.append($cell);
gridRow.push($cell);
var isWall = addWall(x, y, this.opts.gridSize);
if (isWall === 1) {
$cell.addClass("wall");
nodeRow.push(1);
} else {
$cell.addClass('weight1');
nodeRow.push(0);
}
}
$graph.append($row);
this.grid.push(gridRow);
nodes.push(nodeRow);
//Fix for stackoverflow snippet
if ($(window).width() < 700) {
$("#search_grid").css("width", "320px");
$("#main").css("width", "38%");
} else {
$("#search_grid").css("width", "300px");
$("#main").css("width", "20%");
}
}
this.graph = new Graph(nodes);
this.$cells = $graph.find(".grid_item");
grid = this;
};
//Where will be wall in the matrix
addWall = function(x, y, size) {
var limitPointLeftUp = [2, 3];
var limitPointRightUp = [2, size - 4];
var limitPointLeftDown = [size - 4, 2];
var limitPointRightDown = [size - 4, size - 4];
if ((x == 2 && y == 2) || (x == 2 && y == size - 3)) {
return 1;
}
if ((x == size - 3 && y == 2) || (x == size - 3 && y == size - 3)) {
return 1;
}
if (x >= 2 && (y == 3 && x >= limitPointLeftUp[0] && x <= limitPointLeftDown[0] + 1)) {
return 1;
}
if (x >= 2 && (y == size - 4 && x >= limitPointRightUp[0] && x <= limitPointRightDown[0] + 1)) {
return 1;
}
if ((x == 1 && y == 5) || (x == 9 && y == 17) || (x == 6 && y == 0) || (x == 9 && y == 7) || (x == 15 && y == 0) || (x == 15 && y == 2) || (x == 18 && y == 15)) {
return 1;
}
}
//Initializes the agent
Agent.prototype.initialize = function() {
var agent = this;
var goToLeft = false;
var goToRight = true;
var rightLimit = gridSize - 1;
var leftLimit = 0;
var lastPos = 0;
var path = [];
var completedPath = true;
timerId = setInterval(function() {
agent.x = x;
agent.y = y;
currentCell = $("#search_grid .row .grid_item[x=" + x + "][y=" + y + "]");
currentCell.css("background-color", "#e2e2e2");
if (agent.x == gridSize - 1 && agent.y == 0) {
stopInterval(timerId);
return false;
}
if (goToRight && y == rightLimit) {
if (runsSameLine) {
goToLeft = true;
goToRight = false;
runsSameLine = false;
} else {
if (FreeCell((x + 1), y)) {
endCell = $("#search_grid .row .grid_item[x=" + (x + 1) + "][y=" + y + "]");
x++;
goToLeft = true;
goToRight = false;
} else {
endCell = FindNextFreeCell(x, y, "limDir");
goToLeft = true;
goToRight = false;
}
}
} else if (goToLeft && y == leftLimit) {
if (runsSameLine) {
goToLeft = false;
goToRight = true;
runsSameLine = false;
} else {
if (FreeCell((x + 1), y)) {
endCell = $("#search_grid .row .grid_item[x=" + (x + 1) + "][y=" + y + "]");
x++;
goToLeft = false;
goToRight = true;
} else {
endCell = FindNextFreeCell(x, y, "limEsq");
goToLeft = false;
goToRight = true;
}
}
} else if (goToRight) {
if (FreeCell(x, (y + 1))) {
endCell = $("#search_grid .row .grid_item[x=" + x + "][y=" + (y + 1) + "]");
y++;
} else {
endCell = FindNextFreeCell(x, y, "dir");
}
} else if (goToLeft) {
if (FreeCell(x, (y - 1))) {
endCell = $("#search_grid .row .grid_item[x=" + x + "][y=" + (y - 1) + "]");
y--;
} else {
endCell = FindNextFreeCell(x, y, "esq");
}
}
if (completedPath) {
path = grid.move(currentCell, endCell);
}
if (path) {
if (lastPos == path.length - 1) {
completedPath = true;
}
if (path.length > 1 && lastPos < path.length && lastPos != path.length - 1) {
x = path[lastPos].x;
y = path[lastPos].y;
lastPos++;
completedPath = false;
} else if (completedPath) {
x = path[lastPos].x;
y = path[lastPos].y;
lastPos = 0;
}
}
grid.$cells.removeClass("agent");
$("#search_grid .row .grid_item[x=" + x + "][y=" + y + "]").addClass("agent");
}, agentSpeed);
var stopInterval = function() {
clearInterval(timerId);
};
};
FindNextFreeCell = function(x, y, dir) {
if (dir == "limDir") {
if (x != gridSize) {
for (var y = y; y >= 0; y--) {
if (FreeCell((x + 1), y)) {
return getCell((x + 1), y);
}
}
}
} else if (dir == "limEsq") {
if (x != gridSize) {
for (var y = y; y <= gridSize; y++) {
if (FreeCell((x + 1), y)) {
return getCell((x + 1), y);
}
}
}
} else if (dir == "dir") {
for (var y = y; y < gridSize - 1; y++) {
if (FreeCell(x, (y + 1))) {
return getCell(x, (y + 1));
}
}
for (var x = x; x <= gridSize - 1; x++) {
if (FreeCell((x + 1), y)) {
runsSameLine = true;
return getCell((x + 1), y);
}
}
} else if (dir == "esq") {
for (var y = y; y > 0; y--) {
if (FreeCell(x, (y - 1))) {
return getCell(x, (y - 1));
}
}
for (var x = x; x <= gridSize - 1; x++) {
if (FreeCell((x + 1), y)) {
runsSameLine = true;
return getCell((x + 1), y);
}
}
}
}
EmptySqm = function(x, y) {
var bNotWall = !$("#search_grid .row .grid_item[x=" + x + "][y=" + y + "]").hasClass("wall");
return bNotWall;
}
getCell = function(x, y) {
return $("#search_grid .row .grid_item[x=" + x + "][y=" + y + "]");
}
FreeCell = function(x, y) {
var bNaoTemParede = !$("#search_grid .row .grid_item[x=" + x + "][y=" + y + "]").hasClass("wall");
var bNaoTemLixeira = !$("#search_grid .row .grid_item[x=" + x + "][y=" + y + "]").hasClass("lixeira");
var bNaoTemRecarga = !$("#search_grid .row .grid_item[x=" + x + "][y=" + y + "]").hasClass("pontoRecarga");
return bNaoTemParede && bNaoTemLixeira && bNaoTemRecarga;
}
ValidSqm = function(x, y) {
return ((x >= 0 && x < gridSize) && (y >= 0 && y < gridSize));
}
// javascript-astar
// http://github.com/bgrins/javascript-astar
// Freely distributable under the MIT License.
// Implements the astar search algorithm in javascript using a binary heap.
var astar = {
init: function(grid) {
for (var x = 0, xl = grid.length; x < xl; x++) {
for (var y = 0, yl = grid[x].length; y < yl; y++) {
var node = grid[x][y];
node.f = 0;
node.g = 0;
node.h = 0;
node.cost = node.type;
node.visited = false;
node.closed = false;
node.parent = null;
}
}
},
heap: function() {
return new BinaryHeap(function(node) {
return node.f;
});
},
search: function(grid, start, end, diagonal, heuristic) {
astar.init(grid);
heuristic = heuristic || astar.manhattan;
diagonal = !!diagonal;
var openHeap = astar.heap();
openHeap.push(start);
while (openHeap.size() > 0) {
// Grab the lowest f(x) to process next. Heap keeps this sorted for us.
var currentNode = openHeap.pop();
// End case -- result has been found, return the traced path.
if (currentNode === end) {
var curr = currentNode;
var ret = [];
while (curr.parent) {
ret.push(curr);
curr = curr.parent;
}
return ret.reverse();
}
// Normal case -- move currentNode from open to closed, process each of its neighbors.
currentNode.closed = true;
// Find all neighbors for the current node. Optionally find diagonal neighbors as well (false by default).
var neighbors = astar.neighbors(grid, currentNode, diagonal);
for (var i = 0, il = neighbors.length; i < il; i++) {
var neighbor = neighbors[i];
if (neighbor.closed || neighbor.isWall() || $("#search_grid .row .grid_item[x=" + neighbor.x + "][y=" + neighbor.y + "]").hasClass("pontoRecarga") || $("#search_grid .row .grid_item[x=" + neighbor.x + "][y=" + neighbor.y + "]").hasClass("lixeira")) {
// Not a valid node to process, skip to next neighbor.
continue;
}
// The g score is the shortest distance from start to current node.
// We need to check if the path we have arrived at this neighbor is the shortest one we have seen yet.
var gScore = currentNode.g + neighbor.cost;
var beenVisited = neighbor.visited;
if (!beenVisited || gScore < neighbor.g) {
// Found an optimal (so far) path to this node. Take score for node to see how good it is.
neighbor.visited = true;
neighbor.parent = currentNode;
neighbor.h = neighbor.h || heuristic(neighbor.pos, end.pos);
neighbor.g = gScore;
neighbor.f = neighbor.g + neighbor.h;
if (!beenVisited) {
// Pushing to heap will put it in proper place based on the 'f' value.
openHeap.push(neighbor);
} else {
// Already seen the node, but since it has been rescored we need to reorder it in the heap
openHeap.rescoreElement(neighbor);
}
}
}
}
// No result was found - empty array signifies failure to find path.
return [];
},
manhattan: function(pos0, pos1) {
// See list of heuristics: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
var d1 = Math.abs(pos1.x - pos0.x);
var d2 = Math.abs(pos1.y - pos0.y);
return d1 + d2;
},
neighbors: function(grid, node, diagonals) {
var ret = [];
var x = node.x;
var y = node.y;
// West
if (grid[x - 1] && grid[x - 1][y]) {
ret.push(grid[x - 1][y]);
}
// East
if (grid[x + 1] && grid[x + 1][y]) {
ret.push(grid[x + 1][y]);
}
// South
if (grid[x] && grid[x][y - 1]) {
ret.push(grid[x][y - 1]);
}
// North
if (grid[x] && grid[x][y + 1]) {
ret.push(grid[x][y + 1]);
}
if (diagonals) {
// Southwest
if (grid[x - 1] && grid[x - 1][y - 1]) {
ret.push(grid[x - 1][y - 1]);
}
// Southeast
if (grid[x + 1] && grid[x + 1][y - 1]) {
ret.push(grid[x + 1][y - 1]);
}
// Northwest
if (grid[x - 1] && grid[x - 1][y + 1]) {
ret.push(grid[x - 1][y + 1]);
}
// Northeast
if (grid[x + 1] && grid[x + 1][y + 1]) {
ret.push(grid[x + 1][y + 1]);
}
}
return ret;
}
};
// javascript-astar
// http://github.com/bgrins/javascript-astar
// Freely distributable under the MIT License.
// Includes Binary Heap (with modifications) from Marijn Haverbeke.
// http://eloquentjavascript.net/appendix2.html
var GraphNodeType = {
OPEN: 0,
WALL: 1
};
// Creates a Graph class used in the astar search algorithm.
function Graph(grid) {
var nodes = [];
for (var x = 0; x < grid.length; x++) {
nodes[x] = [];
for (var y = 0, row = grid[x]; y < row.length; y++) {
nodes[x][y] = new GraphNode(x, y, row[y]);
}
}
this.input = grid;
this.nodes = nodes;
}
Graph.prototype.toString = function() {
var graphString = "\n";
var nodes = this.nodes;
var rowDebug, row, y, l;
for (var x = 0, len = nodes.length; x < len; x++) {
rowDebug = "";
row = nodes[x];
for (y = 0, l = row.length; y < l; y++) {
rowDebug += row[y].type + " ";
}
graphString = graphString + rowDebug + "\n";
}
return graphString;
};
function GraphNode(x, y, type) {
this.data = {};
this.x = x;
this.y = y;
this.pos = {
x: x,
y: y
};
this.type = type;
}
GraphNode.prototype.toString = function() {
return "[" + this.x + " " + this.y + "]";
};
GraphNode.prototype.isWall = function() {
return this.type === GraphNodeType.WALL;
};
function BinaryHeap(scoreFunction) {
this.content = [];
this.scoreFunction = scoreFunction;
}
BinaryHeap.prototype = {
push: function(element) {
// Add the new element to the end of the array.
this.content.push(element);
// Allow it to sink down.
this.sinkDown(this.content.length - 1);
},
pop: function() {
// Store the first element so we can return it later.
var result = this.content[0];
// Get the element at the end of the array.
var end = this.content.pop();
// If there are any elements left, put the end element at the
// start, and let it bubble up.
if (this.content.length > 0) {
this.content[0] = end;
this.bubbleUp(0);
}
return result;
},
remove: function(node) {
var i = this.content.indexOf(node);
// When it is found, the process seen in 'pop' is repeated
// to fill up the hole.
var end = this.content.pop();
if (i !== this.content.length - 1) {
this.content[i] = end;
if (this.scoreFunction(end) < this.scoreFunction(node)) {
this.sinkDown(i);
} else {
this.bubbleUp(i);
}
}
},
size: function() {
return this.content.length;
},
rescoreElement: function(node) {
this.sinkDown(this.content.indexOf(node));
},
sinkDown: function(n) {
// Fetch the element that has to be sunk.
var element = this.content[n];
// When at 0, an element can not sink any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = ((n + 1) >> 1) - 1,
parent = this.content[parentN];
// Swap the elements if the parent is greater.
if (this.scoreFunction(element) < this.scoreFunction(parent)) {
this.content[parentN] = element;
this.content[n] = parent;
// Update 'n' to continue at the new position.
n = parentN;
}
// Found a parent that is less, no need to sink any further.
else {
break;
}
}
},
bubbleUp: function(n) {
// Look up the target element and its score.
var length = this.content.length,
element = this.content[n],
elemScore = this.scoreFunction(element);
while (true) {
// Compute the indices of the child elements.
var child2N = (n + 1) << 1,
child1N = child2N - 1;
// This is used to store the new position of the element,
// if any.
var swap = null;
var child1Score;
// If the first child exists (is inside the array)...
if (child1N < length) {
// Look it up and compute its score.
var child1 = this.content[child1N];
child1Score = this.scoreFunction(child1);
// If the score is less than our element's, we need to swap.
if (child1Score < elemScore) {
swap = child1N;
}
}
// Do the same checks for the other child.
if (child2N < length) {
var child2 = this.content[child2N],
child2Score = this.scoreFunction(child2);
if (child2Score < (swap === null ? elemScore : child1Score)) {
swap = child2N;
}
}
// If the element needs to be moved, swap it, and continue.
if (swap !== null) {
this.content[n] = this.content[swap];
this.content[swap] = element;
n = swap;
}
// Otherwise, we are done.
else {
break;
}
}
}
};
html,
body {
height: 100%;
margin: 0;
}
.buttons {
float: right;
position: relative;
right: 10px;
top: 10px;
}
.buttons a {
text-decoration: none;
}
#content {
margin: 0 auto;
width: 98%;
text-align: center;
}
#controls {
text-align: center;
margin-bottom: 25px;
padding: 5px;
}
#search_grid {
width: 300px;
height: 300px;
position: relative;
}
#main {
margin: auto;
width: 20%;
}
.grid_item {
display: block;
border: 1px solid #bbb;
float: left;
line-height: 12px;
font-size: 10px;
}
.grid_item.wall {
background-color: #000000;
}
.grid_item.weight1 {
background-color: #ffffff;
}
.agent {
text-align: center;
color: grey;
font-size: 20px;
background-color: red !important;
color: blue;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="content">
<input type="button" id="btnInit" value="Start" /><br><br>
<div id="main">
<div id="search_grid">Loading...</div>
</div>
</div>
<div id="footer"></div>
</body>

Control ball speed in pong

I have this code below, and I'm having a hard time solving this one.
On dotime function, i have the ball speed:
/* HERE */
function dotime() {
move1();
if (myform != null) {
myform.text3.value = display1();
myform.score.value = "" + score;
}
/* ---Ball Speed--- */
if (!oops_flag) timerID = setTimeout("dotime()", 190);
/* ---trying to make ball speed faster--- */
if (score == 1) {
timerID = setTimeout("dotime()", 100 - 30);
}
timerRunning = true;
}
I tried to make the ball move faster but when i do the second "if", the ball just flying too fast.
Thanks in advance,
fufle.
full code:
var crlf = "\r\n";
var x = 0;
var y = 0;
var dx = 1;
var dy = 1;
var s = "";
var u = 0;
var oops_flag = false;
var score = 0;
function move1() {
x += dx;
if (x > 61) {
x -= 2 * Math.abs(dx);
if (dx > 0) dx = -dx;
}
if (x < 0) {
x += 2 * Math.abs(dx);
if (dx < 0) dx = -dx;
}
y += dy;
if (y > 24) {
y -= 2 * Math.abs(dy);
if (dy > 0) dy = -dy;
if (Math.abs(x - 2 * u - 1) > 2) {
oops_flag = true;
} else {
score += 1;
}
}
if (y < 0) {
y += 2 * Math.abs(dy);
if (dy < 0) dy = -dy;
}
}
function display1() {
var s1 = ""
var i, j;
if (oops_flag) return " Unlucky, Play again?"
for (j = 0; j < 25; j++) {
for (i = 0; i < 62; i++) {
/* BALL */
if (j == y && i == x) s1 += "🔴";
else s1 += " ";
}
s1 += crlf;
}
/* DEFENDER */
var s2 = "";
for (i = 0; i < 31; i++) {
if (u == i) s2 += "â–„â–„â–„â–„â–„";
else s2 += " ";
}
return (s1 + s2);
}
var timerID = null;
var timerRunning = false;
var myform;
function stopclock() {
if (timerRunning) clearTimeout(timerID);
timerRunning = false;
}
function startclock(form) {
myform = form;
oops_flag = false;
score = 0;
if (navigator.userAgent.indexOf("Mac") > 2) crlf = "\n";
stopclock();
dotime();
// var id= setInterval(frameElement,10000);
}
/* HERE */
function dotime() {
move1();
if (myform != null) {
myform.text3.value = display1();
myform.score.value = "" + score;
}
if (!oops_flag) timerID = setTimeout("dotime()", 100);
if (score == 1) {
timerID = setTimeout("dotime()", 100 - 30);
}
timerRunning = true;
}
Looks like you have two timers running so you need to make it so only one will run.
if (!oops_flag) {
var speed = 100;
if (score===1) speed = 70;
timerID = setTimeout(dotime, speed);
}
or with a ternary operator
if (!oops_flag) {
var speed = (score===1) ? 70 : 100;
timerID = setTimeout(dotime, speed);
}

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 ==.

Categories

Resources