本文实例为大家分享了java贪吃蛇游戏展示的具体代码,供大家参考,具体内容如下

1、采用MVC(model、view、control)框架模式
2、包和类的关系树形图为:
3、源码:
package com.huai;
import Java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import com.huai.listener.SnakeListener;
import com.huai.util.Constant;
public class Snake {
//和蛇的监听器有关
Set<SnakeListener> snakeListener = new HashSet<SnakeListener>();
//用链表保存蛇的身体节点
LinkedList<Point> body = new LinkedList<Point>();
private boolean life = true;
//默认速度为400ms
private int speed = 400;
private Point lastTail = null;
private boolean pause = false;
//定义各个方向
public static final int UP = 1;
public static final int DOWN = -1;
public static final int LEFT = 2;
public static final int RIGHT = -2;
int newDirection = RIGHT;
int oldDirection = newDirection;
public Snake(){
initial();
}
public void initial(){
//先清空所有的节点
body.removeAll(body);
int x = Constant.WIDTH/2;
int y = Constant.HEIGHT/2;
//蛇的默认长度为7
for(int i = 0; i < 7; i++){
body.add(new Point(x--, y));
}
}
public void setSpeed(int speed){
this.speed = speed;
}
public void setLife(boolean life){
this.life = life;
}
public boolean getLife(){
return this.life;
}
public boolean getPause(){
return this.pause;
}
public void setPause(boolean pause){
this.pause = pause;
}
public void move(){
//蛇移动的实现所采用的数据结构为:蛇尾删除一个节点,蛇头增加一个节点。
System.out.println("snake move");
if(!(oldDirection + newDirection == 0)){
oldDirection = newDirection;
}
lastTail = body.removeLast();
int x = body.getFirst().x;
int y = body.getFirst().y;
switch(oldDirection){
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}
Point point = new Point(x, y);
body.addFirst(point);
}
//当吃到一个食物的时候,把删掉的蛇尾节点增加回来
public void eatFood(){
System.out.println("snake eat food");
body.addLast(lastTail);
}
public boolean isEatItself(){
for(int i = 2; i < body.size(); i++){
if(body.getFirst().equals(body.get(i))){
return true;
}
}
return false;
}
public void drawMe(Graphics g){
System.out.println("draw snake");
//循环打印蛇的各个身体节点
for(Point p:body){
if(p.equals(body.getFirst())){
//当是蛇头的时候,就设置颜色为橘色
g.setColor(Color.orange);
}else{
g.setColor(Color.pink);
}
g.fill3DRect(p.x * Constant.CELL_SIZE, p.y * Constant.CELL_SIZE,
Constant.CELL_SIZE, Constant.CELL_SIZE, true);
}
}
public void changeDirection(int direction){
System.out.println("snake changeDirection");
this.newDirection = direction;
}
//内部类,新增一个游戏线程
public class DriveSnake implements Runnable{ @Override
public void run() {
while(life){
if(!pause){
//只要让蛇不动就可以暂停游戏
move();
}
//监听蛇每次移动的情况
for(SnakeListener listener : snakeListener){
listener.snakeMove(Snake.this);
}
try {
Thread.sleep(speed);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void startMove(){
new Thread(new DriveSnake()).start();
}
//增加监听器的方法
public void addSnakeListener(SnakeListener listener){
if(listener != null){
snakeListener.add(listener);
}
}
//返回蛇的第一个身体节点
public Point getHead(){
return body.getFirst();
}
//返回蛇的所有身体节点
public LinkedList<Point> getSnakeBody(){
return this.body;
}
public boolean died(){
this.life = false;
return true;
}
}
package com.huai;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import com.huai.util.Constant;
public class Food {
private int x = 0;
private int y = 0;
//设置食物的默认颜色为红色
private Color color = Color.red;
public void newFood(Point point){
x = point.x;
y = point.y;
}
//判断是否被吃到
public boolean isAte(Snake snake){
if(snake.getHead().equals(new Point(x, y))){
System.out.println("food isAte");
return true;
}
return false;
}
public void setFoodColor(Color color){
this.color = color;
}
public Color getFoodColor(){
return this.color;
}
public void drawMe(Graphics g){
System.out.println("draw food");
g.setColor(this.getFoodColor());
g.fill3DRect(x * Constant.CELL_SIZE, y * Constant.CELL_SIZE,
Constant.CELL_SIZE, Constant.CELL_SIZE, true);
}
}
package com.huai;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.LinkedList;
import java.util.Random;
import com.huai.util.Constant;
public class Ground {
//在二维数组中,当为1,表示是砖块
private int[][] rock = new int[Constant.WIDTH][Constant.HEIGHT];
private boolean drawLine = true;
public boolean isDrawLine() {
return drawLine;
}
public void setDrawLine(boolean drawLine) {
this.drawLine = drawLine;
} public Ground(){
for(int x = 0; x < Constant.WIDTH; x++){
for(int y = 0; y < Constant.HEIGHT; y++){
rock[0][y] = 1;
rock[x][0] = 1;
rock[Constant.WIDTH-1][y] = 1;
rock[y][Constant.HEIGHT-1] = 1;
}
}
}
//打印游戏的网格
public void drawGrid(Graphics g){
for(int x = 2; x < Constant.WIDTH; x++){
g.drawLine(x * Constant.CELL_SIZE, 0, x*Constant.CELL_SIZE,
Constant.CELL_SIZE * Constant.HEIGHT);
}
for(int y = 2; y < Constant.HEIGHT; y++){
g.drawLine(0, y * Constant.CELL_SIZE,
Constant.WIDTH*Constant.CELL_SIZE, y*Constant.CELL_SIZE);
}
}
public void drawMe(Graphics g){
System.out.println("draw ground");
//打印围墙
g.setColor(Color.pink);
for(int x = 0; x < Constant.WIDTH; x++){
for(int y = 0; y < Constant.HEIGHT; y++){
if(rock[x][y] == 1){
g.fill3DRect(x * Constant.WIDTH, y * Constant.HEIGHT,
Constant.CELL_SIZE, Constant.CELL_SIZE, true);
}
}
}
if(isDrawLine()){
g.setColor(Color.yellow);
this.drawGrid(g);
}
}
//得到一个随机点
public Point getRandomPoint(Snake snake, Thorn thorn){
Random random = new Random();
boolean isUnderSnakebody = false;
boolean isUnderThorn = false;
int x,y = 0;
LinkedList<Point> snakeBody = snake.getSnakeBody();
LinkedList<Point> thorns = thorn.getThorns();
do{
x = random.nextInt(Constant.WIDTH);
y = random.nextInt(Constant.HEIGHT);
for(Point p:snakeBody){
if(x == p.x && y == p.y){
isUnderSnakebody = true;
}
}
for(Point point : thorns){
if(x == point.x && y == point.y){
isUnderThorn = true;
}
}
}while(rock[x][y] == 1 && !isUnderSnakebody && !isUnderThorn);
return new Point(x, y);
}
public boolean isSnakeHitRock(Snake snake){
System.out.println("snack hit rock");
for(int i = 0; i < Constant.WIDTH; i++){
for(int j = 0; j < Constant.HEIGHT; j++){
if(snake.getHead().x == i &&
snake.getHead().y == j && rock[i][j] == 1){
return true;
}
}
}
return false;
}
}
package com.huai
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.LinkedList;
import com.huai.util.Constant;
public class Thorn { int x, y;
private LinkedList<Point> thorns = new LinkedList<Point>();
//返回所有荆棘的链表
public LinkedList<Point> getThorns(){
return this.thorns;
}
public void newThorn(Point point){
x = point.x;
y = point.y;
thorns.add(new Point(x, y));
}
public void drawMe(Graphics g){
System.out.println("draw thorns");
for(Point p: thorns){
int[] xb = {p.x*Constant.CELL_SIZE,
(p.x*Constant.CELL_SIZE +Constant.CELL_SIZE/2),
(p.x*Constant.CELL_SIZE+Constant.CELL_SIZE),
(p.x*Constant.CELL_SIZE+Constant.CELL_SIZE/4*3),
(p.x*Constant.CELL_SIZE+Constant.CELL_SIZE),
(p.x*Constant.CELL_SIZE+Constant.CELL_SIZE/2),
p.x*Constant.CELL_SIZE,
(p.x*Constant.CELL_SIZE+Constant.CELL_SIZE/4),
p.x*Constant.CELL_SIZE};
int [] yb = {p.y*Constant.CELL_SIZE,
(p.y*Constant.CELL_SIZE+Constant.CELL_SIZE/4),
p.y*Constant.CELL_SIZE,
(p.y*Constant.CELL_SIZE+Constant.CELL_SIZE/2),
(p.y*Constant.CELL_SIZE+Constant.CELL_SIZE),
(int)(p.y*Constant.CELL_SIZE+Constant.CELL_SIZE*0.75),
(p.y*Constant.CELL_SIZE+Constant.CELL_SIZE),
(p.y*Constant.CELL_SIZE+Constant.CELL_SIZE/2),
p.y*Constant.CELL_SIZE};
g.setColor(Color.darkGray);
g.fillPolygon(xb, yb, 8);
}
}
public boolean isSnakeHitThorn(Snake snake){
for(Point points : thorns){
if(snake.getHead().equals(points)){
System.out.println("hit thorn");
return true;
}
}
return false;
}
}
package com.huai.listener;
import com.huai.Snake;
public interface SnakeListener {
public void snakeMove(Snake snake);
}
package com.huai.util;public class Constant {
public static int CELL_SIZE = 20;
public static int WIDTH = 20;
public static int HEIGHT = 20;
}
package com.huai.view;
import java.awt.Color;
import java.awt.Graphics;import javax.swing.JPanel;import com.huai.Food;
import com.huai.Ground;
import com.huai.Snake;
import com.huai.Thorn;
import com.huai.util.Constant;public class GamePanel extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
Snake snake;
Food food;
Ground ground;
Thorn thorn;
public void display(Snake snake, Food food, Ground ground, Thorn thorn){
this.snake = snake;
this.food = food;
this.ground = ground;
this.thorn = thorn;
System.out.println("display gamePanel");
this.repaint();
}
@Override
protected void paintComponent(Graphics g) {
if(snake != null && food != null && ground != null){
g.setColor(Color.lightGray);
g.fillRect(0, 0, Constant.WIDTH*Constant.CELL_SIZE,
Constant.HEIGHT*Constant.CELL_SIZE);
snake.drawMe(g);
food.drawMe(g);
ground.drawMe(g);
thorn.drawMe(g);
}else{
System.out.println("snake = null || food = null || ground = null");
}
}
}
package com.huai.controller;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;import com.huai.Food;
import com.huai.Ground;
import com.huai.Snake;
import com.huai.Thorn;
import com.huai.listener.SnakeListener;
import com.huai.view.GamePanel;public class Controller extends KeyAdapter implements SnakeListener{
/**
* 整个游戏的控制类,属于MVC设计框架中的Controller
* 其中包括控制游戏的监听事件和游戏逻辑
*/
Snake snake;
Food food;
Ground ground;
GamePanel gamePanel;
Thorn thorn;
public Controller(){}
//利用构造方法初始化对象
public Controller(Snake snake, Food food, Ground ground, GamePanel gamePanel, Thorn thorn) {
super();
this.snake = snake;
this.food = food;
this.ground = ground;
this.gamePanel = gamePanel;
this.thorn = thorn;
}
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_UP:
snake.changeDirection(Snake.UP);
snake.setSpeed(150);
break;
case KeyEvent.VK_DOWN:
snake.changeDirection(Snake.DOWN);
snake.setSpeed(150);
break;
case KeyEvent.VK_LEFT:
snake.changeDirection(Snake.LEFT);
snake.setSpeed(150);
break;
case KeyEvent.VK_RIGHT:
snake.changeDirection(Snake.RIGHT);
snake.setSpeed(150);
break;
case KeyEvent.VK_ENTER:
if(!snake.getPause() && snake.getLife()){
//暂停游戏
snake.setPause(true);;
}else if(!snake.getLife()){
//重新开始游戏
snake.setLife(true);
snake.initial();
snake.changeDirection(Snake.UP);
thorn.getThorns().removeAll(thorn.getThorns());
this.startGame();
}else{
snake.setPause(false);
}
break;
case KeyEvent.VK_L:
//当按下L按钮时,是否显示游戏网格
if(ground.isDrawLine()){
ground.setDrawLine(false);
}else{
ground.setDrawLine(true);
}
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_UP:
snake.setSpeed(400);
break;
case KeyEvent.VK_DOWN:
snake.setSpeed(400);
break;
case KeyEvent.VK_LEFT:
snake.setSpeed(400);
break;
case KeyEvent.VK_RIGHT:
snake.setSpeed(400);
break;
}
}
//这是实现SnakeListener监听器所Override的方法
@Override
public void snakeMove(Snake snake) {
//显示snake ,food,ground,和thorn
gamePanel.display(snake, food, ground, thorn);
if(ground.isSnakeHitRock(snake)){
snake.died();
}
if(snake.isEatItself()){
snake.died();
}
if(food.isAte(snake)){
snake.eatFood();
food.newFood(ground.getRandomPoint(snake, thorn));
thorn.newThorn(ground.getRandomPoint(snake, thorn));
}
if(thorn.isSnakeHitThorn(snake)){
snake.died();
}
}
public void startGame(){
snake.startMove();//这个将会启动一个新的线程
food.newFood(ground.getRandomPoint(snake, thorn));
thorn.newThorn(ground.getRandomPoint(snake, thorn));
}
}
package com.huai.game;
import java.awt.BorderLayout;
import java.awt.Color;import javax.swing.JFrame;
import javax.swing.JLabel;import com.huai.Food;
import com.huai.Ground;
import com.huai.Snake;
import com.huai.Thorn;
import com.huai.controller.Controller;
import com.huai.util.Constant;
import com.huai.view.GamePanel;public class Game {
public static void main(String args[]){
Snake snake = new Snake();
Food food = new Food();
GamePanel gamePanel = new GamePanel();
Ground ground = new Ground();
Thorn thorn = new Thorn();
Controller controller = new Controller(snake, food, ground, gamePanel, thorn);
JFrame frame = new JFrame("怀哥的小小蛇儿游戏");
frame.add(gamePanel);
frame.setBackground(Color.magenta);
frame.setSize(Constant.WIDTH*Constant.CELL_SIZE+6,
Constant.HEIGHT*Constant.CELL_SIZE+40);
gamePanel.setSize(Constant.WIDTH*Constant.CELL_SIZE,
Constant.HEIGHT*Constant.CELL_SIZE);
frame.add(gamePanel);
frame.setResizable(false);//不可改变窗口大小
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
gamePanel.addKeyListener(controller);
snake.addSnakeListener(controller);
frame.addKeyListener(controller);
JLabel label1 = new JLabel();
label1.setBounds(0, 400, 400, 100);
label1.setText(" ENTER=>>PAUSE or AGAIN; "
+ " L=>DRAWGRID");
label1.setForeground(Color.BLACK);
frame.add(label1, BorderLayout.SOUTH);
controller.startGame();
}
}
更多精彩游戏,请参考专题《java经典小游戏》
更多有趣的经典小游戏实现专题,分享给大家:
C++经典小游戏汇总
python经典小游戏汇总
python俄罗斯方块游戏集合
JavaScript经典游戏 玩不停
javascript经典小游戏汇总
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# java
# 贪吃蛇
# 游戏
# java实现的简单猜数字游戏代码
# java编写贪吃蛇小游戏
# Java完美实现2048小游戏
# java实现五子棋小游戏
# Java编写迷宫小游戏
# Java实现打飞机小游戏(附完整源码)
# java实现简单扫雷小游戏
# java简易小游戏制作代码
# 利用Java实现玩家打怪小游戏的完整过程
# 经典小游戏
# 吃到
# 这是
# 链表
# 蛇尾
# 第一个
# 将会
# 数据结构
# 给大家
# 不动
# 要让
# 按下
# 图为
# 大家分享
# 更多精彩
# 具体内容
# 请参考
# 大家多多
# 清空
# 就可以
相关文章:
,想在网上投简历,哪几个网站比较好?
网站建设设计制作营销公司南阳,如何策划设计和建设网站?
如何在VPS电脑上快速搭建网站?
ppt在线制作免费网站推荐,有什么下载免费的ppt模板网站?
如何在Golang中使用replace替换模块_指定本地或远程路径
手机钓鱼网站怎么制作视频,怎样拦截钓鱼网站。怎么办?
建站主机系统SEO优化与智能配置核心关键词操作指南
深圳网站制作案例,网页的相关名词有哪些?
开封网站制作公司,网络用语开封是什么意思?
详解一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)
如何设计高效校园网站?
相亲简历制作网站推荐大全,新相亲大会主持人小萍萍资料?
武汉网站如何制作,黄黄高铁武穴北站途经哪些村庄?
如何在云虚拟主机上快速搭建个人网站?
深圳网站制作费用多少钱,读秀,深圳文献港这样的网站很多只提供网上试读,但有些人只要提供试读的文章就能全篇下载,这个是怎么弄的?
如何在万网自助建站中设置域名及备案?
大连网站设计制作招聘信息,大连投诉网站有哪些?
魔毅自助建站系统:模板定制与SEO优化一键生成指南
,石家庄四十八中学官网?
已有域名和空间如何快速搭建网站?
矢量图网站制作软件,用千图网的一张矢量图做公司app首页,该网站并未说明版权等问题,这样做算不算侵权?应该如何解决?
电商平台网站制作流程,电商网站如何制作?
网站专业制作公司有哪些,做一个公司网站要多少钱?
建站DNS解析失败?如何正确配置域名服务器?
如何获取PHP WAP自助建站系统源码?
如何配置FTP站点权限与安全设置?
大型企业网站制作流程,做网站需要注册公司吗?
阿里云网站搭建费用解析:服务器价格与建站成本优化指南
如何快速搭建高效WAP手机网站吸引移动用户?
如何快速搭建支持数据库操作的智能建站平台?
高防网站服务器:DDoS防御与BGP线路的AI智能防护方案
网站设计制作书签怎么做,怎样将网页添加到书签/主页书签/桌面?
建站之星导航配置指南:自助建站与SEO优化全解析
哪家制作企业网站好,开办像阿里巴巴那样的网络公司和网站要怎么做?
制作网站哪家好,cc、.co、.cm哪个域名更适合做网站?
SAX解析器是什么,它与DOM在处理大型XML文件时有何不同?
C++如何将C风格字符串(char*)转换为std::string?(代码示例)
图片制作网站免费软件,有没有免费的网站或软件可以将图片批量转为A4大小的pdf?
网站按钮制作软件,如何实现网页中按钮的自动点击?
网站制作网站,深圳做网站哪家比较好?
官网网站制作腾讯审核要多久,联想路由器newifi官网
深圳网站制作平台,深圳市做网站好的公司有哪些?
建站之星在线客服如何快速接入解答?
企业宣传片制作网站有哪些,传媒公司怎么找企业宣传片项目?
高端建站如何打造兼具美学与转化的品牌官网?
湖南网站制作公司,湖南上善若水科技有限公司做什么的?
小型网站制作HTML,*游戏网站怎么搭建?
郑州企业网站制作公司,郑州招聘网站有哪些?
家庭建站与云服务器建站,如何选择更优?
导航网站建站方案与优化指南:一站式高效搭建技巧解析
*请认真填写需求信息,我们会在24小时内与您取得联系。