Written by Lisa Yan
Handouts:
Graphics Reference
ArrayLists
BonusArrays: BorderSnake.java
This is a bonus program! It's meant to be a bit challenging, but completing this program will definitely help you write your final project.
Write a GraphicsProgram that moves a snake counter-clockwise around the border of the canvas.
This exercise assumes that you have completed BorderBox. A lot of the logic is similar (there's only one additional trick), so it really helps to know the general problem setup. If you haven't completed BorderBox yet, go implement it and come back.
In this program, as hinted above, you only need to move a single block to give the illusion that your entire snake has moved. Every time the snake moves, different blocks in the ArrayList now represent the new head and tail of the snake. How do you reliably access the head of your snake in your program?
One option you have is to define a logical invariant that the head of your snake will always be the 0th position of your ArrayList. An invariant is a computer science term that refers to something that can always assumed to be true. While there is no exact coding analogy, having this logical understanding will help the coder proceed through their program. The below code helps translate the logical invariant into the coding you need to do:
snake.remove(block); // the GRect you moved
snake.add(0, block); // becomes the new head
Note that defining this invariant will also help you figure out which position of the ArrayList will always be the tail of the snake.
Suppose we have the snake in the following configuration, where snakeDirection = NORTH:
In order to move the snake, do we care that part of the snake is still turning? (Hint: No, we don't) Given this information, how do we move a single block to the right position on the Canvas?
If you are stuck on what to do, try looking at this Border Snake Tutorial that implements one particular approach to this solution.
Congratulations, you now have a moving snake! :)