Java GUI編程之貪吃蛇游戲簡(jiǎn)單實(shí)現(xiàn)方法【附demo源碼下載】
本文實(shí)例講述了Java GUI編程之貪吃蛇游戲簡(jiǎn)單實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
例子簡(jiǎn)單,界面簡(jiǎn)陋 請(qǐng)見諒
項(xiàng)目結(jié)構(gòu)如下

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();
}
}
/**
* 重寫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);
}
/**
* 畫蛋
* @param g 畫筆
*/
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)開始方向向左 ,蛇身有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);
}
/**
* 是否吃到蛋,蛇身是否有格子跟蛋重疊,所以重寫了Node的equals方法
*
* @param egg蛋
* @return boolean
*/
boolean eatEgg(Egg egg) {
if (nodeList.contains(egg)) {
addNode();
return true;
} else {
return false;
}
}
/**
* 畫自己
*
* @param g畫筆
*/
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();
}
/**
* 鍵盤事件,來確定前進(jìn)方向,有左右上下4個(gè)方向
*
* @param e鍵盤監(jiān)聽事件
*/
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;
/**
* 給畫筆起一個(gè)線程
*/
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)聽事件
*/
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
/**
* 添加鍵盤監(jiān)聽事件
*/
this.addKeyListener(new KeyMomiter());
/**
* 畫筆線程啟動(dòng)
*/
new Thread(paintThread).start();
}
/**
* 畫筆畫界面
*/
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();
}
/**
* 畫筆的線程
*
* @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;
}
/**
* 重新開始
*/
public void restart() {
this.pause = true;
snake = new Snake();
}
/**
* 游戲結(jié)束
*/
public void gameOver() {
isRun = false;
}
}
/**
* 停止
*/
void stop() {
gameOver = true;
}
/**
* 鍵盤監(jiān)聽器
*
* @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)行效果:

附:完整實(shí)例代碼點(diǎn)擊此處本站下載。
更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java字符與字符串操作技巧總結(jié)》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
相關(guān)文章
深入詳解java高并發(fā)熱點(diǎn)數(shù)據(jù)更新
這篇文章主要為大家深入介紹了java高并發(fā)熱點(diǎn)數(shù)據(jù)更新詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
細(xì)說Springcloud eureka的幾種主動(dòng)下線服務(wù)的方式
這篇文章主要介紹了細(xì)說Springcloud eureka的幾種主動(dòng)下線服務(wù)的方式,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-09-09
java 代理模式及動(dòng)態(tài)代理機(jī)制深入分析
這篇文章主要介紹了java 代理模式及動(dòng)態(tài)代理機(jī)制深入分析的相關(guān)資料, 代理是一種常用的設(shè)計(jì)模式,其目的就是為其他對(duì)象提供一個(gè)代理以控制對(duì)某個(gè)對(duì)象的訪問,需要的朋友可以參考下2017-03-03
Spring Boot 整合 Apache Dubbo的示例代碼
Apache Dubbo是一款高性能、輕量級(jí)的開源 Java RPC 框架,這篇文章主要介紹了Spring Boot 整合 Apache Dubbo的方法,本文通過示例說明給大家講解的非常詳細(xì),需要的朋友可以參考下2021-07-07
springboot starter自定義實(shí)現(xiàn)公共模塊方式
這篇文章主要介紹了springboot starter自定義實(shí)現(xiàn)公共模塊方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
解讀@SpringBootApplication注解有什么用
@SpringBootApplication是SpringBoot的核心注解,主要包含@SpringBootConfiguration、@EnableAutoConfiguration和@ComponentScan三個(gè)注解,這些注解共同簡(jiǎn)化了Spring應(yīng)用的配置工作,并使得通過主程序類就可以啟動(dòng)SpringBoot應(yīng)用2024-09-09

