import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class SnakeGame extends JFrame implements KeyListener {
private int stat = 1, direction = 0, bodylen = 6, headx = 7, heady = 8, tailx = 1, taily = 8, tail, foodx, foody,
food;// 初始化定义变量
public final int EAST = 1, WEST = 2, SOUTH = 3, NORTH = 4;// 方向常量
int[][] fillblock = new int[20][20];// 定义蛇身所占位置
public SnakeGame() {
// 构造函数
super("贪吃蛇");
setSize(510, 510);
setLocationRelativeTo(null);
setVisible(true);// 设定窗口属性
addKeyListener(this);// 添加监听
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 1; i <= 7; i++)
fillblock[i][8] = EAST;// 初始化蛇身属性
direction = EAST;// 方向初始化的设置
FoodLocate(); // 定位食物
while (stat == 1) {
fillblock[headx][heady] = direction;
switch (direction) {
case 1:
headx++;
break;
case 2:
headx--;
break;
case 3:
heady++;
break;
case 4:
heady--;
break;
}// 蛇头的前进
if (heady > 19 || headx > 19 || tailx > 19 || taily > 19 || heady < 0 || headx < 0 || tailx < 0 || taily < 0
|| fillblock[headx][heady] != 0) {
stat = 0;
break;
} // 判断游戏是否结束
try {
Thread.sleep(100);
} catch (InterruptedException e) {
} // 延迟
fillblock[headx][heady] = direction;
if (headx == foodx && heady == foody) {
// 吃到食物
FoodLocate();
food = 2;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
} // 延迟
}
if (food != 0)
food--;
else {
tail = fillblock[tailx][taily];
fillblock[tailx][taily] = 0;// 蛇尾的消除
switch (tail) {
case 1:
tailx++;
break;
case 2:
tailx--;
break;
case 3:
taily++;
break;
case 4:
taily--;
break;
}// 蛇尾的前进
}
repaint();
}
if (stat == 0)
JOptionPane.showMessageDialog(null, "GAME OVER", "Game Over", JOptionPane.INFORMATION_MESSAGE);
}
public void keyPressed(KeyEvent e) {
// 按键响应
int keyCode = e.getKeyCode();
if (stat == 1)
switch (keyCode) {
case KeyEvent.VK_UP:
if (direction != SOUTH)
direction = NORTH;
break;
case KeyEvent.VK_DOWN:
if (direction != NORTH)
direction = SOUTH;
break;
case KeyEvent.VK_LEFT:
if (direction != EAST)
direction = WEST;
break;
case KeyEvent.VK_RIGHT:
if (direction != WEST)
direction = EAST;
break;
}
}
public void keyReleased(KeyEvent e) {
}// 空函数
public void keyTyped(KeyEvent e) {
} // 空函数
public void FoodLocate() {
// 定位食物坐标
do {
Random r = new Random();
foodx = r.nextInt(20);
foody = r.nextInt(20);
} while (fillblock[foodx][foody] != 0);
}
public void paint(Graphics g) {
// 画图
super.paint(g);
g.setColor(Color.BLUE);
for (int i = 0; i < 20; i++)
for (int j = 0; j < 20; j++)
if (fillblock[i][j] != 0)
g.fillRect(25 * i + 5, 25 * j + 5, 24, 24);
g.setColor(Color.RED);
g.fillRect(foodx * 25 + 5, foody * 25 + 5, 24, 24);
}
public static void main(String[] args) {
// 主程序
SnakeGame application = new SnakeGame();
}
}