// Snake.java // Written in class on Tue 13-Oct-09 // As with any code that is written in real time in class, // this may contain a bug here or there and in any case // cuts some corners on style (to wit: no comments!). import java.awt.*; import javax.swing.*; import java.util.*; public class Snake extends JComponentWithEvents { private boolean debug = true; private int rows = 10; private int cols = 10; private int[][] snake = new int[rows][cols]; private int dir = UP; private int headRow, headCol; private int foodRow, foodCol; public void moveSnake() { int snakeLength = snake[headRow][headCol]; int newHeadRow = headRow, newHeadCol = headCol; if (dir == UP) newHeadRow--; else if (dir == DOWN) newHeadRow++; else if (dir == RIGHT) newHeadCol++; else newHeadCol--; if ((newHeadRow < 0) || (newHeadRow >= rows) || (newHeadCol < 0) || (newHeadCol >= cols)) { die(); } else if (snake[newHeadRow][newHeadCol] > 0) { die(); } else if ((newHeadRow == foodRow) && (newHeadCol == foodCol)) { headRow = newHeadRow; headCol = newHeadCol; snake[newHeadRow][newHeadCol] = snakeLength+1; placeFood(); } else { for (int row=0; row 0) --snake[row][col]; snake[newHeadRow][newHeadCol] = snakeLength; headRow = newHeadRow; headCol = newHeadCol; } } public void die() { reset(); } public void keyPressed(char key) { if (key == 'm') moveSnake(); else if (key == UP) dir = UP; else if (key == DOWN) dir = DOWN; else if (key == RIGHT) dir = RIGHT; else if (key == LEFT) dir = LEFT; } public void timerFired() { moveSnake(); } public void start() { reset(); } public void reset() { for (int row=0; row 0) { page.setColor(Color.blue); page.fillOval(left, top, right-left, bottom-top); if (debug) { page.setColor(Color.white); page.setFont(new Font("Arial", Font.BOLD, 16)); drawCenteredString(page, ""+snake[row][col], left, top, right-left, bottom-top); } } } public void paint(Graphics2D page) { for (int row=0; row