JavaScript Snake 10-09-2015, 01:20 AM
#1
So, I'm trying to build Snake with JavaScript, but I've come across a slight problem - I'm using window.setInterval with an interval of 4 miliseconds to constantly check if a collision has occurred, but I'm sure there's a better way; using this makes everything repeatedly happen once the collision has been detected - an infinite number of random circles are generated [at least, until Chrome crashes, which is at around 5000 circles
], etc. How else would I do this?
Here's my code...
], etc. How else would I do this?Here's my code...
Code:
var canvas = document.querySelector('.canvas');
Crafty.init(500, 250, canvas);
Crafty.c('Square', {
init: function () {
this.addComponent('2D, Canvas, Color, DOM, Image, HTML');
this.w = 25;
this.h = 25;
},
coordinates: function (x, y) {
this.x = x;
this.y = y;
return this;
}
});
var select = document.querySelector('.num');
var arr = [];
var i;
for (i = 0; i <= 1000; i += 1) {
arr[i] = document.createElement('OPTION');
arr[i].innerHTML = i;
}
var j;
for (j = 0; j <= 1000; j += 1) {
select.appendChild( arr[j] );
}
var start = document.querySelector('.submit');
var score = 0;
var playerCircle = Crafty.e('Square, Fourway').coordinates(236, 90).fourway(3.5).append('<div style="width: 25px; height: 25px; background: #00CCFF; border-radius: 100%;"></div>');
var generateCircle = function () {
var randomCircle = Crafty.e('Square').coordinates(Math.floor((Math.random() * 475) + 1), Math.floor((Math.random() * 225) + 1)).append('<div style="width: 10px; height: 10px; background: #333; border-radius: 100%;"></div>');
return randomCircle;
};
var displayedScore = document.querySelector('.score');
var randomCircle = generateCircle();
var Collision = function () {
if (playerCircle.x < randomCircle.x + randomCircle.w && playerCircle.x + playerCircle.w > randomCircle.x && playerCircle.y < randomCircle.y + randomCircle.h && playerCircle.h + playerCircle.y > randomCircle.y) {
return true;
} else {
return false;
}
};
var isCollided = function () {
if (Collision()) {
randomCircle.css('display', 'none');
generateCircle();
score = score + 1;
displayedScore.innerHTML = score + ' circles';
}
};
window.setInterval(isCollided, select.value);



![[+]](https://sinister.li/images/modern/collapse_collapsed.png)


