溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Java GUI編程之貪吃蛇游戲簡(jiǎn)單實(shí)現(xiàn)方法【附demo源碼下載】

發(fā)布時(shí)間:2020-08-20 09:52:20 來(lái)源:腳本之家 閱讀:170 作者:送人玫瑰手留余香 欄目:編程語(yǔ)言

本文實(shí)例講述了Java GUI編程之貪吃蛇游戲簡(jiǎn)單實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:

例子簡(jiǎn)單,界面簡(jiǎn)陋 請(qǐng)見(jiàn)諒

項(xiàng)目結(jié)構(gòu)如下

Java GUI編程之貪吃蛇游戲簡(jiǎn)單實(shí)現(xiàn)方法【附demo源碼下載】

Constant.jvava 代碼如下:

package snake;
/**
 *
 * @author hjn
 *
 */
public class Constant {
/**
 * 蛇方移動(dòng)方向:左邊
 */
public static final int LEFT = 0;
/**
 * 蛇方移動(dòng)方向:右邊
 */
public static final int RIGHT = 1;
/**
 * 蛇方移動(dòng)方向:上邊
 */
public static final int UP = 3;
/**
 * 蛇方移動(dòng)方向:下邊
 */
public static final int DOWN = 4;
/**
 * 界面列數(shù)
 */
public static final int COLS = 30;
/**
 * 界面行數(shù)
 */
public static final int ROWS = 30;
/**
 * 每個(gè)格子邊長(zhǎng)
 */
public static final int BODER_SIZE = 15;
}

Node.java代碼如下:

package snake;
/**
 * 格子
 *
 * @author hjn
 *
 */
public class Node {
/**
 * 所在行數(shù)
 */
private int row;
/**
 * 所在列數(shù)
 */
private int col;
public Node() {
};
public Node(int row, int col) {
this.row = row;
this.col = col;
};
/**
 * 蛇將要移動(dòng)一格時(shí)頭部格子將所到格子
 *
 * @param dir
 *      蛇前進(jìn)方向
 * @param node
 *      蛇頭所在的格子
 */
public Node(int dir, Node node) {
if (dir == Constant.LEFT) {
this.col = node.getCol() - 1;
this.row = node.getRow();
} else if (dir == Constant.RIGHT) {
this.col = node.getCol() + 1;
this.row = node.getRow();
} else if (dir == Constant.UP) {
this.row = node.getRow() - 1;
this.col = node.getCol();
} else {
this.row = node.getRow() + 1;
this.col = node.getCol();
}
}
/**
 * 重寫(xiě)equals方法
 */
public boolean equals(Object obj) {
if (obj instanceof Node) {
Node node = (Node) obj;
if (this.col == node.col && this.row == node.row) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getCol() {
return col;
}
public void setCol(int col) {
this.col = col;
}
public String toString() {
return "col:" + this.col + " row:" + this.row;
}
}

Egg.java代碼如下:

package snake;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
/**
 * 蛋,蛇的食物
 *
 * @author Nan
 *
 */
public class Egg extends Node {
/**
 * 蛋的顏色
 */
Color color;
/**
 * 隨機(jī)函數(shù)
 */
public static Random random = new Random();
/**
 * 構(gòu)造函數(shù) 蛋出現(xiàn)在固定位置
 *
 * @param row
 *      所在第幾行數(shù)
 * @param col
 *      所在第幾列數(shù)
 */
public Egg(int row, int col) {
super(row, col);
this.color = Color.green;
}
/**
 * 構(gòu)造函數(shù) 蛋隨機(jī)出現(xiàn)
 *
 */
public Egg() {
super();
int col = random.nextInt(Constant.COLS - 4) + 2;
int row = random.nextInt(Constant.ROWS - 4) + 2;
this.setCol(col);
this.setRow(row);
}
/**
 * 畫(huà)蛋
 * @param g 畫(huà)筆
 */
void draw(Graphics g) {
if (this.color == Color.green) {
this.color = Color.red;
} else {
this.color = Color.green;
}
g.setColor(this.color);
int boderSize = Constant.BODER_SIZE;
g.fillOval(this.getCol() * boderSize, this.getRow() * boderSize,
boderSize, boderSize);
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}

Snake.java代碼如下:

package snake;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
/**
 * 蛇
 *
 * @author hjn
 *
 */
public class Snake {
/**
 * 前進(jìn)的方向
 */
int dir;
/**
 * 蛇的身體,由一個(gè)格子Node集合組成
 */
List<Node> nodeList = new ArrayList<Node>();
/**
 * 是否越界
 */
boolean isOverstep = false;
/**
 * 構(gòu)造方法默認(rèn)開(kāi)始方向向左 ,蛇身有3個(gè)格子 ,位置在20行,15列
 */
public Snake() {
this.dir = Constant.LEFT;
for (int i = 0; i < 3; i++) {
Node node = new Node(20, 15 + i);
this.nodeList.add(node);
}
}
/**
 * 蛇前進(jìn)
 */
void forward() {
addNode();
nodeList.remove(nodeList.size() - 1);
}
/**
 * 蛇前進(jìn)的時(shí)候頭部增加格子,私有方法
 */
private void addNode() {
Node node = nodeList.get(0);
node = new Node(dir, node);
nodeList.add(0, node);
}
/**
 * 是否吃到蛋,蛇身是否有格子跟蛋重疊,所以重寫(xiě)了Node的equals方法
 *
 * @param egg蛋
 * @return boolean
 */
boolean eatEgg(Egg egg) {
if (nodeList.contains(egg)) {
addNode();
return true;
} else {
return false;
}
}
/**
 * 畫(huà)自己
 *
 * @param g畫(huà)筆
 */
void draw(Graphics g) {
g.setColor(Color.black);
for (int i = 0; i < this.nodeList.size(); i++) {
Node node = this.nodeList.get(i);
if (node.getCol() > (Constant.COLS - 2) || node.getCol() < 2
|| node.getRow() > (Constant.ROWS - 2) || node.getRow() < 2) {
this.isOverstep = true;
}
g.fillRect(node.getCol() * Constant.BODER_SIZE, node.getRow()
* Constant.BODER_SIZE, Constant.BODER_SIZE,
Constant.BODER_SIZE);
}
forward();
}
/**
 * 鍵盤(pán)事件,來(lái)確定前進(jìn)方向,有左右上下4個(gè)方向
 *
 * @param e鍵盤(pán)監(jiān)聽(tīng)事件
 */
void keyPress(KeyEvent e) {
int key = e.getKeyCode();
switch (key) {
case KeyEvent.VK_LEFT:
if (this.dir != Constant.LEFT)
this.dir = Constant.LEFT;
break;
case KeyEvent.VK_RIGHT:
if (this.dir != Constant.RIGHT)
this.dir = Constant.RIGHT;
break;
case KeyEvent.VK_UP:
if (this.dir != Constant.UP)
this.dir = Constant.UP;
break;
case KeyEvent.VK_DOWN:
if (this.dir != Constant.DOWN)
this.dir = Constant.DOWN;
break;
default:
break;
}
}
public int getDir() {
return dir;
}
public void setDir(int dir) {
this.dir = dir;
}
public List<Node> getNodeList() {
return nodeList;
}
public void setNodeList(List<Node> nodeList) {
this.nodeList = nodeList;
}
public boolean isOverstep() {
return isOverstep;
}
public void setOverstep(boolean isOverstep) {
this.isOverstep = isOverstep;
}
}

主界面MainFrame.java代碼如下:

package snake;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
 * 貪吃蛇展示頁(yè)面
 *
 * @author hjn
 *
 */
public class MainFrame extends Frame {
/**
 * 版本
 */
private static final long serialVersionUID = -5227266702753583633L;
/**
 * 背景顏色
 */
Color color = Color.gray;
/**
 * 蛋
 */
static Egg egg = new Egg();
/**
 * 蛇
 */
Snake snake = new Snake();
/**
 * 游戲是否失敗
 */
boolean gameOver = false;
/**
 * 給畫(huà)筆起一個(gè)線(xiàn)程
 */
PaintThread paintThread = new PaintThread();
/**
 * 構(gòu)造方法
 */
public MainFrame() {
init();
}
/**
 * 界面初始化
 */
void init() {
this.setBounds(200, 200, Constant.COLS * Constant.BODER_SIZE,
Constant.ROWS * Constant.BODER_SIZE);
this.setResizable(true);
this.repaint();
/**
 * 窗口關(guān)閉監(jiān)聽(tīng)事件
 */
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
/**
 * 添加鍵盤(pán)監(jiān)聽(tīng)事件
 */
this.addKeyListener(new KeyMomiter());
/**
 * 畫(huà)筆線(xiàn)程啟動(dòng)
 */
new Thread(paintThread).start();
}
/**
 * 畫(huà)筆畫(huà)界面
 */
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.GRAY);
g.fillRect(0, 0, Constant.COLS * Constant.BODER_SIZE, Constant.ROWS
* Constant.BODER_SIZE);
g.setColor(Color.DARK_GRAY);
for (int i = 0; i < Constant.ROWS; i++) {
g.drawLine(0, i * Constant.BODER_SIZE, Constant.COLS
* Constant.BODER_SIZE, i * Constant.BODER_SIZE);
}
for (int i = 0; i < Constant.COLS; i++) {
g.drawLine(i * Constant.BODER_SIZE, 0, i * Constant.BODER_SIZE,
Constant.ROWS * Constant.BODER_SIZE);
}
g.setColor(Color.yellow);
g.setFont(new Font("宋體", Font.BOLD, 20));
g.drawString("score:" + getScore(), 10, 60);
if (gameOver) {
g.setColor(Color.red);
g.drawString("GAME OVER", 100, 60);
this.paintThread.pause = true;
}
g.setColor(c);
if (snake.eatEgg(egg)) {
egg = new Egg();
}
snake.draw(g);
egg.draw(g);
}
/**
 * 獲取分?jǐn)?shù)
 *
 * @return int 分?jǐn)?shù)
 */
int getScore() {
return snake.getNodeList().size();
}
/**
 * 畫(huà)筆的線(xiàn)程
 *
 * @author hjn
 */
class PaintThread implements Runnable {
private boolean isRun = true;
private boolean pause = false;
@Override
public void run() {
while (isRun) {
if (pause) {
continue;
} else {
if (snake.isOverstep == true) {
gameOver = true;
}
repaint();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
 * 暫停
 */
public void pause() {
this.pause = true;
}
/**
 * 重新開(kāi)始
 */
public void restart() {
this.pause = true;
snake = new Snake();
}
/**
 * 游戲結(jié)束
 */
public void gameOver() {
isRun = false;
}
}
/**
 * 停止
 */
void stop() {
gameOver = true;
}
/**
 * 鍵盤(pán)監(jiān)聽(tīng)器
 *
 * @author hjn
 *
 */
class KeyMomiter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
int key = e.getKeyCode();
if (key == KeyEvent.VK_F2) {
paintThread.restart();
} else {
snake.keyPress(e);
}
}
}
/**
 * 啟動(dòng)程序入口
 *
 * @param args
 */
@SuppressWarnings("deprecation")
public static void main(String[] args) {
MainFrame mainFrame = new MainFrame();
mainFrame.show();
}
}

運(yùn)行效果:

Java GUI編程之貪吃蛇游戲簡(jiǎn)單實(shí)現(xiàn)方法【附demo源碼下載】

附:完整實(shí)例代碼點(diǎn)擊此處本站下載。

更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java字符與字符串操作技巧總結(jié)》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》

希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI