Concept and Approach:
For this assignment I was inspired by the snakes game we used to play as kids especially since I used to play one that grew with blocks, very similar to the way the cells look in our cellular automata sketches. I tried to initially have the cells within the snake interact with one another based on the game of life rules, but that did not depict what I was envisioning. So I decided to have the background be based on the game of life rules while the snake travels around the canvas following the mouse. I also added an element of interactivity wherein the cells die or come to life based on their condition when pressed on by the user.
The method I followed was pretty simple I created a grid of cells whose visibility (life) is determined by the condition of their neighboring cells. I followed the same methodology we did in class creating a loop that checks through all the cells in the rows and columns and then applies the rules of game of life.
For the snake, I created a class that has several functions. First of all in its constructor it has the body of the snake as an array where the length of the cells that make up the body are collected. The length is limited to 20 cells, and the cells are adapted from the ones used to make up the game of life mechanism in the background. The snake grows as it follows the mouse and remains as one single cell when the mouse is still. I used the unshift() method which I learned is a method that works on an array similar to pop() and push() except the unshift() adds new elements to the beginning of an array overwriting the original array, which is what I need to be done to have the head of the snake constantly following the mouse’s direction.
update() { // Copy the current head position of the snake let head = this.body[0].copy(); // Asssign position of the mouse in terms of board cells let mousePos = createVector(mouseX / cellSize, mouseY / cellSize); // Calculate the direction vector from the head to the mouse position and limit its magnitude to 1 let direction = p5.Vector.sub(mousePos, head).limit(1); // update head position based on direction vector head.add(direction); // Add the updated head to the front of the snake's body this.body.unshift(head); // Keeping the body shorter than 20 segments if (this.body.length > 20) { this.body.pop(); } }
Reflection and Ideas:
What I find interesting about this code is the element of interactivity that makes it look as though the snake is consuming the cells or leading to their explosion in some way or another. This was pretty easy to achieve but I think it could be changed to make the game look more realistic. As of now, pressing on the cells just switches their condition from alive to dead or vice versa. For future improvements I could work on making the relationship between the snake and the cells in the background seem more uniform and less separate.