import java.util.*;import javax.swing.*;import java.awt.*;import java.awt.geom.*;import java.awt.event.*;
public class ArrayTest { public static void main(String args[]) { TestFrame frame = new TestFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); }}
class TestFrame extends JFrame { public TestFrame() { setSize(width, height); this.setBackground(Color.BLACK); Container c = getContentPane();
TestPanel panel = new TestPanel(); c.add(panel, BorderLayout.CENTER); }
int width = 600;
int height = 500;}
// TestPanel类实现移动的功能:当按键时,在头部增加新的节点,同时去掉尾部的节点class TestPanel extends JPanel implements KeyListener {
int sideX = 15;// 定义节点的宽和高;
int sideY = 15;
int panelWidth = 600;
int panelHeight = 500;
int d = 1;// 移动的步长;
int foodX;
int foodY;
TestNode n;
Rectangle2D foodRect;
Rectangle2D snakeHead;
LinkedList list = new LinkedList();
public TestPanel() { // 当游戏开始时,初始化蛇,食物的位置 for (int i = 0; i < 10; i++) { list.add(new TestNode(sideX + i, sideY));// 初始化node. }// 初试化蛇 foodX = 45; foodY = 60;// 初始化食物的位置 foodRect = new Rectangle2D.Double(foodX, foodY, 10, 10); snakeHead = new Rectangle2D.Double(); this.setSize(panelWidth, panelHeight); this.setBackground(Color.BLACK); setFocusable(true); addKeyListener(this); }
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; // 绘制食物和蛇 g2.setColor(Color.YELLOW); g2.fill(foodRect); Iterator it = list.iterator(); g2.setColor(Color.RED); while (it.hasNext()) { n = (TestNode) it.next(); g2.fillRect(n.nodeX * sideX, n.nodeY * sideY, sideX - 1, sideY - 1); } // 将蛇头填充为黄色. g2.setColor(Color.YELLOW); TestNode first = (TestNode) list.getFirst(); snakeHead = new Rectangle2D.Double(first.nodeX * sideX, first.nodeY * sideY, sideX - 1, sideX - 1); g2.fill(snakeHead); }
public void keyPressed(KeyEvent e) { int keycode = e.getKeyCode(); if (keycode == KeyEvent.VK_LEFT) { move(-d, 0);
} else if (keycode == KeyEvent.VK_DOWN) { move(0, d); } else if (keycode == KeyEvent.VK_UP) { move(0, -d); } else if (keycode == KeyEvent.VK_RIGHT) { move(d, 0); } }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
// 蛇的运动函数; public void move(int mx, int my) {
TestNode n = (TestNode) list.getFirst(); int maxX = this.getWidth() / sideX; int maxY = this.getHeight() / sideY; int x = n.nodeX; int y = n.nodeY; if ((x >= 0 && x < maxX - 0.5) && (y >= 0 && y < maxY)) { if (snakeHead.contains(foodRect)) { foodX = 1 + (int) (Math.random() * panelWidth / sideX) * 15; foodY = 1 + (int) (Math.random() * panelHeight / sideY) * 15; foodRect = new Rectangle2D.Double(foodX, foodY, 10, 10); list.addFirst(new TestNode(x + mx, y + my)); } else { list.addFirst(new TestNode(x + mx, y + my)); list.removeLast(); } } else { JOptionPane.showMessageDialog(null, "GAME OVER"); System.exit(0); } repaint(); }}
class TestNode {// 可以算做是节点类吧. int nodeX;
int nodeY;
public TestNode(int x, int y) { this.nodeX = x; this.nodeY = y; }}