This article recommends a classic mini game implemented by Java: Snake, I believe everyone has played it, how to achieve it?
Reproduction image:
Without further ado, just present the code:
1.
public class GreedSnake { public static void main(String[] args) { SnakeModel model = new SnakeModel(20,30); SnakeControl control = new SnakeControl(model); SnakeView view = new SnakeView(model,control); //Add an observer and let the view become the observer of the model model.addObserver(view); (new Thread(model)).start(); }}2.
package mvcTest;//SnakeControl.javaimport java.awt.event.KeyEvent;import java.awt.event.KeyListener;public class SnakeControl implements KeyListener{ SnakeModel model; public SnakeControl(SnakeModel model){ this.model = model; } public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (model.running){ // The processed key switch (keyCode) { case KeyEvent.VK_UP: model.changeDirection(SnakeModel.UP); break; case KeyEvent.VK_DOWN: model.changeDirection(SnakeModel.DOWN); break; case KeyEvent.VK_LEFT: model.changeDirection(SnakeModel.LEFT); break; case KeyEvent.VK_RIGHT: model.changeDirection(SnakeModel.RIGHT); break; case KeyEvent.VK_ADD: case KeyEvent.VK_PAGE_UP: model.speedUp(); break; case KeyEvent.VK_SUBTRACT: case KeyEvent.VK_PAGE_DOWN: model.speedDown(); break; case KeyEvent.VK_SPACE: case KeyEvent.VK_P: model.changePauseState(); break; default: } } // A key is processed in any case, and the key causes the game to restart if (keyCode == KeyEvent.VK_R || keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_ENTER) { model.reset(); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { }}3.
package mvcTest;//SnakeModel.javaimport javax.swing.*;import java.util.Arrays;import java.util.LinkedList;import java.util.Observable;import java.util.Observable;import java.util.Random;class SnakeModel extends Observable implements Runnable { boolean[][] matrix; // Indicate whether there is a snake body or food at the position LinkedList nodeArray = new LinkedList(); // Snake body Node food; int maxX; int maxY; int direction = 2; // The direction of the snake's running boolean running = false; // Run state int timeInterval = 200; // Time interval, millisecond double speedChangeRate = 0.75; // Each time the speed change rate boolean paused = false; // Pause flag int score = 0; // Score int countMove = 0; // Number of times you move before eating food// UP and DOWN should be even // RIGHT and LEFT should be odd public static final int UP = 2; public static final int DOWN = 4; public static final int LEFT = 1; public static final int RIGHT = 3; public SnakeModel( int maxX, int maxY) { this.maxX = maxX; this.maxY = maxY; reset(); } public void reset(){ direction = SnakeModel.UP; // Direction of the snake running timeInterval = 200; // Time interval, millisecond paused = false; // Pause flag score = 0; // Score countMove = 0; // Number of times before eating food// initial matirx, all clear 0 matrix = new boolean[maxX][]; for (int i = 0; i < maxX; ++i) { matrix[i] = new boolean[maxY]; Arrays.fill(matrix[i], false); } // initial the snake // Initial the snake body, if there are more than 20 horizontal positions, the length is 10, otherwise it is half of the horizontal position int initArrayLength = maxX > 20 ? 10 : maxX / 2; nodeArray.clear(); for (int i = 0; i < initArrayLength; ++i) { int x = maxX / 2 + i;//maxX is initialized to 20 int y = maxY / 2; //maxY is initialized to 30 //nodeArray[x,y]: [10,15]-[11,15]-[12,15]~~[20,15] //The default running direction is up, so at the beginning of the game nodeArray becomes: // [10,14]-[10,15]-[11,15]-[12,15]~~[19,15] nodeArray.addLast(new Node(x, y)); matrix[x][y] = true; } // Create food food = createFood(); matrix[food.x][food.y] = true; } public void changeDirection(int newDirection) { // The changed direction cannot be in the same direction or reversed to the original direction if (direction % 2 != newDirection % 2) { direction = newDirection; } } public boolean moveOn() { Node n = (Node) nodeArray.getFirst(); int x = nx; int y = ny; // Increase and decrease the coordinate value according to the direction switch (direction) { case UP: y--; break; case DOWN: y++; break; case LEFT: x--; break; case RIGHT: x++; break; } // If the new coordinate falls within the valid range, process if ((0 <= x && x < maxX) && (0 <= y && y < maxY)) { if (matrix[x][y]) { // If there is something on the point in the new coordinate (snake body or food) if (x == food.x && y == food.y) { // Eat food and succeed nodeArray.addFirst(food); // Giving a length from the snake head// The score rule is related to the number and speed of movement changes direction int scoreGet = (10000 - 200 * countMove) / timeInterval; score += scoreGet > 0 ? scoreGet : 10; countMove = 0; food = createFood(); // Create a new food matrix[food.x][food.y] = true; // Set the food location return true; } else // Eat the snake body itself, fail return false; } else { // If there is nothing on the point in the new coordinate (snake body), move the snake body nodeArray.addFirst(new Node(x, y)); matrix[x][y] = true; n = (Node) nodeArray.removeLast(); matrix[nx][ny] = false; countMove++; return true; } } return false; // Touch the edge, fail} public void run() { running = true; while (running) { try { Thread.sleep(timeInterval); } catch (Exception e) { break; } if (!paused) { if (moveOn()) { setChanged(); // Model notifies the View data that has been updated notifyObservers(); } else { JOptionPane.showMessageDialog(null, "you failed", "Game Over", JOptionPane.INFORMATION_MESSAGE); break; } } } running = false; } private Node createFood() { int x = 0; int y = 0; // Random get the position in a valid area that does not overlap with the snake body and food do { Random r = new Random(); x = r.nextInt(maxX); y = r.nextInt(maxY); } while (matrix[x][y]); return new Node(x, y); } public void speedUp() { timeInterval *= speedChangeRate; } public void speedDown() { timeInterval /= speedChangeRate; } public void changePauseState() { paused = !paused; } public String toString() { String result = ""; for (int i = 0; i < nodeArray.size(); ++i) { Node n = (Node) nodeArray.get(i); result += "[" + nx + "," + ny + "]"; } return result; }}class Node { int x; int y; Node(int x, int y) { this.x = x; this.y = y; }}4.
package mvcTest;//SnakeView.javaimport javax.swing.*;import java.awt.*;import java.util.Iterator;import java.util.LinkedList;import java.util.Observable;import java.util.Observable;import java.util.Observable;import java.util.Observable;import java.util.Observer;public class SnakeView implements Observer { SnakeControl control = null; SnakeModel model = null; JFrame mainFrame; Canvas paintCanvas; JLabel labelScore; public static final int canvasWidth = 200; public static final int canvasHeight = 300; public static final int nodeWidth = 10; public static final int nodeHeight = 10; public SnakeView(SnakeModel model, SnakeControl control) { this.model = model; this.control = control; mainFrame = new JFrame("GreedSnake"); Container cp = mainFrame.getContentPane(); // Create the top score display labelScore = new JLabel("Score:"); cp.add(labelScore, BorderLayout.NORTH); // Create the middle game display area paintCanvas = new Canvas(); paintCanvas.setSize(canvasWidth + 1, canvasHeight + 1); paintCanvas.addKeyListener(control); cp.add(paintCanvas, BorderLayout.CENTER); // Create the help bar below JPanel panelButtom = new JPanel(); panelButtom.setLayout(new BorderLayout()); JLabel labelHelp; labelHelp = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER); panelButtom.add(labelHelp, BorderLayout.NORTH); labelHelp = new JLabel("ENTER or R or S for start;", JLabel.CENTER); panelButtom.add(labelHelp, BorderLayout.CENTER); labelHelp = new JLabel("SPACE or P for pause", JLabel.CENTER); panelButtom.add(labelHelp, BorderLayout.SOUTH); cp.add(panelButtom, BorderLayout.SOUTH); mainFrame.addKeyListener(control); mainFrame.pack(); mainFrame.setResizable(false); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setVisible(true); } void repaint() { Graphics g = paintCanvas.getGraphics(); //draw background g.setColor(Color.WHITE); g.fillRect(0, 0, canvasWidth, canvasHeight); // draw the snake g.setColor(Color.BLACK); LinkedList na = model.nodeArray; Iterator it = na.iterator(); while (it.hasNext()) { Node n = (Node) it.next(); drawNode(g, n); } // draw the food g.setColor(Color.RED); Node n = model.food; drawNode(g, n); updateScore(); } private void drawNode(Graphics g, Node n) { g.fillRect(nx * nodeWidth, ny * nodeHeight, nodeWidth - 1, nodeHeight - 1); } public void updateScore() { String s = "Score: " + model.score; labelScore.setText(s); } public void update(Observable o, Object arg) { repaint(); }}The purpose of this article is to take you to reminisce about the classics, but the more important purpose is to help you learn Java programming well.