# Midterm Game

Concept:

I thought the snake game will be fun to implement – it is simple, fun, and can be done easily using OOP. It turned out to be a little more difficult than I expected it to be. Nevertheless, it was satisfying to implement a game I grew up playing 🙂

Challenges:

One of the most difficult parts was figuring out the algorithm for the movement of snake. It took me a lot of time. The way the algorithm works is that it the snake head (which is a class of itself) moves independently. It changes the direction based on the input key. The rest of the body of the snake is stored in an array. I run a for loop starting from the last index of the array and assign the last element’s x and y coordinate to the second last element. I do so until the second element’s x and y coordinate is equal to the first element’s values. Then I update the the first element’s values basis the position of the head for which I have 4 if conditions.

Another smaller issue I ran into was not being able to make a class which inherits from Arrays. I am not sure if that is possible in JS.

This is the bit on which I spent most of my time.

```if(this.direction=="RIGHT"){
for(let i=(g.arr.length)-1; i>1; i--){  //g is the snake head
print("LOK");
g.arr[i].row = g.arr[i-1].row;
g.arr[i].col = g.arr[i-1].col;
g.arr[i].display();
}
g.arr.row = this.row+0.5;
g.arr.col = this.col+0.5;
g.arr.display();
}

else if(this.direction=="LEFT"){
for(let i=(g.arr.length)-1; i>1; i--){
print("LOK");
g.arr[i].row = g.arr[i-1].row;
g.arr[i].col = g.arr[i-1].col;
g.arr[i].display();
}
g.arr.row = this.row+0.5;
g.arr.col = this.col+0.5;
g.arr.display();
}
else if(this.direction=="UP"){
for(let i=(g.arr.length)-1; i>1; i--){
print("LOK");
g.arr[i].row = g.arr[i-1].row;
g.arr[i].col = g.arr[i-1].col;
g.arr[i].display();
}
g.arr.row = this.row+0.5;
g.arr.col = this.col+0.5;
g.arr.display();
}
else if(this.direction=="DOWN"){
for(let i=(g.arr.length)-1; i>1; i--){
g.arr[i].row = g.arr[i-1].row;
g.arr[i].col = g.arr[i-1].col;
g.arr[i].display();
}
g.arr.row = this.row+0.5;
g.arr.col = this.col+0.5;
g.arr.display();
}