Here is the beginning of our code for the class CarpetSnakePanel:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CarpetSnakePanel extends JPanel {
/*
Steer a snake with the arrow keys.
*/
// instance variables
int [] xCorner = new int [100];
int [] yCorner = new int [100];
// constructor
public CarpetSnakePanel ( ) {
setBackground(Color.white);
for (int i=0; i<100; i++) {
xCorner[i] = -800 + 10*i;
yCorner[i] = 200;
}
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
moveSquare(evt);
}
});
}
public void paintComponent (Graphics g) {
// draw square
super.paintComponent(g);
requestFocus();
for (int i=0; i<100; i++) {
switch (i%4) {
case 0: g.setColor(Color.orange); break;
case 1: g.setColor(Color.yellow); break;
case 2: g.setColor(Color.black); break;
case 3: g.setColor(Color.black); break;
}
g.fillRect(xCorner[i], yCorner[i], 10, 10);
}
}
The method moveSquare is missing from this class.
Notice how arrays are used to store the coordinates of the upper-left corner of 100 squares each 10 pixels wide and placed side by side in a long line. Initially a large part of the snake is not shown in the window - all squares with a negative xCorner (see the constructor method where the initial coordinates of the squares are declared).
The paintComponent method displays the 100 squares in the window and uses a switch-statement to colour them in a repeating pattern. The colours were chosen to most closely reflect the actual colours of the Queensland carpet snake (well, within the bounds of artistic imagination). The coordinates of the head of the snake are at index position 99.
Notice also the requestFocus() statement in the paintComponent method. This is needed so that the panel can have the focus when keys are pressed. Without this statement the panel would not respond to the keystrokes after losing the focus.
Now comes the tricky bit. We need to write the code for the method moveSquare which is invoked whenever a key on the keyboard is pressed. In this code we need to detect if the key pressed is one of the arrow keys, and if so perform the required actions. This will involve moving the head of the snake 10 pixels in the given direction; as well, each portion of the tail will move to the position of that adjacent square which is nearer to the head.
Try this before looking at the next hint.
Next Hint