自己寫(xiě)著玩的,很簡(jiǎn)單,你試一試哦...
“專(zhuān)業(yè)、務(wù)實(shí)、高效、創(chuàng)新、把客戶的事當(dāng)成自己的事”是我們每一個(gè)人一直以來(lái)堅(jiān)持追求的企業(yè)文化。 創(chuàng)新互聯(lián)公司是您可以信賴的網(wǎng)站建設(shè)服務(wù)商、專(zhuān)業(yè)的互聯(lián)網(wǎng)服務(wù)提供商! 專(zhuān)注于成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、軟件開(kāi)發(fā)、設(shè)計(jì)服務(wù)業(yè)務(wù)。我們始終堅(jiān)持以客戶需求為導(dǎo)向,結(jié)合用戶體驗(yàn)與視覺(jué)傳達(dá),提供有針對(duì)性的項(xiàng)目解決方案,提供專(zhuān)業(yè)性的建議,創(chuàng)新互聯(lián)建站將不斷地超越自我,追逐市場(chǎng),引領(lǐng)市場(chǎng)!
主要用了javax.swing.Timer這個(gè)類(lèi):
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class MainClass extends JFrame {
ControlSnake control;
Toolkit kit;
Dimension dimen;
public static void main(String[] args) {
new MainClass("my snake");
}
public MainClass(String s) {
super(s);
control = new ControlSnake();
control.setFocusable(true);
kit = Toolkit.getDefaultToolkit();
dimen = kit.getScreenSize();
add(control);
setLayout(new BorderLayout());
setLocation(dimen.width / 3, dimen.height / 3);// dimen.width/3,dimen.height/3
setSize(FWIDTH, FHEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public static final int FWIDTH = 315;
public static final int FHEIGHT = 380;
}
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import java.util.Random;
@SuppressWarnings("serial")
public class ControlSnake extends JPanel implements ActionListener {
Random rand;
ArrayListPoint list, listBody;
String str, str1;
static boolean key;
int x, y, dx, dy, fx, fy, flag;
int snakeBody;
int speed;
public ControlSnake() {
snakeBody = 1;
str = "上下左右方向鍵控制 P鍵暫停...";
str1 = "現(xiàn)在的長(zhǎng)度為:" + snakeBody;
key = true;
flag = 1;
speed = 700;
rand = new Random();
list = new ArrayListPoint();
listBody = new ArrayListPoint();
x = 5;
y = 5;
list.add(new Point(x, y));
listBody.add(list.get(0));
dx = 10;
dy = 0;
fx = rand.nextInt(30) * 10 + 5;// 2
fy = rand.nextInt(30) * 10 + 5;// 2
setBackground(Color.WHITE);
setSize(new Dimension(318, 380));
final Timer time = new Timer(speed, this);
time.start();
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 37) {
dx = -10;
dy = 0;
} else if (e.getKeyCode() == 38) {
dx = 0;
dy = -10;
} else if (e.getKeyCode() == 39) {
dx = 10;
dy = 0;
} else if (e.getKeyCode() == 40) {
dx = 0;
dy = 10;
} else if (e.getKeyCode() == 80) {
if (flag % 2 == 1) {
time.stop();
}
if (flag % 2 == 0) {
time.start();
}
flag++;
}
}
});
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, 400, 400);
g.setColor(Color.DARK_GRAY);
g.drawLine(3, 3, 305, 3);
g.drawLine(3, 3, 3, 305);
g.drawLine(305, 3, 305, 305);
g.drawLine(3, 305, 305, 305);
g.setColor(Color.PINK);
for (int i = 0; i listBody.size(); i++) {
g.fillRect(listBody.get(i).x, listBody.get(i).y, 9, 9);
}
g.fillRect(x, y, 9, 9);
g.setColor(Color.ORANGE);
g.fillRect(fx, fy, 9, 9);
g.setColor(Color.DARK_GRAY);
str1 = "現(xiàn)在的長(zhǎng)度為:" + snakeBody;
g.drawString(str, 10, 320);
g.drawString(str1, 10, 335);
}
public void actionPerformed(ActionEvent e) {
x += dx;
y += dy;
if (makeOut() == false) {
JOptionPane.showMessageDialog(null, "重新開(kāi)始......");
speed = 700;
snakeBody = 1;
x = 5;
y = 5;
list.clear();
list.add(new Point(x, y));
listBody.clear();
listBody.add(list.get(0));
dx = 10;
dy = 0;
}
addPoint(x, y);
if (x == fx y == fy) {
speed = (int) (speed * 0.8);//速度增加參數(shù)
if (speed 200) {
speed = 100;
}
fx = rand.nextInt(30) * 10 + 5;// 2
fy = rand.nextInt(30) * 10 + 5;// 2
snakeBody++;// 2
} // 2
repaint();
}
public void addPoint(int xx, int yy) {
// 動(dòng)態(tài)的記錄最新發(fā)生的50步以內(nèi)的移動(dòng)過(guò)的坐標(biāo)
// 并畫(huà)出最新的snakeBody
if (list.size() 100) {//蛇身長(zhǎng)度最長(zhǎng)為100
list.add(new Point(xx, yy));
} else {
list.remove(0);
list.add(new Point(xx, yy));
}
if (snakeBody == 1) {
listBody.remove(0);
listBody.add(0, list.get(list.size() - 1));
} else {
listBody.clear();
if (list.size() snakeBody) {
for (int i = list.size() - 1; i 0; i--) {
listBody.add(list.get(i));
}
} else {
for (int i = list.size() - 1; listBody.size() snakeBody; i--) {
listBody.add(list.get(i));
}
}
}
}
public boolean makeOut() {
if ((x 3 || y 3) || (x 305 || y 305)) {
return false;
}
for (int i = 0; i listBody.size() - 1; i++) {
for (int j = i + 1; j listBody.size(); j++) {
if (listBody.get(i).equals(listBody.get(j))) {
return false;
}
}
}
return true;
}
}
用MVC方式實(shí)現(xiàn)的貪吃蛇游戲,共有4個(gè)類(lèi)。運(yùn)行GreedSnake運(yùn)行即可。主要是觀察者模式的使用,我已經(jīng)添加了很多注釋了。
1、
/*
* 程序名稱:貪食蛇
* 原作者:BigF
* 修改者:algo
* 說(shuō)明:我以前也用C寫(xiě)過(guò)這個(gè)程序,現(xiàn)在看到BigF用Java寫(xiě)的這個(gè),發(fā)現(xiàn)雖然作者自稱是Java的初學(xué)者,
* 但是明顯編寫(xiě)程序的素養(yǎng)不錯(cuò),程序結(jié)構(gòu)寫(xiě)得很清晰,有些細(xì)微得地方也寫(xiě)得很簡(jiǎn)潔,一時(shí)興起之
* 下,我認(rèn)真解讀了這個(gè)程序,發(fā)現(xiàn)數(shù)據(jù)和表現(xiàn)分開(kāi)得很好,而我近日正在學(xué)習(xí)MVC設(shè)計(jì)模式,
* 因此嘗試把程序得結(jié)構(gòu)改了一下,用MVC模式來(lái)實(shí)現(xiàn),對(duì)源程序得改動(dòng)不多。
* 我同時(shí)也為程序增加了一些自己理解得注釋?zhuān)M麑?duì)大家閱讀有幫助。
*/
package mvcTest;
/**
* @author WangYu
* @version 1.0
* Description:
* /pre
* Create on :Date :2005-6-13 Time:15:57:16
* LastModified:
* History:
*/
public class GreedSnake {
public static void main(String[] args) {
SnakeModel model = new SnakeModel(20,30);
SnakeControl control = new SnakeControl(model);
SnakeView view = new SnakeView(model,control);
//添加一個(gè)觀察者,讓view成為model的觀察者
model.addObserver(view);
(new Thread(model)).start();
}
}
-------------------------------------------------------------
2、
package mvcTest;
//SnakeControl.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
* MVC中的Controler,負(fù)責(zé)接收用戶的操作,并把用戶操作通知Model
*/
public class SnakeControl implements KeyListener{
SnakeModel model;
public SnakeControl(SnakeModel model){
this.model = model;
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (model.running){ // 運(yùn)行狀態(tài)下,處理的按鍵
switch (keyCode) {
case KeyEvent.VK_UP:
model.changeDirection(SnakeModel.UP);
break;
case KeyEvent.VK_DOWN:
model.changeDirection(SnakeModel.DOWN);
break;
case KeyEvent.VK_LEFT:
model.changeDirection(SnakeModel.LEFT);
break;
case KeyEvent.VK_RIGHT:
model.changeDirection(SnakeModel.RIGHT);
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_PAGE_UP:
model.speedUp();
break;
case KeyEvent.VK_SUBTRACT:
case KeyEvent.VK_PAGE_DOWN:
model.speedDown();
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
model.changePauseState();
break;
default:
}
}
// 任何情況下處理的按鍵,按鍵導(dǎo)致重新啟動(dòng)游戲
if (keyCode == KeyEvent.VK_R ||
keyCode == KeyEvent.VK_S ||
keyCode == KeyEvent.VK_ENTER) {
model.reset();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
-------------------------------------------------------------
3、
/*
*
*/
package mvcTest;
/**
* 游戲的Model類(lèi),負(fù)責(zé)所有游戲相關(guān)數(shù)據(jù)及運(yùn)行
* @author WangYu
* @version 1.0
* Description:
* /pre
* Create on :Date :2005-6-13 Time:15:58:33
* LastModified:
* History:
*/
//SnakeModel.java
import javax.swing.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Random;
/**
* 游戲的Model類(lèi),負(fù)責(zé)所有游戲相關(guān)數(shù)據(jù)及運(yùn)行
*/
class SnakeModel extends Observable implements Runnable {
boolean[][] matrix; // 指示位置上有沒(méi)蛇體或食物
LinkedList nodeArray = new LinkedList(); // 蛇體
Node food;
int maxX;
int maxY;
int direction = 2; // 蛇運(yùn)行的方向
boolean running = false; // 運(yùn)行狀態(tài)
int timeInterval = 200; // 時(shí)間間隔,毫秒
double speedChangeRate = 0.75; // 每次得速度變化率
boolean paused = false; // 暫停標(biāo)志
int score = 0; // 得分
int countMove = 0; // 吃到食物前移動(dòng)的次數(shù)
// UP and DOWN should be even
// RIGHT and LEFT should be odd
public static final int UP = 2;
public static final int DOWN = 4;
public static final int LEFT = 1;
public static final int RIGHT = 3;
public SnakeModel( int maxX, int maxY) {
this.maxX = maxX;
this.maxY = maxY;
reset();
}
public void reset(){
direction = SnakeModel.UP; // 蛇運(yùn)行的方向
timeInterval = 200; // 時(shí)間間隔,毫秒
paused = false; // 暫停標(biāo)志
score = 0; // 得分
countMove = 0; // 吃到食物前移動(dòng)的次數(shù)
// initial matirx, 全部清0
matrix = new boolean[maxX][];
for (int i = 0; i maxX; ++i) {
matrix[i] = new boolean[maxY];
Arrays.fill(matrix[i], false);
}
// initial the snake
// 初始化蛇體,如果橫向位置超過(guò)20個(gè),長(zhǎng)度為10,否則為橫向位置的一半
int initArrayLength = maxX 20 ? 10 : maxX / 2;
nodeArray.clear();
for (int i = 0; i initArrayLength; ++i) {
int x = maxX / 2 + i;//maxX被初始化為20
int y = maxY / 2; //maxY被初始化為30
//nodeArray[x,y]: [10,15]-[11,15]-[12,15]~~[20,15]
//默認(rèn)的運(yùn)行方向向上,所以游戲一開(kāi)始nodeArray就變?yōu)椋?/p>
// [10,14]-[10,15]-[11,15]-[12,15]~~[19,15]
nodeArray.addLast(new Node(x, y));
matrix[x][y] = true;
}
// 創(chuàng)建食物
food = createFood();
matrix[food.x][food.y] = true;
}
public void changeDirection(int newDirection) {
// 改變的方向不能與原來(lái)方向同向或反向
if (direction % 2 != newDirection % 2) {
direction = newDirection;
}
}
/**
* 運(yùn)行一次
* @return
*/
public boolean moveOn() {
Node n = (Node) nodeArray.getFirst();
int x = n.x;
int y = n.y;
// 根據(jù)方向增減坐標(biāo)值
switch (direction) {
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}
// 如果新坐標(biāo)落在有效范圍內(nèi),則進(jìn)行處理
if ((0 = x x maxX) (0 = y y maxY)) {
if (matrix[x][y]) { // 如果新坐標(biāo)的點(diǎn)上有東西(蛇體或者食物)
if (x == food.x y == food.y) { // 吃到食物,成功
nodeArray.addFirst(food); // 從蛇頭贈(zèng)長(zhǎng)
// 分?jǐn)?shù)規(guī)則,與移動(dòng)改變方向的次數(shù)和速度兩個(gè)元素有關(guān)
int scoreGet = (10000 - 200 * countMove) / timeInterval;
score += scoreGet 0 ? scoreGet : 10;
countMove = 0;
food = createFood(); // 創(chuàng)建新的食物
matrix[food.x][food.y] = true; // 設(shè)置食物所在位置
return true;
} else // 吃到蛇體自身,失敗
return false;
} else { // 如果新坐標(biāo)的點(diǎn)上沒(méi)有東西(蛇體),移動(dòng)蛇體
nodeArray.addFirst(new Node(x, y));
matrix[x][y] = true;
n = (Node) nodeArray.removeLast();
matrix[n.x][n.y] = false;
countMove++;
return true;
}
}
return false; // 觸到邊線,失敗
}
public void run() {
running = true;
while (running) {
try {
Thread.sleep(timeInterval);
} catch (Exception e) {
break;
}
if (!paused) {
if (moveOn()) {
setChanged(); // Model通知View數(shù)據(jù)已經(jīng)更新
notifyObservers();
} else {
JOptionPane.showMessageDialog(null,
"you failed",
"Game Over",
JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
running = false;
}
private Node createFood() {
int x = 0;
int y = 0;
// 隨機(jī)獲取一個(gè)有效區(qū)域內(nèi)的與蛇體和食物不重疊的位置
do {
Random r = new Random();
x = r.nextInt(maxX);
y = r.nextInt(maxY);
} while (matrix[x][y]);
return new Node(x, y);
}
public void speedUp() {
timeInterval *= speedChangeRate;
}
public void speedDown() {
timeInterval /= speedChangeRate;
}
public void changePauseState() {
paused = !paused;
}
public String toString() {
String result = "";
for (int i = 0; i nodeArray.size(); ++i) {
Node n = (Node) nodeArray.get(i);
result += "[" + n.x + "," + n.y + "]";
}
return result;
}
}
class Node {
int x;
int y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
}
------------------------------------------------------------
4、
package mvcTest;
//SnakeView.java
import javax.swing.*;
import java.awt.*;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;
/**
* MVC模式中得Viewer,只負(fù)責(zé)對(duì)數(shù)據(jù)的顯示,而不用理會(huì)游戲的控制邏輯
*/
public class SnakeView implements Observer {
SnakeControl control = null;
SnakeModel model = null;
JFrame mainFrame;
Canvas paintCanvas;
JLabel labelScore;
public static final int canvasWidth = 200;
public static final int canvasHeight = 300;
public static final int nodeWidth = 10;
public static final int nodeHeight = 10;
public SnakeView(SnakeModel model, SnakeControl control) {
this.model = model;
this.control = control;
mainFrame = new JFrame("GreedSnake");
Container cp = mainFrame.getContentPane();
// 創(chuàng)建頂部的分?jǐn)?shù)顯示
labelScore = new JLabel("Score:");
cp.add(labelScore, BorderLayout.NORTH);
// 創(chuàng)建中間的游戲顯示區(qū)域
paintCanvas = new Canvas();
paintCanvas.setSize(canvasWidth + 1, canvasHeight + 1);
paintCanvas.addKeyListener(control);
cp.add(paintCanvas, BorderLayout.CENTER);
// 創(chuàng)建底下的幫助欄
JPanel panelButtom = new JPanel();
panelButtom.setLayout(new BorderLayout());
JLabel labelHelp;
labelHelp = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.NORTH);
labelHelp = new JLabel("ENTER or R or S for start;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.CENTER);
labelHelp = new JLabel("SPACE or P for pause", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.SOUTH);
cp.add(panelButtom, BorderLayout.SOUTH);
mainFrame.addKeyListener(control);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
void repaint() {
Graphics g = paintCanvas.getGraphics();
//draw background
g.setColor(Color.WHITE);
g.fillRect(0, 0, canvasWidth, canvasHeight);
// draw the snake
g.setColor(Color.BLACK);
LinkedList na = model.nodeArray;
Iterator it = na.iterator();
while (it.hasNext()) {
Node n = (Node) it.next();
drawNode(g, n);
}
// draw the food
g.setColor(Color.RED);
Node n = model.food;
drawNode(g, n);
updateScore();
}
private void drawNode(Graphics g, Node n) {
g.fillRect(n.x * nodeWidth,
n.y * nodeHeight,
nodeWidth - 1,
nodeHeight - 1);
}
public void updateScore() {
String s = "Score: " + model.score;
labelScore.setText(s);
}
public void update(Observable o, Object arg) {
repaint();
}
}
-------------------------------------------------------------
用MVC方式實(shí)現(xiàn)的貪吃蛇游戲,共有4個(gè)類(lèi)。運(yùn)行GreedSnake運(yùn)行即可。主要是觀察者模式的使用,我已經(jīng)添加了很多注釋了。
1、
/*
* 程序名稱:貪食蛇
* 原作者:BigF
* 修改者:algo
* 說(shuō)明:我以前也用C寫(xiě)過(guò)這個(gè)程序,現(xiàn)在看到BigF用Java寫(xiě)的這個(gè),發(fā)現(xiàn)雖然作者自稱是Java的初學(xué)者,
* 但是明顯編寫(xiě)程序的素養(yǎng)不錯(cuò),程序結(jié)構(gòu)寫(xiě)得很清晰,有些細(xì)微得地方也寫(xiě)得很簡(jiǎn)潔,一時(shí)興起之
* 下,我認(rèn)真解讀了這個(gè)程序,發(fā)現(xiàn)數(shù)據(jù)和表現(xiàn)分開(kāi)得很好,而我近日正在學(xué)習(xí)MVC設(shè)計(jì)模式,
* 因此嘗試把程序得結(jié)構(gòu)改了一下,用MVC模式來(lái)實(shí)現(xiàn),對(duì)源程序得改動(dòng)不多。
* 我同時(shí)也為程序增加了一些自己理解得注釋?zhuān)M麑?duì)大家閱讀有幫助。
*/
package mvcTest;
/**
* @author WangYu
* @version 1.0
* Description:
* /pre
* Create on :Date :2005-6-13 Time:15:57:16
* LastModified:
* History:
*/
public class GreedSnake {
public static void main(String[] args) {
SnakeModel model = new SnakeModel(20,30);
SnakeControl control = new SnakeControl(model);
SnakeView view = new SnakeView(model,control);
//添加一個(gè)觀察者,讓view成為model的觀察者
model.addObserver(view);
(new Thread(model)).start();
}
}
-------------------------------------------------------------
2、
package mvcTest;
//SnakeControl.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
* MVC中的Controler,負(fù)責(zé)接收用戶的操作,并把用戶操作通知Model
*/
public class SnakeControl implements KeyListener{
SnakeModel model;
public SnakeControl(SnakeModel model){
this.model = model;
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (model.running){ // 運(yùn)行狀態(tài)下,處理的按鍵
switch (keyCode) {
case KeyEvent.VK_UP:
model.changeDirection(SnakeModel.UP);
break;
case KeyEvent.VK_DOWN:
model.changeDirection(SnakeModel.DOWN);
break;
case KeyEvent.VK_LEFT:
model.changeDirection(SnakeModel.LEFT);
break;
case KeyEvent.VK_RIGHT:
model.changeDirection(SnakeModel.RIGHT);
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_PAGE_UP:
model.speedUp();
break;
case KeyEvent.VK_SUBTRACT:
case KeyEvent.VK_PAGE_DOWN:
model.speedDown();
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
model.changePauseState();
break;
default:
}
}
// 任何情況下處理的按鍵,按鍵導(dǎo)致重新啟動(dòng)游戲
if (keyCode == KeyEvent.VK_R ||
keyCode == KeyEvent.VK_S ||
keyCode == KeyEvent.VK_ENTER) {
model.reset();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
-------------------------------------------------------------
3、
/*
*
*/
package mvcTest;
/**
* 游戲的Model類(lèi),負(fù)責(zé)所有游戲相關(guān)數(shù)據(jù)及運(yùn)行
* @author WangYu
* @version 1.0
* Description:
* /pre
* Create on :Date :2005-6-13 Time:15:58:33
* LastModified:
* History:
*/
//SnakeModel.java
import javax.swing.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Random;
/**
* 游戲的Model類(lèi),負(fù)責(zé)所有游戲相關(guān)數(shù)據(jù)及運(yùn)行
*/
class SnakeModel extends Observable implements Runnable {
boolean[][] matrix; // 指示位置上有沒(méi)蛇體或食物
LinkedList nodeArray = new LinkedList(); // 蛇體
Node food;
int maxX;
int maxY;
int direction = 2; // 蛇運(yùn)行的方向
boolean running = false; // 運(yùn)行狀態(tài)
int timeInterval = 200; // 時(shí)間間隔,毫秒
double speedChangeRate = 0.75; // 每次得速度變化率
boolean paused = false; // 暫停標(biāo)志
int score = 0; // 得分
int countMove = 0; // 吃到食物前移動(dòng)的次數(shù)
// UP and DOWN should be even
// RIGHT and LEFT should be odd
public static final int UP = 2;
public static final int DOWN = 4;
public static final int LEFT = 1;
public static final int RIGHT = 3;
public SnakeModel( int maxX, int maxY) {
this.maxX = maxX;
this.maxY = maxY;
reset();
}
public void reset(){
direction = SnakeModel.UP; // 蛇運(yùn)行的方向
timeInterval = 200; // 時(shí)間間隔,毫秒
paused = false; // 暫停標(biāo)志
score = 0; // 得分
countMove = 0; // 吃到食物前移動(dòng)的次數(shù)
// initial matirx, 全部清0
matrix = new boolean[maxX][];
for (int i = 0; i maxX; ++i) {
matrix[i] = new boolean[maxY];
Arrays.fill(matrix[i], false);
}
// initial the snake
// 初始化蛇體,如果橫向位置超過(guò)20個(gè),長(zhǎng)度為10,否則為橫向位置的一半
int initArrayLength = maxX 20 ? 10 : maxX / 2;
nodeArray.clear();
for (int i = 0; i initArrayLength; ++i) {
int x = maxX / 2 + i;//maxX被初始化為20
int y = maxY / 2; //maxY被初始化為30
//nodeArray[x,y]: [10,15]-[11,15]-[12,15]~~[20,15]
//默認(rèn)的運(yùn)行方向向上,所以游戲一開(kāi)始nodeArray就變?yōu)椋?/p>
// [10,14]-[10,15]-[11,15]-[12,15]~~[19,15]
nodeArray.addLast(new Node(x, y));
matrix[x][y] = true;
}
// 創(chuàng)建食物
food = createFood();
matrix[food.x][food.y] = true;
}
public void changeDirection(int newDirection) {
// 改變的方向不能與原來(lái)方向同向或反向
if (direction % 2 != newDirection % 2) {
direction = newDirection;
}
}
/**
* 運(yùn)行一次
* @return
*/
public boolean moveOn() {
Node n = (Node) nodeArray.getFirst();
int x = n.x;
int y = n.y;
// 根據(jù)方向增減坐標(biāo)值
switch (direction) {
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}
// 如果新坐標(biāo)落在有效范圍內(nèi),則進(jìn)行處理
if ((0 = x x maxX) (0 = y y maxY)) {
if (matrix[x][y]) { // 如果新坐標(biāo)的點(diǎn)上有東西(蛇體或者食物)
if (x == food.x y == food.y) { // 吃到食物,成功
nodeArray.addFirst(food); // 從蛇頭贈(zèng)長(zhǎng)
// 分?jǐn)?shù)規(guī)則,與移動(dòng)改變方向的次數(shù)和速度兩個(gè)元素有關(guān)
int scoreGet = (10000 - 200 * countMove) / timeInterval;
score += scoreGet 0 ? scoreGet : 10;
countMove = 0;
food = createFood(); // 創(chuàng)建新的食物
matrix[food.x][food.y] = true; // 設(shè)置食物所在位置
return true;
} else // 吃到蛇體自身,失敗
return false;
} else { // 如果新坐標(biāo)的點(diǎn)上沒(méi)有東西(蛇體),移動(dòng)蛇體
nodeArray.addFirst(new Node(x, y));
matrix[x][y] = true;
n = (Node) nodeArray.removeLast();
matrix[n.x][n.y] = false;
countMove++;
return true;
}
}
return false; // 觸到邊線,失敗
}
public void run() {
running = true;
while (running) {
try {
Thread.sleep(timeInterval);
} catch (Exception e) {
break;
}
if (!paused) {
if (moveOn()) {
setChanged(); // Model通知View數(shù)據(jù)已經(jīng)更新
notifyObservers();
} else {
JOptionPane.showMessageDialog(null,
"you failed",
"Game Over",
JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
running = false;
}
private Node createFood() {
int x = 0;
int y = 0;
// 隨機(jī)獲取一個(gè)有效區(qū)域內(nèi)的與蛇體和食物不重疊的位置
do {
Random r = new Random();
x = r.nextInt(maxX);
y = r.nextInt(maxY);
} while (matrix[x][y]);
return new Node(x, y);
}
public void speedUp() {
timeInterval *= speedChangeRate;
}
public void speedDown() {
timeInterval /= speedChangeRate;
}
public void changePauseState() {
paused = !paused;
}
public String toString() {
String result = "";
for (int i = 0; i nodeArray.size(); ++i) {
Node n = (Node) nodeArray.get(i);
result += "[" + n.x + "," + n.y + "]";
}
return result;
}
}
class Node {
int x;
int y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
}
------------------------------------------------------------
4、
package mvcTest;
//SnakeView.java
import javax.swing.*;
import java.awt.*;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;
/**
* MVC模式中得Viewer,只負(fù)責(zé)對(duì)數(shù)據(jù)的顯示,而不用理會(huì)游戲的控制邏輯
*/
public class SnakeView implements Observer {
SnakeControl control = null;
SnakeModel model = null;
JFrame mainFrame;
Canvas paintCanvas;
JLabel labelScore;
public static final int canvasWidth = 200;
public static final int canvasHeight = 300;
public static final int nodeWidth = 10;
public static final int nodeHeight = 10;
public SnakeView(SnakeModel model, SnakeControl control) {
this.model = model;
this.control = control;
mainFrame = new JFrame("GreedSnake");
Container cp = mainFrame.getContentPane();
// 創(chuàng)建頂部的分?jǐn)?shù)顯示
labelScore = new JLabel("Score:");
cp.add(labelScore, BorderLayout.NORTH);
// 創(chuàng)建中間的游戲顯示區(qū)域
paintCanvas = new Canvas();
paintCanvas.setSize(canvasWidth + 1, canvasHeight + 1);
paintCanvas.addKeyListener(control);
cp.add(paintCanvas, BorderLayout.CENTER);
// 創(chuàng)建底下的幫助欄
JPanel panelButtom = new JPanel();
panelButtom.setLayout(new BorderLayout());
JLabel labelHelp;
labelHelp = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.NORTH);
labelHelp = new JLabel("ENTER or R or S for start;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.CENTER);
labelHelp = new JLabel("SPACE or P for pause", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.SOUTH);
cp.add(panelButtom, BorderLayout.SOUTH);
mainFrame.addKeyListener(control);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
void repaint() {
Graphics g = paintCanvas.getGraphics();
//draw background
g.setColor(Color.WHITE);
g.fillRect(0, 0, canvasWidth, canvasHeight);
// draw the snake
g.setColor(Color.BLACK);
LinkedList na = model.nodeArray;
Iterator it = na.iterator();
while (it.hasNext()) {
Node n = (Node) it.next();
drawNode(g, n);
}
// draw the food
g.setColor(Color.RED);
Node n = model.food;
drawNode(g, n);
updateScore();
}
private void drawNode(Graphics g, Node n) {
g.fillRect(n.x * nodeWidth,
n.y * nodeHeight,
nodeWidth - 1,
nodeHeight - 1);
}
public void updateScore() {
String s = "Score: " + model.score;
labelScore.setText(s);
}
public void update(Observable o, Object arg) {
repaint();
}
}
希望采納
package games;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import static java.lang.Math.*;//靜態(tài)導(dǎo)入
/*
* 此類(lèi)是貪吃蛇的簡(jiǎn)單實(shí)現(xiàn)方法
* 自己可以加入在開(kāi)始時(shí)的設(shè)置,比如
* 選關(guān),初始的蛇的長(zhǎng)度等等
*/
public class Snake extends JPanel {
private static final long serialVersionUID = 1L;
private Direction dir;// 要走的方向
private int blockWidth = 10;// 塊大小
private int blockSpace = 2;// 塊之間的間隔
private long sleepTime;// 重畫(huà)的進(jìn)間間隔
private MySnake my;
private int total;// 代表蛇的長(zhǎng)度
private Rectangle food;// 代表蛇的食物
private volatile boolean go;
private int round;// 表示第幾關(guān)
public Snake(JFrame jf) {
initOther();
// 為頂級(jí)窗口類(lèi)JFrame添加事件處理函數(shù)
jf.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
int code = ke.getKeyCode();
if (code == KeyEvent.VK_RIGHT) {
if (dir != Direction.WEST)
dir = Direction.EAST;
}
else if (code == KeyEvent.VK_LEFT) {
if (dir != Direction.EAST)
dir = Direction.WEST;
}
else if (code == KeyEvent.VK_UP) {
if (dir != Direction.SOUTH)
dir = Direction.NORTH;
}
else if (code == KeyEvent.VK_DOWN) {
if (dir != Direction.NORTH)
dir = Direction.SOUTH;
} else if (code == KeyEvent.VK_ENTER) {
if (!go)
initOther();
}
}
});
this.setBounds(300, 300, 400, 400);
this.setVisible(true);
}
// 隨機(jī)生成一個(gè)食物的位置
private void makeFood() {
int x = 40 + (int) (random() * 30) * 12;
int y = 10 + (int) (random() * 30) * 12;
food = new Rectangle(x, y, 10, 10);
}
// 做一些初始化的工作
private void initOther() {
dir = Direction.EAST;
sleepTime = 500;
my = new MySnake();
makeFood();
total = 3;
round = 1;
new Thread(new Runnable() {
public void run() {
go = true;
while (go) {
try {
Thread.sleep(sleepTime);
repaint();
} catch (Exception exe) {
exe.printStackTrace();
}
}
}
}).start();
}
// 處理多少關(guān)的函數(shù)
private void handleRound() {
if (total == 6) {
round = 2;
sleepTime = 300;
} else if (total == 10) {
round = 3;
sleepTime = 200;
} else if (total == 15) {
round = 4;
sleepTime = 100;
} else if (total == 18) {
round = 5;
sleepTime = 50;
} else if (total == 20) {
round = 6;
sleepTime = 20;
} else if (total 21) {
round = 7;
sleepTime = 15;
}
}
// 把自己的組件全部畫(huà)出來(lái)
public void paintComponent(Graphics g) {
g.setColor(Color.PINK);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.BLACK);
g.drawRect(40, 10, 358, 360);
if (go) {
my.move();
my.draw(g);
g.setFont(new Font("黑體", Font.BOLD, 20));
g.drawString("您的得分:" + (total * 10) + " 第" + round + "關(guān)", 40,
400);
} else {
g.setFont(new Font("黑體", Font.BOLD, 20));
g.drawString("游戲結(jié)束,按回車(chē)(ENTER)鍵重玩!", 40, 440);
}
g.setColor(Color.RED);
g.fillRect(food.x, food.y, food.width, food.height);
}
private class MySnake {
private ArrayListRectangle list;
public MySnake() {
list = new ArrayListRectangle();
list.add(new Rectangle(160 + 24, 130, 10, 10));
list.add(new Rectangle(160 + 12, 130, 10, 10));
list.add(new Rectangle(160, 130, 10, 10));
}
// 蛇移動(dòng)的方法
public void move() {
if (isDead()) {
go = false;
return;
}
if (dir == Direction.EAST) {
Rectangle rec = list.get(0);
Rectangle rec1 = new Rectangle(rec.x
+ (blockWidth + blockSpace), rec.y, rec.width,
rec.height);
list.add(0, rec1);
} else if (dir == Direction.WEST) {
Rectangle rec = list.get(0);
Rectangle rec1 = new Rectangle(rec.x
- (blockWidth + blockSpace), rec.y, rec.width,
rec.height);
list.add(0, rec1);
} else if (dir == Direction.NORTH) {
Rectangle rec = list.get(0);
Rectangle rec1 = new Rectangle(rec.x, rec.y
- (blockWidth + blockSpace), rec.width, rec.height);
list.add(0, rec1);
} else if (dir == Direction.SOUTH) {
Rectangle rec = list.get(0);
Rectangle rec1 = new Rectangle(rec.x, rec.y
+ (blockWidth + blockSpace), rec.width, rec.height);
list.add(0, rec1);
}
if (isEat()) {
handleRound();
makeFood();
} else {
list.remove(list.size() - 1);
}
}
// 判斷是否吃到了食物
private boolean isEat() {
if (list.get(0).contains(food)) {
total++;
return true;
} else
return false;
}
// 判斷是否死了,如果碰壁或者自己吃到自己都算死了
private boolean isDead() {
Rectangle temp = list.get(0);
if (dir == Direction.EAST) {
if (temp.x == 388)
return true;
else {
Rectangle comp = new Rectangle(temp.x + 12, temp.y, 10, 10);
for (Rectangle rec : list) {
if (rec.contains(comp))
return true;
}
}
return false;
} else if (dir == Direction.WEST) {
if (temp.x == 40)
return true;
else {
Rectangle comp = new Rectangle(temp.x - 12, temp.y, 10, 10);
for (Rectangle rec : list) {
if (rec.contains(comp))
return true;
}
}
return false;
} else if (dir == Direction.NORTH) {
if (temp.y == 10)
return true;
else {
Rectangle comp = new Rectangle(temp.x, temp.y - 12, 10, 10);
for (Rectangle rec : list) {
if (rec.contains(comp))
return true;
}
}
return false;
} else if (dir == Direction.SOUTH) {
if (temp.y == 358)
return true;
else {
Rectangle comp = new Rectangle(temp.x, temp.y + 12, 10, 10);
for (Rectangle rec : list) {
if (rec.contains(comp))
return true;
}
}
return false;
} else {
return false;
}
}
// 把自己畫(huà)出來(lái)
public void draw(Graphics g) {
for (Rectangle rec : list) {
g.fillRect(rec.x, rec.y, rec.width, rec.height);
}
}
}
public static void main(String arsg[]) {
JFrame jf = new JFrame("貪吃蛇");
Snake s = new Snake(jf);
jf.getContentPane().add(s, BorderLayout.CENTER);
jf.setBounds(300, 300, 500, 500);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
// 定義一個(gè)枚舉,在此也可以用接口或者常量值代替
enum Direction {
EAST, SOUTH, WEST, NORTH;
}
Runnable
}
if (i.util.Date.start();args) {
Thread new Thread(new Thread1());0;one = new Thread(new Thread2()).printStackTrace();
public
if (i %
one.start();
two;class Thread2
Thread implements class Thread1 {
while(true){
i++;
System.out.println(new i = run() {
while (true) {
two = Date().toLocaleString());
} catch try {
Thread.sleep(10000);Runnable {
break;
}
}
}
}
import java;Client {
public static void main(String[] );
public void run()
}
}
}
}pre t="code" l="java"public class 4 == 0) {
System.out.println(;*******pre t="code" l="java"public implements {
private int (InterruptedException e) {
e;{
public void 100)nbsp
設(shè)計(jì)游戲,首先就要設(shè)計(jì)界面。首先看一下我設(shè)計(jì)的一個(gè)界面。界面分為左邊的游戲區(qū)與右邊的控制區(qū)。游戲區(qū)包含“得分信息”和貪吃蛇的游戲區(qū),右邊控制區(qū)有“開(kāi)始”“暫?!薄巴V埂卑粹o,等級(jí)選擇單選框以及游戲排行榜。
所以我們需要定義swing組件,并在類(lèi)初始化時(shí)初始化這些組件,添加組件。因?yàn)楹竺嬖O(shè)計(jì)游戲的時(shí)候,我們要確切知道游戲區(qū)的大小,所以這里設(shè)置游戲區(qū)固定大小值。本來(lái)想用布局來(lái)更好的管理,但作者對(duì)布局也掌握不夠,所以就先設(shè)置固定大小吧。
定義我們的游戲。貪吃蛇游戲其實(shí)就是包含很多細(xì)小網(wǎng)格,然后蛇在網(wǎng)格中移動(dòng)。蛇由一連串的網(wǎng)格組成,為了視覺(jué)效果,蛇身用藍(lán)色標(biāo)記,食物用紅色標(biāo)記,背景白色。如第一張圖片所示。所以,我們需要定義二維數(shù)組,保存網(wǎng)格信息,保存蛇身和食物的位置信息等。初始化時(shí),還需要添加鍵盤(pán)事件控制上下左右移動(dòng)。
食物的位置信息是二維的,所以我簡(jiǎn)單定義了一個(gè)類(lèi)用來(lái)保存二維信息。
接著就是實(shí)現(xiàn)游戲的功能了。開(kāi)始,暫停,停止按鈕添加事件控制游戲開(kāi)始。等級(jí)按鈕定義游戲難度等。
開(kāi)始游戲后,我們定義一個(gè)定時(shí)器。蛇身按照指定的方向移動(dòng),方向是通過(guò)初始化時(shí)添加的鍵盤(pán)事件,鍵盤(pán)的上下左右按鈕來(lái)控制。蛇身是連續(xù)的位置信息,保存到隊(duì)列中,所以蛇身的移動(dòng)就是隊(duì)首增加一個(gè)位置,隊(duì)尾減少位置,然后重新繪畫(huà)游戲區(qū)就可以了。
在蛇身移動(dòng)時(shí)進(jìn)一步做吃掉食物、撞墻、撞到自己的處理。這是游戲的主要邏輯。
最后,游戲結(jié)束我們彈出一個(gè)對(duì)話框提示是否保存游戲得分。我們制作了排行榜信息,只保留前10名的游戲得分。首先定義了一個(gè)實(shí)現(xiàn)Comparable接口的游戲得分類(lèi),按得分高,時(shí)間最早來(lái)排序。
游戲結(jié)束時(shí)保存得分信息,看是否進(jìn)入到排行榜中。而之前在初始化排行榜組件時(shí)就會(huì)加載游戲排行榜信息。
通過(guò)保存和讀取排行榜信息,我們也熟悉一下文件讀取操作,還有集合、排序算法的功能。
當(dāng)前標(biāo)題:java編寫(xiě)貪吃蛇代碼長(zhǎng),Java編寫(xiě)貪吃蛇
文章地址:http://jinyejixie.com/article6/dssejog.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、響應(yīng)式網(wǎng)站、營(yíng)銷(xiāo)型網(wǎng)站建設(shè)、標(biāo)簽優(yōu)化、網(wǎng)站收錄、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)