java实现贪吃蛇

import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.LinkedList;


import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class Work2 extends JFrame {
private static LinkedList snake = new LinkedList<>();// 蛇的坐标
private static LinkedList jLabels = new LinkedList<>();// 蛇身
private boolean flag = false;


private int dz = 62;// 初始食物坐标
private int fx = 1;// 初始方向


static {
snake.add(61);
snake.add(60);// 初始蛇坐标
jLabels.add(new JLabel());
jLabels.add(new JLabel());// C初始蛇身


}


public Work2() {
this.setTitle("贪吃蛇");
this.setSize(415, 438);
this.setLocation(100, 90);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


this.setLayout(null);


}


void init() {
JPanel jPanel = new JPanel();// 地图
jPanel.setLayout(null);
jPanel.setSize(400, 400);
jPanel.setLocation(0, 0);
jPanel.setBackground(Color.BLACK);
JLabel jLabel = new JLabel();// 食物
// 通过监听键盘来确定上,下,左,右方向
this.addKeyListener(new KeyListener() {


@Override
public void keyTyped(KeyEvent e) {


}


@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN:
fx = fx == -20 ? -20 : 20;// 如果方向相反则不变
System.out.println("2");
break;
case KeyEvent.VK_UP:
fx = fx == 20 ? 20 : -20;
break;
case KeyEvent.VK_LEFT:
fx = fx == 1 ? 1 : -1;
break;
case KeyEvent.VK_RIGHT:
fx = fx == -1 ? -1 : 1;
break;
default:
break;
}


}


@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub


}
});


jPanel.add(jLabel);
jPanel.add(jLabels.get(0));


jPanel.add(jLabels.get(1));
this.add(jPanel);
this.setVisible(true);


while (true) {


snake.addFirst(snake.get(0) + fx);
// 蛇头碰到墙游戏结束
if (snake.get(0) < 0 || snake.get(0) > 399 || (fx == 1 && snake.get(0) % 20 == 0)
|| (fx == -1 && snake.get(0) % 20 == 19)) {
JOptionPane.showMessageDialog(null, "游戏结束");


return;


}
// 蛇头碰到蛇身
for (int i = 1; i < snake.size() - 1; i++) {


if (snake.get(0).equals(snake.get(i))) {
JOptionPane.showMessageDialog(null, "游戏结束");
return;
}
}
// 判读是否吃到食物
if (snake.get(0) == dz) {
flag = true;
// 吃到的操作
jLabels.addFirst(new JLabel());
jPanel.add(jLabels.get(0));
} else {
// 没吃的操作
snake.removeLast();


}
for (int i = 0; i < snake.size(); i++) {
// 显现蛇
drow(jLabels.get(i), snake.get(i), Color.green);
}
try {
// 速度
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 重新产生食物
if (flag) {
flag = false;
while (true) {
int random = (int) (Math.random() * 399);
if (!snake. contains(random)) {
dz = random;


break;
}


}
drow(jLabel, dz, Color.YELLOW);
}


}


}


// 每块蛇身的坐标大小
private void drow(JLabel jLabel, int a, Color color) {
jLabel.setOpaque(true);
jLabel.setBackground(color);
jLabel.setSize(18, 18);
jLabel.setLocation(a % 20 * 20, a / 20 * 20);


}


public static void main(String[] args) {
new Work2().init();
}


}

你可能感兴趣的:(游戏)