目录

一、实验内容:

二、实验准备

三、程序代码

四、成果展示


一、实验内容:

1)实现贪吃蛇游戏基本功能,屏幕上随机出现一个“食物”,称为豆子。玩家能利用上下左右键控制“蛇”的移动,“蛇”吃到“豆子”后“蛇”身体加长一节,得分增加,“蛇”碰到边界或蛇头与蛇身相撞,“蛇”死亡,游戏结束。

2)进行交互界面的设计,要有开始键、暂停键和停止退出的选项,能够控制游戏进程。对蛇吃到豆子进行分值计算,可以设置游戏速度,游戏音乐等拓展元素。

二、实验准备

(1)java的thread类_thread 类详解:

http://​  java的thread类_thread 类详解_沐LaLa的博客-CSDN博客 ​

(2) Java 窗口设置图标及背景图片:

Java 窗口设置图标及背景图片_橘月零八的博客-CSDN博客_java窗口设置背景图

(3) JAVA界面编程之弹窗、弹框JOptionPane的showMessageDialog方法详解:

JAVA界面编程之弹窗、弹框JOptionPane的showMessageDialog方法详解_一个只有绵薄之力的老年人-CSDN博客_showmessagedialog参数

(4)) Java中加背景音乐

等 https://blog.csdn.net/qq_44752978/article/details/116297832

三、程序代码

进入游戏初窗口界面设置 kaishi

package Sanke;import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;public class kaishi extends JFrame implements ActionListener {JButton button = new JButton();Image im;SnakeGrid snakeGrid= new SnakeGrid();public kaishi(){this.setTitle("Snakebite games");Font font3 = new Font("宋体", 0, 16);button.addActionListener(this); //添加监视器this.add(button);this.setBounds(250, 170, 700, 525);//设置窗口大小this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //设置按关闭键即可关闭窗体//创建面板JPaneLJPanel panel = new JPanel();this.add(panel);panel.setLayout(null);JLabel userLabel1 = new JLabel("欢迎来到贪吃蛇游戏");userLabel1.setBounds(210, 50, 400, 25);userLabel1.setFont(new Font("黑体", Font.BOLD, 26));panel.add(userLabel1);JLabel userLabel = new JLabel("昵称: ");userLabel.setBounds(212, 130, 80, 25);userLabel.setFont(new Font("TimesRoman", Font.BOLD, 18));panel.add(userLabel);JTextField userText = new JTextField(20);userText.setBounds(270, 125, 185, 30);panel.add(userText);JLabel userLabel2= new JLabel("玩法说明:");JLabel userLabel4= new JLabel("按动方向键↑ ↓ ← →控制蛇的移动方向");JLabel userLabel3= new JLabel("每吃到一个食物加10分");userLabel2.setBounds(370, 180, 450, 25);userLabel2.setFont(font3);panel.add(userLabel2);//玩法说明userLabel3.setBounds(370, 227, 400, 28);userLabel3.setFont(font3);panel.add(userLabel3);userLabel4.setBounds(370, 205,450, 28);userLabel4.setFont(font3);panel.add(userLabel4);
//创建登陆按钮(JButton)JButton loginButton = new JButton("进 入 游 戏");loginButton.setBounds(220, 320, 250, 50);//字体的更换实现loginButton.setFont(new Font("TimesRoman", Font.BOLD, 22));panel.add(loginButton);loginButton.addActionListener(this);//加入事件监听setContentPane(panel);panel.setOpaque(false);//设置面板背景为透明init();this.setVisible(true);  //可视化}//窗口图标背景public void init() {ImageIcon ig = new ImageIcon("src/Sanke/9.jpg");im = ig.getImage();setIconImage(im);ImageIcon img = new ImageIcon("src/Sanke/4.jpg");JLabel imgLabel = new JLabel(img);this.getLayeredPane().add(imgLabel, new Integer(Integer.MIN_VALUE));//将背景标签添加到jfram的LayeredPane面板里。imgLabel.setBounds(0, 0, 700, 500);}//切换下一个窗体@Overridepublic void actionPerformed(ActionEvent e) {this.setVisible(false);  new SnakeGame();  }//主函数public static void main(String[] args) {new kaishi();}
}

游戏界面窗口设置 SnakeGame

package Sanke;import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;/*** @author Swyee**/
public class SnakeGame extends JFrame {public static int gameScore=0;private static JLabel score;public static int speed=0;SnakeGrid snakeGrid= new SnakeGrid();Button button = new Button(snakeGrid);Image im;public static boolean isMove=true;//表示运行状态SnakeGame(){this.setTitle("Sanke");this.setBounds(250, 170, 700, 510);//设置窗口大小this.setLayout(null);//更改layout 以便添加组件this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭窗口的状态this.setResizable(false);//窗口不可以改变大小Font font2 = new Font("TimesRoman", Font.BOLD, 21);JPanel panel = new JPanel();this.add(panel);panel.setLayout(null);JPanel panel2 = new JPanel();this.add(panel2);panel2.setBounds(370, 390, 240, 60);score = new JLabel("目前得分:   "+gameScore , JLabel.CENTER);panel2.add(score);score.setFont(font2);//score.setForeground(Color.white);//设置颜色new Thread(()->{while(true) {playMusic();}}).start();// Lambda表达式JLabel userLabel1 = new JLabel("在左上角选择游戏速度即可开始");userLabel1.setFont(new Font("宋体", 0, 12));panel2.add(userLabel1);init()this.add(snakeGrid);this.add(button);snakeGrid.setFocusable(true);snakeGrid.requestFocus();this.setVisible(true);JMenuBar menubar= new JMenuBar();this.setJMenuBar(menubar);JMenu Operation=new JMenu("速度");JMenuItem add=new JMenuItem("快");JMenuItem sub=new JMenuItem("中");JMenuItem mul=new JMenuItem("慢");//div.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_MASK));menubar.add(Operation);Operation.add(add);Operation.add(sub);Operation.add(mul);add.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {speed=1;snakeGrid.snakeThread.start();}});sub.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {speed=2;snakeGrid.snakeThread.start();}});mul.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {speed=3;snakeGrid.snakeThread.start();}});}public static JLabel getJTextArea() {return score;}
//设置窗口图标public void init() {ImageIcon ig = new ImageIcon("src/Sanke/8.jpg");im = ig.getImage();setIconImage(im);}// 背景音乐播放static void playMusic() {try {AudioInputStream ais = AudioSystem.getAudioInputStream(new File("src/Sanke/1.wav"));AudioFormat aif = ais.getFormat();final SourceDataLine sdl;DataLine.Info info = new DataLine.Info(SourceDataLine.class, aif);sdl = (SourceDataLine) AudioSystem.getLine(info);sdl.open(aif);sdl.start();FloatControl fc = (FloatControl) sdl.getControl(FloatControl.Type.MASTER_GAIN);double value = 2;float dB = (float) (Math.log(value == 0.0 ? 0.0001 : value) / Math.log(10.0) * 20.0);fc.setValue(dB);int nByte = 0;int writeByte = 0;final int SIZE = 1024 * 64;byte[] buffer = new byte[SIZE];while (nByte != -1) {nByte = ais.read(buffer, 0, SIZE);sdl.write(buffer, 0, nByte);}sdl.stop();}catch (Exception e) {e.printStackTrace();}}
}

窗口及速度设置 SnakeGrid

package Sanke;import java.awt.*;
import java.awt.event.*;
import javax.swing.*;/*** @author Swyee**/
public class SnakeGrid extends JPanel {Food food = new Food();Snake snake = new Snake(food);//创建蛇ImageIcon image = new ImageIcon("src/Sanke/5.png");//图片文件地址SnakeThread snakeThread = new SnakeThread();JPanel panel = new JPanel();SnakeGrid(){this.setBounds(0, 0, 690, 390);this.add(panel);this.addKeyListener(new KeyAdapter() {@Overridepublic void keyPressed(KeyEvent e) {snake.keyboard(e);}});}/*** 设置画笔* @param g*/@Overridepublic void paint(Graphics g) {super.paint(g);image.paintIcon(this, g, 0, 0); //设置背景图片snake.move();//蛇移动snake.draw(g);food.draw(g);}class SnakeThread extends Thread{boolean flag = true;@Overridepublic void run() {while(Snake.islive &&flag){try {switch (SnakeGame.speed) {case 1 -> Thread.sleep(95);case 2 -> Thread.sleep(170);case 3 -> Thread.sleep(240);}} catch (InterruptedException e) {e.printStackTrace();// TODO Auto-generated catch block}if(Snake.islive&& Button.isMove){repaint();}}if(flag){JOptionPane.showMessageDialog(SnakeGrid.this, "游戏结束"+"\n"+"你的得分为: "+SnakeGame.gameScore);}}public void stopThread(){flag=false;}}
}

游戏窗口按键设置 Button

package Sanke;import javax.swing.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class Button extends JPanel{public static boolean isMove=true;//表示运行状态SnakeGrid snakeGrid;int n=0;Button(SnakeGrid snakeGrid){this.snakeGrid=snakeGrid;this.setBounds(5, 398,280, 50);JButton jb1 = new JButton("暂停游戏");JButton jb2 = new JButton("继续游戏");JButton jb3 = new JButton("重新开始");this.add(jb1);this.add(jb2);this.add(jb3);jb1.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {isMove=false;}});jb2.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {isMove=true;snakeGrid.setFocusable(true);snakeGrid.requestFocus();}});jb3.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {//重新创建蛇等 重新开始游戏snakeGrid.snakeThread.stopThread();Food food = new Food();snakeGrid.food=food;snakeGrid.snake=new Snake(food);Snake.islive=true;isMove=true;SnakeGrid.SnakeThread st = snakeGrid.new SnakeThread();snakeGrid.snakeThread=st;st.start();SnakeGame.gameScore=0;SnakeGame.getJTextArea().setText("目前得分:   "+SnakeGame.gameScore + "");snakeGrid.setFocusable(true);snakeGrid.requestFocus();}});}
}

蛇的设置 Snake

package Sanke;import java.awt.*;
import java.awt.event.KeyEvent;/*** @author Swyee*/
public class Snake {public static int n;public static final int span=15;//间距public static final int rows=26;//行public static final int cols=46;//列public static final String up="u";public static final String down="d";public static final String left="l";public static final String right="r";public static boolean islive=true;Node body;//蛇的身体Node head;//蛇的头部Node tail;//蛇的头部Food food;Snake(Food food){body = new Node(13,23,left);head = body;tail = body;this.food=food;}class Node{int row;int col;String dir;//方向Node next;Node pre;Node(int row,int col,String dir){this.row = row;this.col = col;this.dir = dir;}public void draw(Graphics g) {g.fillOval (col*span, row*span, span,span);//坐标}}public void draw(Graphics g) {g.setColor(Color.yellow);for(Node n=head;n!=null;n=n.next){n.draw(g);g.setColor(Color.ORANGE);}}public void keyboard(KeyEvent e) {switch(e.getKeyCode()){case KeyEvent.VK_UP:if(head.dir.equals(down)){break;}head.dir=up;break;case KeyEvent.VK_DOWN:if(head.dir.equals(up)){break;}head.dir=down;break;case KeyEvent.VK_LEFT:if(head.dir.equals(right)){break;}head.dir=left;break;case KeyEvent.VK_RIGHT:if(head.dir.equals(left)){break;}head.dir=right;break;default:break;}}public void addHead(){Node node = null;switch (head.dir){case "l":node = new Node(head.row,head.col-1,head.dir);break;case "r":node = new Node(head.row,head.col+1,head.dir);break;case "u":node = new Node(head.row-1,head.col,head.dir);break;case "d":node = new Node(head.row+1,head.col,head.dir);break;default:break;}node.next=head;head.pre=node;head=node;}public void deleteTail(){tail.pre.next=null;tail=tail.pre;}/*增加move方法*/public void move() {addHead();if(this.getSnakeRectangle().intersects(food.getCoordinates())){//当蛇头与食物重合的时候 蛇吃食物 食物刷新,不再删除尾巴,达到一种蛇增长的要求SnakeGame.gameScore=SnakeGame.gameScore+10;SnakeGame.getJTextArea().setText("目前得分:   "+SnakeGame.gameScore + "");n=n+10;food.repearShow();}else{deleteTail();}DeadOrLive();}public Rectangle getSnakeRectangle(){return new Rectangle(head.col*span,head.row*span,span,span);}public void DeadOrLive(){//超出边框范围 蛇头撞到身体 游戏结束if(head.row<0 || head.row>rows-1 || head.col<0 ||head.col>cols){islive=false;}for(Node n=head.next;n!=null;n=n.next){if(n.col==head.col && n.row==head.row){islive=false;}}}}

食物的生成 Food

package Sanke;import java.awt.*;public class Food {int row;int col;Food(){row = 5;//创建食物的大小col  =15;}public void repearShow(){row = (int)(Math.random()*23);//生成随机数 乘以食物的大小可以得到坐标col = (int)(Math.random()*43);}public void draw(Graphics g) {//把食物画出来g.setColor(Color.cyan);g.fillOval(col*15, row*15, 15, 15);//表示坐标}public Rectangle getCoordinates(){return new Rectangle(col*15,row*15,15,15);//获得食物的坐标}}

四、成果展示

.

软件实习项目二:贪吃蛇的游戏开发相关推荐

  1. 计算机软件实习项目二 —— 贪吃蛇游戏 (实验准备)

    目录 一.实验目的 二.编程语言和平台 三.实验难点: 四.参考资料 一.实验目的 1.实现贪吃蛇游戏基本功能,屏幕上随机出现一个"食物",称为豆子 2.上下左右控制"蛇 ...

  2. 实验二 贪吃蛇的游戏开发

    实验目的: 实现贪吃蛇游戏基本功能,屏幕上随机出现一个"食物",称为豆子,上下左右控制"蛇"的移动,吃到"豆子"以后"蛇" ...

  3. 计算机软件实习项目二 —— 贪吃蛇游戏 (代码实现) 12-16

    代码实现   不得不说python真是太香了,我感觉写起来比C++快,而且代码量更少,还有非常多十分方便的方法可以使用.在pycharm里有非常多的快捷键十分的方便,相较项目使用的visual stu ...

  4. 软件实习项目2——贪吃喵(猫吃鱼版贪吃蛇)(代码实现)

    软件实习项目2--贪吃喵(猫吃鱼版贪吃蛇)(代码实现) 类变量的定义以及类的初始化__init__ 一.游戏的逻辑 1.猫头的生成 2.鱼的生成 3.猫头和鱼骨的移动 4.按下键盘,改变方向 二.主窗 ...

  5. 软件实习项目2——贪吃喵(猫吃鱼版贪吃蛇)(实验准备与设计)

    软件实习项目2--贪吃喵(猫吃鱼版贪吃蛇)(实验准备与设计) 实验内容 编程语言以及开发环境的选择 实验思路(游戏设计) 一.游戏的逻辑设计 1.猫头的生成 2.鱼的生成 3.猫头和鱼骨的移动 4.按 ...

  6. 软件实习项目2——贪吃喵(猫吃鱼版贪吃蛇)(成品展示)

    软件实习项目2--贪吃喵(猫吃鱼版贪吃蛇)(成品展示) 成品展示 1.开始游戏界面 2.游戏主界面 3.结束游戏界面 视频演示 成品展示 1.开始游戏界面 速度选择: 猫咪类型选择: 2.游戏主界面 ...

  7. 实验二、贪吃蛇的游戏开发

    实验二.贪吃蛇的游戏开发 1.实验目的: 开发一个贪吃蛇游戏,吃到食物蛇身增长,蛇头撞到自身和四周墙壁死亡. 2.实验工具 通过Java运行输出. 3.实验内容 预习: 实验要求:实现贪吃蛇游戏基本功 ...

  8. 实验项目二 贪吃蛇游戏开发

    一.实验要求 1.实现贪吃蛇游戏基本功能,屏幕上随机出现一个"食物",称为豆子, 2.上下左右控制"蛇"的移动,吃到"豆子"以后" ...

  9. 【C++】经典项目控制台贪吃蛇小游戏详细教程

    [小游戏]贪吃蛇GreedySnake 本文将讲解如何使用c++面向对象方法编写控制台版贪吃蛇小游戏 项目github地址:游戏源码链接 游戏下载:GreedySnake 本人属初学者,水平所限,难免 ...

  10. GUI编程---贪吃蛇小游戏开发

    学习链接:狂神说Java–1小时开发贪吃蛇小游戏 ①初识理论 帧:时间片足够小=>就是动画,1秒30帧.连起来是动画,拆开就是静态的图片! 键盘监听 定时器Timer 游戏图片素材:GUI之贪吃 ...

最新文章

  1. mysql 返回的查询结果为空 (即零行)._Mysql数据同步(单向)
  2. FPGA的设计艺术(18)如何使用Verilog中的数组对存储器进行建模?
  3. 史上最纯洁的女孩,看到我实在被雷到了。
  4. oracle定时任务的编写及查看删除
  5. Android 微信登录
  6. 机器人开发--OS系统介绍
  7. sqrt函数java_Java BigDecimal sqrt()用法及代码示例
  8. Linux下通过虚拟网卡实现局域网 转发tcp/udp流量
  9. android 调出键盘表情_Android 显示输入法中的emoji表情以及String字符
  10. pc端ui图片尺寸_PC端UI设计尺寸规范?
  11. 台式计算机idc数据排名,2019年电脑销量排行_IDC:2019年中国PC市场预测销量持续走低...
  12. 解读高端PCB板的设计工艺!
  13. Arduino 实现物理非自锁按键触发变为软件上自锁状态保持控制方法
  14. libtool-2.4.6-9-x86_64.pkg.tar.xz无法下载
  15. 你逛过凌晨4点的校园吗? -- 前端人的漫漫长路
  16. 武林外传电影版java,武林外传经典台词
  17. 代码阅读总结之Fitch and Mather 7.0(资源文件Resource随笔)
  18. dede判断手机访问电脑端网站跳转代码
  19. 贪吃蛇c语言课程设计报告下载,c语言课程设计-贪吃蛇游戏
  20. 大数据应用及其解决方案

热门文章

  1. 图片工具网址导航 处理图片免费网站集合
  2. lru算法实现 redis_Redis中的lru算法实现
  3. HTML5实现简易电子书
  4. java实训简单计步器实训报告_基于android的手机计步器设计与实现毕业论文
  5. (九十八)大白话一线电商公司的订单系统是如何进行数据库设计的?
  6. python怎么输出列表中元素的索引_python怎么获取列表元素的索引
  7. 去斑收毛孔 7个经济小偏方
  8. JS常用的六种数据类型
  9. 深度学习(GoogLeNet)
  10. 中国无菌注射药物行业市场供需与战略研究报告