Storing Worm Information

The Worm class stores coordinate information about the worm in a circular buffer. It includes testing methods for checking if the player has clicked near the worm's head or body and includes methods for moving and drawing the worm.

The issues which make things more complicated include:

  • Having the worm grow in length up to a maximum size

  • Regulating the worm's movements to be semi-random so that it mostly moves in a forward direction

  • Getting the worm to go around obstacles in its path

Growing a Worm

The worm is grown by storing a series of Point objects in a cells[] array. Each point represents the location of one of the black circles of the worm's body (and the red circle for its head). As the worm grows, more points are added to the array until it is full; the worm's maximum extent is equivalent to the array's size.

Movement of the full-size worm is achieved by creating a new head circle at its front and removing the tail circle (if necessary). This removal frees up a space in the cells[] array where the point for the new head can be stored.

The growing and movement phases are illustrated by Figure 3-6, which shows how the cells[] array is gradually filled and then reused. The two indices, headPosn and tailPosn, make it simple to modify the head and tail of the worm, and nPoints records the length of the worm.

Worm data structures during growth and movement

Figure 3-6. Worm data structures during growth and movement ...

Get Killer Game Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.