这篇文章主要介绍了Java GUI编程之贪吃蛇游戏简单实现方法,详细分析了贪吃蛇游戏的具体实现步骤与相关注意事项,并附带demo源码供读者下载参考,需要的朋友可以参考下

本文实例讲述了Java GUI编程之贪吃蛇游戏简单实现方法。分享给大家供大家参考,具体如下:

例子简单,界面简陋 请见谅

项目结构如下

Constant.jvava 代码如下:

package snake;

/**

*

* @author hjn

*

*/

public class Constant {

/**

* 蛇方移动方向:左边

*/

public static final int LEFT = 0;

/**

* 蛇方移动方向:右边

*/

public static final int RIGHT = 1;

/**

* 蛇方移动方向:上边

*/

public static final int UP = 3;

/**

* 蛇方移动方向:下边

*/

public static final int DOWN = 4;

/**

* 界面列数

*/

public static final int COLS = 30;

/**

* 界面行数

*/

public static final int ROWS = 30;

/**

* 每个格子边长

*/

public static final int BODER_SIZE = 15;

}

Node.java代码如下:

package snake;

/**

* 格子

*

* @author hjn

*

*/

public class Node {

/**

* 所在行数

*/

private int row;

/**

* 所在列数

*/

private int col;

public Node() {

};

public Node(int row, int col) {

this.row = row;

this.col = col;

};

/**

* 蛇将要移动一格时头部格子将所到格子

*

* @param dir

* 蛇前进方向

* @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;

/**

* 随机函数

*/

public static Random random = new Random();

/**

* 构造函数 蛋出现在固定位置

*

* @param row

* 所在第几行数

* @param col

* 所在第几列数

*/

public Egg(int row, int col) {

super(row, col);

this.color = Color.green;

}

/**

* 构造函数 蛋随机出现

*

*/

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 {

/**

* 前进的方向

*/

int dir;

/**

* 蛇的身体,由一个格子Node集合组成

*/

List nodeList = new ArrayList();

/**

* 是否越界

*/

boolean isOverstep = false;

/**

* 构造方法默认开始方向向左 ,蛇身有3个格子 ,位置在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);

}

}

/**

* 蛇前进

*/

void forward() {

addNode();

nodeList.remove(nodeList.size() - 1);

}

/**

* 蛇前进的时候头部增加格子,私有方法

*/

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();

}

/**

* 键盘事件,来确定前进方向,有左右上下4个方向

*

* @param e键盘监听事件

*/

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 getNodeList() {

return nodeList;

}

public void setNodeList(List 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;

/**

* 贪吃蛇展示页面

*

* @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;

/**

* 给画笔起一个线程

*/

PaintThread paintThread = new PaintThread();

/**

* 构造方法

*/

public MainFrame() {

init();

}

/**

* 界面初始化

*/

void init() {

this.setBounds(200, 200, Constant.COLS * Constant.BODER_SIZE,

Constant.ROWS * Constant.BODER_SIZE);

this.setResizable(true);

this.repaint();

/**

* 窗口关闭监听事件

*/

this.addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

/**

* 添加键盘监听事件

*/

this.addKeyListener(new KeyMomiter());

/**

* 画笔线程启动

*/

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);

}

/**

* 获取分数

*

* @return int 分数

*/

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();

}

/**

* 游戏结束

*/

public void gameOver() {

isRun = false;

}

}

/**

* 停止

*/

void stop() {

gameOver = true;

}

/**

* 键盘监听器

*

* @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);

}

}

}

/**

* 启动程序入口

*

* @param args

*/

@SuppressWarnings("deprecation")

public static void main(String[] args) {

MainFrame mainFrame = new MainFrame();

mainFrame.show();

}

}

运行效果:

java gui怎么做游戏_Java中关于GUI实现贪吃蛇游戏的简单方法相关推荐

  1. php贪吃蛇游戏代码下载,JS实现的贪吃蛇游戏完整实例

    本文实例讲述了JS实现的贪吃蛇游戏.分享给大家供大家参考,具体如下: 思想: 1.设计蛇:属性有宽.高.方向.状态(有多少节),方法:显示,跑 2.设计食物:属性宽.高 3.显示蛇:根据状态向地图里加 ...

  2. bat贪吃蛇游戏代码_C语言写个贪吃蛇游戏

    贪吃蛇是个非常经典的游戏,用C语言来实现也是一个好玩的事情.这个游戏我写完后放在知乎,竟然点赞的人数超级多.我觉得大家喜欢,一个方面是因为写得简单,大家都能看得懂,一个可扩展性还是非常强的. 我试了说 ...

  3. c语言贪吃蛇游戏源码下载,c语言贪吃蛇游戏源码.doc

    c语言贪吃蛇游戏源码.doc /*运行是按任意键开始,不过呢,反向也算输哟*/include include include include include include include defin ...

  4. java代码二进制转为十六进制_Java 中二进制转换成十六进制的两种实现方法

    Java 中二进制转换成十六进制的两种实现方法 每个字节转成16进制,方法1 /** * 每个字节转成16进制,方法1 * * @param result */ private static Stri ...

  5. java线程能做什么_java中的多线程能做什么 ?基本作用能说下吗?

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 给你写个最简单的 多线程分同步和异步的,我已经给你写上了synchronized ,但注释了,你可以顺便看看加上它和去掉他的区别! public clas ...

  6. java线程开启不了_Java中多线程启动,为什么调用的是start方法,而不是run方法?...

    前言 大年初二,大家新年快乐,我又开始码字了.写这篇文章,源于在家和基友交流的时候,基友问到了,我猛然发现还真是这么回事,多线程启动调用的都是start,那么为什么没人掉用run呢?于是打开我的ide ...

  7. java io 文件路径格式_java中iofile的路径问题,确定一个未知方法所需要的文件路径...

    今天遇到一个极其烦躁的问题,一个jar包中的一个方法,要求函数中要求传入一个String类型的参数,用于指示文件所在的路径.但是对于我们来说完全不知道他需要的路径是绝对路径还是相对路径,所以我尝试了很 ...

  8. Java贪吃蛇暂停怎么做_Java实现贪吃蛇游戏(1小时学会)

    今天就来拿贪吃蛇小游戏来练练手吧! 贪吃蛇游戏规则: 1.按下空格键(游戏未结束)则游戏暂停或开始: 2.按下空格键(游戏结束后)则游戏重新开始: 3.当贪吃蛇的头部撞到身体时则贪吃蛇死亡(游戏结束) ...

  9. 贪吃蛇大作战代码java,贪吃蛇游戏,贪吃蛇java游戏代码讲解

    贪吃蛇游戏,贪吃蛇java游戏代码讲解 来源:互联网 作者:佚名 时间:2020-06-06 贪吃蛇源代码.txt这世界上除了我谁都没资格陪在你身边. 听着,我允许你喜欢我.除了白头偕老,我们... ...

最新文章

  1. 用python解“BCD解密”问题
  2. boost::mp11::mp_assign相关用法的测试程序
  3. Boost:基于boost::asio的延迟tcp服务器测试程序
  4. OpenGL简单镶嵌
  5. linkedlist java 实现_Java LinkedList 实现原理
  6. 洛谷2774:[网络流24题]方格取数问题——题解
  7. 一台微型计算机_Linux的上百万行代码,一台新的微型计算机以及Google和Microsoft的更多产品
  8. linux so 库的生成与调用
  9. 何时使用 Golang
  10. Mybatis3.4.x技术内幕(十七):Mybatis之动态Sql设计原本(上)
  11. # AD19规则设置的傻瓜式教程
  12. php 输入经纬度查询位置,根据经纬度查询附近地点信息
  13. 关于电平转换电路1.8V转3.3V
  14. The types of the interface org.apache.flink.util.OutputTag could not be inferred.
  15. 【概率论基础进阶】随机事件和概率-古典概型与伯努利概型
  16. 项目生命周期、开发生命周期与产品生命周期的区别
  17. 科学设置百度网盟到访定向,提升竞价转化率!
  18. 【图书】前端工程化:体系设计与实践
  19. 什么是闭包?闭包的优缺点? 1
  20. List(updated 2023.01.29)

热门文章

  1. AlienSkinExposureX8必备的图片后期PS处理软件
  2. HTML连载69-透视属性以及其他属性练习
  3. MATLAB实验三办好,大学物理实验
  4. 榨干我们的老板,宣布了一件细思极恐的决定。
  5. 2018年天猫入驻新规则介绍 商家入驻必看
  6. 金蝶中间件Apusic单机部署并发布服务
  7. HD Tune绿色版结合硬盘再生器HDDREG快速修复硬盘错误
  8. 数据增量抽取项目重演
  9. 计算机一级销售排名,热门笔记本电脑排行榜 TOP前十销量排行榜
  10. 超前点播修改了,网站视频信息采集