Snake.prototype.move = function() {
var head = this.head();
var newCoord = new Coord(head.pos);
console.log(head, newCoord);
console.log(head.pos, newCoord.pos);
this.segments.push(newCoord);
head.plus(this.dir);
if (this.growingCount > 0) {
this.growingCount -= 1;
} else {
this.segments.pop();
}
};
Coord()
Constructor and plus
function:
var Coord = SnakeGame.Coord = function(pos) {
this.pos = pos;
};
Coord.prototype.plus = function(dir) {
if (dir === "U") {
this.pos[0] -= 1;
} else if (dir === "D") {
this.pos[0] += 1;
} else if (dir === "R") {
this.pos[1] += 1;
} else if (dir === "L") {
this.pos[1] -= 1;
}
};
head()
returns the first segment in the segments
property on the Snake
instance.
The problem I'm seeing is that it seems like the two console.log
's are showing different results. The first line shows the Coord
objects with a pos
value of [3, 2] (which shouldn't be the case since head
hasn't been updated yet). The next console
line, outputs [3, 3] and [3, 3] (which should be the case).
What's going on? I feel like the error is staring at me in the face and I can't see it.
Clarification: Basically the head
and newCoord
when they're first instantiated, to have the same positions (unchanged). After the head.plus(this.dir);
line, head
should be one position further than newCoord
.
One execution of the method should have head.pos
be [3, 2] and newCoord
to have [3, 3]. Next execution, head.pos
should be [3, 1], another newCoord
should be [3, 2]. Does this make sense?