Multiple object intersection and removal problem [ processing/p5.js ] - javascript

I am new to stack and not quite sure how to use it. But here I am. I am working on a ecosystem project, and I have an animal class with 2 different genders(0 for female, 1 for male). When 2 different genders intersect each other than I want to remove those 2 objects and add a couple(different object, static) object on that position. I kinda did it but it only works for a couple of seconds. Then the code just breaks. In the console it says,
“Uncaught TypeError: Cannot read property ‘intersects’ of undefined”
Here's the question on the processing forum in case I get a solution which might help others: https://discourse.processing.org/t/multiple-object-intersection-and-removal/22900/2
Here's the sketch.js file:
var animats = [];
var couples = [];
function setup() {
frameRate(30);
createCanvas(displayWidth, 470);
for(var i = 0; i < 50; i++)
{
animats[i] = new Animat(random(0, width), random(0, height));
}
}
function draw() {
background(255,100,100);
for(var i = animats.length-1; i >= 0; i--) {
animats[i].birth();
animats[i].grow();
for(var j = i; j >= 0; j--) {
if(j != i && animats[i].intersects(animats[j])) {
animats.splice(i, 1);
animats.splice(j, 1);
}
}
}
}
Here's the animat class file:
function Animat(x, y) {
this.x = x;
this.y = y;
this.gender;
var g = random(0,1);
var c;
if(g > 0.5) {
c = 0;
this.gender = 0;
} else {
c = 255;
this.gender = 1;
}
this.speed = 1;
this.age = 0;
this.length = 0.5;
this.birth = function() {
//gender
//create
noStroke();
fill(c);
text("n", this.x, this.y, this.length, this.length);
ellipse(this.x, this.y, this.length * 2, this.length * 2);
//move
switch(floor(random(0,4))) {
case 0:
this.x += this.speed;
break;
case 1:
this.y += this.speed;
break;
case 2:
this.x -= this.speed;
break;
case 3:
this.y -= this.speed;
break;
default:
this.x++;
this.y--;
}
//bounce
if(this.x > width || this.x < 4){
this.speed *= -1;
}
if(this.y > height || this.y < 4){
this.speed *= -1;
}
}
this.grow = function() {
this.age += 0.01;
this.length += 0.05;
//age checks
if(this.age > 10) {
this.speed + 5;
} else if(this.age > 21) {
this.length = 25;
this.speed = this.speed
//console.log("max age:" + this.age)
} else if(this.age > 70) {
//die
} else {
}
//length checks
if(this.length > 25) {
this.length = 25;
//console.log("max length");
}
}
//relationship
this.intersects = function(other) {
var d = dist(this.x, this.y, other.x, other.y);
var r = this.length + other.length;
if(d < r) {
if(((this.gender == 0) && (other.gender == 1)) || ((this.gender == 1) && (other.gender == 0))) {
return true;
} else {
this.speed *= -1;
}
} else {
return false;
}
}
//mate
this.couple = function() {
if(((this.gender == 0) && (other.gender == 1)) || ((this.gender == 1) && (other.gender == 0))) {
return true;
} else {
this.speed *= -1;
}
}
//die
/*this.die = function() {
if(this.age > 50) {
return true;
} else {
return false;
}
}*/
}
Here's the codepen link for results I am getting:
https://codepen.io/AbrarShahriar/pen/XWXwLPM

Try changing your nested for loop to:
for (var i = animats.length - 1; i >= 0; i--) {
animats[i].birth();
animats[i].grow();
for (var j = i; j >= 0; j--) {
if (j != i && animats[i].intersects(animats[j])) {
animats.splice(i, 1);
animats.splice(j, 1);
break; //exit the inner loop after a match
}
}
}
In other words, add a break; after two animats have coupled and have been removed from the array. The error was probably caused by you trying to call the intersects method of an animat that had already been removed.

you need to keep animats[i] as long as the for-loop for j has not finished.
Here the code you need to fix:
for(var i = animats.length-1; i >= 0; i--) {
animats[i].birth();
animats[i].grow();
let remove = false; // mark 'i' as NOT REMOVE by default
for(var j = i; j >= 0; j--) {
if(j != i && animats[i].intersects(animats[j])) {
remove = true; // mark 'i' as to remove when collision detected
animats.splice(j, 1);
}
}
if (remove) { // remove 'i' after compared to all 'j'
animats.splice(i, 1);
}
}

Related

how to calculate percisely the character movement in a tiles

So, i have started building a game 2d just a few day so its make me so confuse with some reason of the movement character in the tilemap.In my tilemap, every per tiles2 is have the width and height 16px and the whole map is 800 x 1250, every movement of my character will add/sub 1 in per step, when I calculating detection collisions, the position became wrong position specifically when character move a step then the position return to far though i try to divide 16 px in every movement of character.
This is my movement:
this.setting_walking_speed = 3 ;
if (this.player.control_direction[0] == 1) {
this.player.x -= this.setting_walking_speed;
this.player.walking = 1;
this.player.direction = 0;
} else if (this.player.control_direction[1] == 1) {
this.player.y -= this.setting_walking_speed;
this.player.walking = 1;
this.player.direction = 2;
} else if (this.player.control_direction[2] == 1) {
this.player.x += this.setting_walking_speed;
this.player.walking = 1;
this.player.direction = 1;
} else if (this.player.control_direction[3] == 1) {
this.player.y += this.setting_walking_speed;
this.player.walking = 1;
this.player.direction = 3;
}
var posf = {
x:Math.floor( this.player.y /16 ) ,
y:Math.floor( this.player.x /16 )
};
this.collide(posf);
console.log(posf.x , posf.y);
}
And the collision function is:
The this.setting_minblocksize\[k\] = 16;
this.bound = this.draw_collision();
function rectangularCollision({rect1, rect2 }) {
return (
rect1.x >= rect2.x &&
rect1.x <= rect2.x &&
rect1.y <= rect2.y &&
rect1.y >= rect2.y
)
}
this.collide = function(player){
// console.log(this.bound);
this.bound.forEach((boundaries) => {
if(
rectangularCollision({,
rect1: player,
rect2: boundaries
})
){
console.log('collide');
}
})
}
this.draw_collision = function () {
var obj = [];
this.ctxt.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < canvas.height; i++) {
for (var j = 0; j < canvas.width; j++) {
var data = 0;
if (i >= 0 && j >= 0 && i < this.map.layers[1].height && j < this.map.layers[1].width) {
var data = this.map.layers[1].data[i * this.map.layers[1].width + j];
for (var k = 0; k < 1; k++) {
this.ctxt.fillStyle = 'red';
if (data != 0) {
obj.push({
x: j ,
y: i
});
this.ctxt.fillRect(
(j * this.setting_minblocksize[k]) ,
(i * this.setting_minblocksize[k]) ,
this.setting_minblocksize[k],
this.setting_minblocksize[k]
);
}
}
}
}
}
return obj;
}
My codepen link is right here
Thank you all for helping me!

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/

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);
}

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

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;
}
}

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