这两天学着做了一个简单的贪吃蛇,只是为了练习用,所以很多地方都不完美

实现方式是用链表,代码中有详细注释

活动区域Yard:

<span style="font-size:14px;">import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;public class Yard extends Frame {// 活动区域private static final int ROWS = 30;// 行数private static final int COLS = 30;// 列数private static final int BLOCK_SIZE = 15;// 格子尺寸private Font fontGameOver = new Font("宋体", Font.BOLD, 50);//字体private int score = 0;// 分数Image offScreenImage = null;// 创建一个位图,防止闪烁Snake snake = new Snake(this);// 创建一个蛇Egg e = new Egg();// 随机创建一个蛋;PaintThread paintThread = new PaintThread();private boolean gameOver=false;//判断游戏是否结束public static int getROWS() {return ROWS;}public static int getCOLS() {return COLS;}public static int getBLOCK_XIZE() {return BLOCK_SIZE;}public int getScore() {return score;}public void launch() {// 设置窗体this.setLocation(300, 300);// 窗口出现位置this.setSize(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE);// 窗口大小// 添加关闭事件this.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {System.exit(0);}});this.setVisible(true);// 窗口是否显示this.addKeyListener(new KeyMonitor());// 监听按键new Thread(paintThread).start();/// 启动线程}public static void main(String[] args) {// TODO Auto-generated method stubnew Yard().launch();}public void setScore(int score) {// 设置分数this.score = score;}@Overridepublic void paint(Graphics g) {// 画// 设置背景颜色Color c = g.getColor();g.setColor(Color.GRAY);g.fillRect(0, 0, COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE);// 设置线的颜色g.setColor(Color.DARK_GRAY);// 画线for (int i = 1; i < ROWS; i++) {g.drawLine(0, i * BLOCK_SIZE, COLS * BLOCK_SIZE, BLOCK_SIZE * i);}for (int i = 1; i < ROWS; i++) {g.drawLine(i * BLOCK_SIZE, 0, BLOCK_SIZE * i, ROWS * BLOCK_SIZE);}g.setColor(Color.YELLOW);g.drawString("score:" + score, 10, 60);// 画分数if(gameOver) {g.setFont(fontGameOver);g.drawString("游戏结束", 120, 180);paintThread.pause();}g.setColor(c);snake.eat(e);snake.draw(g);// 画蛇e.draw(g);// 画蛋}@Overridepublic void update(Graphics g) {if (offScreenImage == null) {offScreenImage = this.createImage(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE);}Graphics gOff = offScreenImage.getGraphics();paint(gOff);g.drawImage(offScreenImage, 0, 0, null);}public void stop() {gameOver=true;//游戏结束}private class PaintThread implements Runnable {private boolean running = true;private boolean pause = false;public void run() {while(running) {if(pause) continue; else repaint();try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}}}public void pause() {this.pause = true;}public void reStart() {this.pause = false;snake = new Snake(Yard.this);gameOver = false;}public void gameOver() {running = false;}}private class KeyMonitor extends KeyAdapter {// 监听键值@Overridepublic void keyPressed(KeyEvent e) {int key = e.getKeyCode();if(key == KeyEvent.VK_F2) {paintThread.reStart();}snake.keyPressed(e);}}
}
</span>

蛇Snake

<span style="font-size:14px;">import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;public class Snake {private Node head = null;// 头结点private Node tail = null;// 尾结点private int size = 0;// 结点个数private Node node = new Node(20, 30, Direction.LEFT);// 初始结点(蛇)private Yard y;//在哪个范围内public Snake(Yard y) {head = node;tail = node;size = 1;this.y=y;}public void addToTail() {// 结点添加到尾巴Node node = null;switch (tail.dir) {case LEFT:node = new Node(tail.row, tail.col + 1, tail.dir);// 向左新建结点break;case RIGHT:node = new Node(tail.row, tail.col - 1, tail.dir);break;case UP:node = new Node(tail.row + 1, tail.col, tail.dir);break;case DOWN:node = new Node(tail.row - 1, tail.col, tail.dir);break;}// 添加尾结点tail.next = node;node.prev = tail;tail = node;size++;}public void addToHead() {// 结点添加到头Node node = null;switch (head.dir) {case LEFT:node = new Node(head.row, head.col - 1, head.dir);break;case UP:node = new Node(head.row - 1, head.col, head.dir);break;case RIGHT:node = new Node(head.row, head.col + 1, head.dir);break;case DOWN:node = new Node(head.row + 1, head.col, head.dir);break;}node.next = head;head.prev = node;head = node;size++;}private void deleteFromTail() {if (size == 0)return;tail = tail.prev;tail.next = null;}private void checkDead() {// 检验是否死亡if(head.row < 2 || head.col < 0 || head.row > Yard.getROWS()|| head.col > Yard.getCOLS())  {y.stop();}for(Node n = head.next; n != null; n = n.next) {if(head.row == n.row && head.col == n.col) {y.stop();}}}private void move() {// 蛇移动addToHead();// 把尾巴结点添加到头deleteFromTail();checkDead();}public void draw(Graphics g) {// 画结点if (size <= 0)return;move();for (Node n = head; n != null; n = n.next) {n.draw(g);}}private class Node {int w = Yard.getBLOCK_XIZE();// 结点宽度int h = Yard.getBLOCK_XIZE();// 结点高度int row, col;// 结点位置Direction dir = Direction.LEFT;// 初始结点向左Node next = null;// 下一节Node prev = null;// 前一节Node(int row, int col, Direction dir) {this.row = row;this.col = col;this.dir = dir;}void draw(Graphics g) {// 画出结点Color c = g.getColor();g.setColor(Color.black);g.fillRect(Yard.getBLOCK_XIZE() * col, Yard.getBLOCK_XIZE() * row, w, h);g.setColor(c);}}public void eat(Egg e) {if(this.getRect().intersects(e.getRect())) {e.reAppear();this.addToHead();y.setScore(y.getScore() + 5);}}private Rectangle getRect() {return new Rectangle(Yard.getBLOCK_XIZE() * head.col, Yard.getBLOCK_XIZE() * head.row, head.w, head.h);}public void keyPressed(KeyEvent e) {int key = e.getKeyCode();switch (key) {case KeyEvent.VK_LEFT:if (head.dir != Direction.RIGHT)head.dir = Direction.LEFT;break;case KeyEvent.VK_RIGHT:if (head.dir != Direction.LEFT)head.dir = Direction.RIGHT;break;case KeyEvent.VK_UP:if (head.dir != Direction.DOWN)head.dir = Direction.UP;break;case KeyEvent.VK_DOWN:if (head.dir != Direction.UP)head.dir = Direction.DOWN;break;}}
}
</span>

目标物体Egg:

<span style="font-size:14px;">import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;public class Egg {int row,col;int w=Yard.getBLOCK_XIZE();int h=Yard.getBLOCK_XIZE();private static Random r=new Random();//蛋的随机生成位置private Color color=Color.green;//蛋初始颜色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 Egg(int row, int col) {this.row = row;this.col = col;}public Egg(){this(r.nextInt(Yard.getROWS()-2)+2, r.nextInt(Yard.getCOLS()));}public void reAppear(){//重新设定蛋的位置this.row = r.nextInt(Yard.getROWS()-2) + 2;this.col = r.nextInt(Yard.getCOLS());}public Rectangle getRect() {return new Rectangle(Yard.getBLOCK_XIZE() * col, Yard.getBLOCK_XIZE() * row, w, h);}void draw(Graphics g) {// 画出蛋Color c = g.getColor();g.setColor(color);g.fillOval(Yard.getBLOCK_XIZE() * col, Yard.getBLOCK_XIZE() * row, w, h);g.setColor(c);if(color==Color.green){color=color.red;}else{color=color.green;}}
}
</span>

方向direction

<span style="font-size:14px;">public enum Direction {LEFT,RIGHT,UP,DOWN
}
</span>

Java实现简单的贪吃蛇相关推荐

  1. 隐藏窗口 java swing_Java简单实现贪吃蛇经典小游戏(附源代码)

    在我们学习java的时候,为了提高我们的兴趣,我们经常会使用所学到的知识去做一些小游戏,这篇blog就介绍了一个经典而且好理解的小游戏-贪吃蛇. 一.使用知识 Jframe GUI 双向链表 线程 二 ...

  2. 贪吃蛇java 暂停_Java实现贪吃蛇小游戏

    三月份的时候用Java写了一个贪吃蛇的小游戏,写完的时候颇有成就感,现在在这里做一下总结. 先把需要用到的图片资源放在这里,分别为上.下.左.右方向的蛇头,蛇身,食物,标题,可以通过右击另存为的方式下 ...

  3. 台州学院acm:3128 简单版贪吃蛇

    3128: 简单版贪吃蛇  时间限制(普通/Java):1000MS/3000MS     内存限制:65536KByte 总提交: 545            测试通过:169 Special J ...

  4. STM32+LCD实现简单的贪吃蛇小游戏

    寒假放假回家,只能宅在家里,无聊之余,幸好带了一块开发板回来,以前做项目都是在网上找相似或者有关联的项目,把别人的代码拿过来,修改修改,拼拼凑凑出自己项目,既然无聊就自己动脑筋思考,自己动手写贪吃蛇的 ...

  5. VC环境下简单的贪吃蛇

    下午真无聊的不知道干什么了,翻翻自己以前写的代码,偶然看到大一时写的这个简单的贪吃蛇,自己玩了几把后还是决定发到博客吧.(实在无聊,打发时间) 注:完全基于VC++6.0环境,不支持Linux 下te ...

  6. 一个简单的贪吃蛇游戏 c

    一个简单的贪吃蛇游戏 #include "pch.h" #include <iostream> #include<stdio.h> #include< ...

  7. 计算机毕业设计-基于Java的GUI实现贪吃蛇小游戏

    标题:基于Java多线程版本GUI贪吃蛇小游戏 1.项目技术点 1.多线程的运用. 2.JAVA的GUI的运用. 3.数据结构的灵活运用. 4.随机食物的生成. 5.关卡加速,随着蛇身增长,蛇的速度也 ...

  8. Python 简单实现贪吃蛇小游戏

    文章目录 1. pygame库的简介2. pygame库的安装3. python代码实现贪吃蛇小游戏4. pyinstaller打包成exe 很多人学习python,不知道从何学起. 很多人学习pyt ...

  9. 老滚5初始化python失败_五分钟学会怎么用python做一个简单的贪吃蛇

    Pygame 是一组用来开发游戏软件的 Python 程序模块,基于 SDL 库的基础上开发.我们今天将利用它来制作一款大家基本都玩过的小游戏--贪吃蛇. 一.需要导入的包 import pygame ...

最新文章

  1. .NET Core 2.1改进了性能,并提供了新的部署选项
  2. Linux安装卸载mysql
  3. Android开发-mac上使用三星S3做真机调试
  4. 结巴分词jieba添加自定义词典
  5. 【公开课预告】百度语言与知识最新技术成果详解
  6. c++11-std::functionbind
  7. oracle11g约束有哪几种状态,【简答题】数据完整性通常有哪几种类型, Oracle11g 通过哪些方式来进行数据完整性控制...
  8. Invalid argument: Key: label. Data types don't match. Data type: int64 but expected type: float
  9. docker构建oracle集群,docker 构建 oracle数据库 镜像-Go语言中文社区
  10. Adobe illustrator 调整图例为2列 - 连载 16
  11. UPS不间断电源的种类有哪些 常见的3类UPS电源
  12. THREEJS - mousedown/mouseup等鼠标相关事件失效
  13. 上海特斯拉发那科机器人视觉引导程序备份
  14. mysql io 优化_mysql 中io优化
  15. AD7705模数转换芯片工作原理
  16. 3.2.2 方法的重写 3.2.3 super关键字
  17. 企业办理的icp许可证领取需要什么手续
  18. C语言基础向——二级总结
  19. 更进阶的实战效率、更准确的研究成果——欢迎参加材料计算PWmat进阶小组会
  20. 一个简单的监控系统的设计

热门文章

  1. ospf避免环路_多进程OSPF发布LSA形成路由环路的规避办法
  2. 【问题】C4D中设置了界面颜色,如何恢复默认?
  3. 12【C语言 趣味算法】存钱问题(四层for循环,if判断)
  4. Python中私有变量和私有方法芳
  5. 2016年3月4日。
  6. 艾默生Micromotion质量流量计的应用总结
  7. 用VLC开发视频播放器/组件(两种方式:libVLC / VLC-Qt)
  8. 理解GAM和SGAM页
  9. 如何使用JiaoZiVideoPlayer(饺子视频播放器)播放avi格式的视频
  10. NCBI网页上进行Nr注释