今天玩了一下swing,看到其中有网格布局模式,便想到用其实现一个简易的贪吃蛇。代码写起来也是简短精悍。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.Random;
public class MySnake {
static final int width = 20; static final int height = 20; static int len = 3; static int[] xArr = new int[400]; static int[] yArr = new int[400]; static int foodX = 13; static int foodY = 13; static int speed = 50; static int dis = KeyEvent.VK_RIGHT; static Random random = new Random();
public static void main(String[] args) { JFrame frame = new JFrame(); JPanel[][] jPanels = new JPanel[width][height]; xArr[0] = 5;yArr[0] = 5; xArr[1] = 5;yArr[0] = 4; xArr[2] = 5;yArr[0] = 3; frame.setTitle("Snake"); frame.setLayout(new GridLayout(20, 20, 0, 0)); frame.setBounds(1000, 500, 300, 300); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { jPanels[i][j] = new JPanel(); frame.add(jPanels[i][j]); } } paint(jPanels); new Thread(() -> { try { for (; ; ) { int xx = xArr[len - 1];int yy = yArr[len - 1]; for (int i = len - 1; i > 0; i--) { xArr[i] = xArr[i - 1]; yArr[i] = yArr[i - 1]; } switch (dis) { case KeyEvent.VK_LEFT: yArr[0] -= 1; if (yArr[0] < 0) yArr[0] = 19; break; case KeyEvent.VK_UP: xArr[0] -= 1; if (xArr[0] < 0) xArr[0] = 19; break; case KeyEvent.VK_RIGHT: yArr[0] += 1; if (yArr[0] > 19) yArr[0] = 0; break; case KeyEvent.VK_DOWN: xArr[0] += 1; if (xArr[0] > 19) xArr[0] = 0; break; } for (int i = 1; i < len; i++) { if (xArr[0] == xArr[i] && yArr[0] == yArr[i]) { throw new RuntimeException(); } } if (xArr[0] == foodX && yArr[0] == foodY) { len++; xArr[len - 1] = xx; yArr[len - 1] = yy; foodX = random.nextInt(20); foodY = random.nextInt(20); } paint(jPanels); Thread.sleep(speed); } } catch (InterruptedException e) { throw new RuntimeException(e); } }).start(); frame.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { dis = e.getKeyCode(); } @Override public void keyReleased(KeyEvent e) {} }); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
private static void paint(JPanel[][] jPanels) { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { jPanels[i][j].setBackground(Color.WHITE); } } for (int i = 0; i < len; i++) { jPanels[xArr[i]][yArr[i]].setBackground(Color.BLACK); } jPanels[foodX][foodY].setBackground(Color.RED); }
}
|
运行效果如下: