📄 greedysnake.java
字号:
package com.snake;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.JTable;
/**
*
* @author 陈剑龙
*
*/
public class GreedySnake extends Frame {
public static final int GAME_WIDTH = 510; //蛇运动的宽度
public static final int GAME_HEIGHT = 616;//蛇运动的高度
public static int speed = 250;
public static boolean pause = false;
public static boolean over = false;
public static int score = 0;
private Panel controlPanel = new Panel();
Image offScreenImage = null;
List<Node> snakeList = null;
List<String> list = new ArrayList<String>();
Node n = null;
Snake snake = null;
Node food = null;
Thread thread = null;
Label titleLabel = new Label("贪吃蛇游戏说明");
Label scoreLabel = new Label("你的得分为:" + score + " ");
Label speedLabel = new Label(" 你的速度为:5 ");
Label rangeLabel = new Label(" 高 分 排 名 榜 ");
TextArea describeArea = new TextArea("", 13, 30, 3);
TextArea rangeArea = new TextArea("", 11, 30, 3);
public void initSnake() {
snake = new Snake(Dir.L, this);
pause = false;
over = false;
speed = 250;
score = 0;
snakeList = new ArrayList<Node>();
createSnake(5);//初始化贪吃蛇
food = Node.createFood(snakeList);//初始化食物
thread = new Thread(new PaintThread());
thread.start();
}
public void initPanel() {
titleLabel.setFont(new Font("楷体",Font.BOLD, 18));
scoreLabel.setFont(new Font("楷体",Font.BOLD, 18));
speedLabel.setFont(new Font("楷体",Font.BOLD, 18));
rangeLabel.setFont(new Font("楷体",Font.BOLD, 18));
describeArea.setFont(new Font("楷体",Font.BOLD, 13));
rangeArea.setFont(new Font("楷体",Font.BOLD, 13));
describeArea.setEnabled(false);
rangeArea.setEnabled(false);
describeArea.setText("1.学校:桂林电子科技大学\n"+
"\n2.学院:计算机与控制学院06级\n" +
"\n3.专业:软件工程\n" +
"\n4.姓名:陈剑龙\n" +
"\n5.PageUp加速,上限速度为9\n" +
"\n5.PageDown减速,下限速度为1\n" +
"\n7.P键或者空格键暂停\n" +
"\n8.R键重新开始,方向键改变方向\n" +
"\n9.每吃一食物就加100分\n" );
controlPanel.setBackground(Color.YELLOW.darker());
controlPanel.add(titleLabel);
controlPanel.add(describeArea);
controlPanel.add(scoreLabel);
controlPanel.add(speedLabel);
controlPanel.add(rangeLabel);
controlPanel.add(rangeArea);
}
public void readScore() {
try {
InputStream input = GreedySnake.class.getClassLoader().getResourceAsStream("score/score.txt");
BufferedReader buf = new BufferedReader(new InputStreamReader(input));
String temp = null;
while((temp = buf.readLine()) != null) {
String[] tempString = temp.split("[ \r]+");
for(int i=0; i<tempString.length; i++) {
list.add(tempString[i]);
}
}
updateRangeArea(); //更新排分榜
input.close();
buf.close();
}catch(Exception e){e.printStackTrace();}
}
public GreedySnake() {
this.setLocation(350, 200);
this.setSize(GAME_WIDTH + 250, GAME_HEIGHT);
this.setTitle("贪吃蛇");
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowActivated(WindowEvent e) {
repaint();
}
});
this.setIconImage(Toolkit.getDefaultToolkit().getImage(GreedySnake.class.getClassLoader().getResource("image/snake.gif")));
initPanel(); //初始化控制面板
this.setLayout(null);
this.add(controlPanel);
controlPanel.setBounds(GAME_WIDTH, 28, 250, GAME_HEIGHT);
this.setResizable(false);
this.setVisible(true);
this.addKeyListener(new KeyMonitor());
initSnake(); //初始化参数
readScore();
}
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.green);
for(int x=3; x<GAME_WIDTH; x+=11) { //绘制方格
for(int y=29; y<GAME_HEIGHT; y+=11) {
g.drawLine(x, y, x + GAME_WIDTH, y);
g.drawLine(x, y, x, y + GAME_HEIGHT);
}
}
snake.eatFood(snakeList, food);
food.draw(g);
snake.move(snakeList); //开始移动蛇
for(int i=0; i<snakeList.size(); i++) {
n = snakeList.get(i);
if(true == n.collidesWithSnake(snakeList)) { //判断是否撞到自身
over = true;
}
n.draw(g);
}
g.setColor(c);
}
/**
* 实现双缓冲,消除闪烁
*/
public void update(Graphics g) {
if (offScreenImage == null) {
offScreenImage = this.createImage(GAME_WIDTH, GAME_HEIGHT);
}
Graphics gOffScreen = offScreenImage.getGraphics();
Color c = gOffScreen.getColor();
gOffScreen.setColor(Color.BLACK.darker());
gOffScreen.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
gOffScreen.setColor(c);
paint(gOffScreen);
g.drawImage(offScreenImage, 0, 0, null);
}
/**
* 内部类实现线程
*/
private class PaintThread implements Runnable {
public void run() {
while (true) {
if(true == pause) continue; //达到暂停作用
if(true == over) {
gameOver();//结束游戏
return;
}
repaint();
try {
Thread.sleep(speed);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
*
* 重新开始贪吃蛇游戏
*/
public void restart() {
if(thread != null) {
thread.stop();
}
initSnake();//重新进行初始化
}
/**
* 排序
*/
private void sortArray(int [] array) {
for(int i=0; i<array.length; i++)
for(int j=i+1; j<array.length; j++) {
if(array[i] <= array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
Collections.swap(list, 3 * i + 1, 3 * j + 1);
Collections.swap(list, 3 * i, 3 * j);
}
}
}
/**
* 更新排分榜
*/
private void updateRangeArea() {
rangeArea.setText("");
rangeArea.append("昵称 分数 名次");
int length = list.size();
if(length >= 39) { //最多只显示前面的13名
length = 39;
}
for(int i=0; i<length; i++) {
if(i%3 == 0) rangeArea.append("\n");
rangeArea.append(list.get(i) + " ");
}
}
/**
* 游戏结束
*/
private void gameOver() {
JOptionPane.showMessageDialog(this, "游戏结束!","系统温馨提示",JOptionPane.INFORMATION_MESSAGE);
String name = "无名";
try {
name = JOptionPane.showInputDialog(this, "请输入你的昵称");
}catch(Exception e) {
e.printStackTrace();
}
finally {
if(name.trim().length() == 0) name = "无名";
list.add(name);
list.add("" + score);
list.add("" + (list.size() / 3 + 1));
int [] scoreArray = new int[list.size() / 3];
for(int i=0; i<scoreArray.length; i++)
scoreArray[i] = Integer.parseInt(list.get(3 * i + 1));
sortArray(scoreArray);
updateRangeArea(); //更新排名榜
}
}
/**
* 键盘事件处理的内部类
*/
private class KeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
snake.keyPressed(e);
}
}
/**
* 创建蛇身结点
* @param length = 产生的结点数
*/
public void createSnake(int length) {
int x = GAME_WIDTH / 2 + 2;
int y = GAME_HEIGHT / 2 - 3;
int temp = 0;
for(int i=0; i<length; i++) {
Node n = new Node(x + temp, y);
temp += Node.WIDTH + 1;
snakeList.add(n);
}
}
public static void main(String args[]) {
new GreedySnake();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -