I am currently trying to create my own snake game in JS and having a hard time finding a solution to a really easy problem. So I want to apologize in advance if i annoy someone.
I want the said Snake to have a tail that is not longer than the variable 'length'. If it is the last Vector (storing positions of the tail part) in the Array should be deleted - aka the oldest one. Here's the updated code:
////Snake Class//////
function Snake() {
var scl = 20;
this.tail = [];
this.length = 5;
this.x = 0;
this.y = cnv.height / 2;
this.xspeed = 1;
this.yspeed = 0;
this.move = function (x, y) {
this.xspeed = x;
this.yspeed = y;
}
this.update = function () {
this.x = this.x + this.xspeed * scl;
this.y = this.y + this.yspeed * scl;
this.tail.unshift(createVector(this.x, this.y));
if(this.tail.length > this.length) {
this.tail.pop();
}
}
this.show = function (){
for (var i = 0; i < this.tail.length; i++) {
rect(this.tail[i].x, this.tail[i].y, scl, scl);
}
}
}
//////////Main Class///////////
function setup() {
cnv = createCanvas(windowWidth, windowHeight);
cnv.style('display','block');
background(249,49,119);
frameRate(10);
s = new Snake();
}
function draw() {
s.update();
s.show();
}
function keyPressed() {
if (keyCode == UP_ARROW) {
console.log("UP");
s.move(0, -1);
}else if (keyCode == DOWN_ARROW){
s.move(0,1);
} else if (keyCode == LEFT_ARROW){
s.move(-1, 0);
}else if (keyCode == RIGHT_ARROW){
s.move(1, 0);
}
}
/////Html///////
<html>
<head>
<script
src="https://cdnjs.cloudflare.com
/ajax/libs/p5.js/0.7.1/p5.min.js">
</script>
<script
src="https://cdnjs.cloudflare.com/ajax/
libs/p5.js/0.7.1/addons/p5.dom.min.js">
</script>
<script
src="https://cdnjs.cloudflare.com/ajax/
libs/p5.js/0.7.1/addons/p5.sound.min.js"></script>
<link rel = "stylesheet" href = "style.css" type = "text/css">
</head>
<body>
<script src = "Main.js"></script>
<script src = "Snake.js"></script>
</body>
</html>
///CSS///
html, body {
background-color: #919191;
height: 100%;
}
body {
margin: 0;
display: flex;
/*Centers the Game horizontally*/
justify-content: center;
/*Centers the Game vertically*/
align-items: center;
}