贪吃蛇游戏

package com.snake.controller;import javax.swing.JFrame;
import javax.swing.JOptionPane;import com.snake.view.SnakeJPanel;public class SnakeStart {public static void main(String[] args) {int speed = 0;String showInputDialog = null;//初始化时间//得到速度while(true) {showInputDialog = JOptionPane.showInputDialog("蛇移动速度(1 - 5)","3");if(showInputDialog == null) {showInputDialog = "3";//默认速度break;}if(showInputDialog.length() > 1) {continue;}char[] a = showInputDialog.toCharArray();if(a[0] >= '1' && a[0] <= '5') {break;}}speed = Integer.parseInt(showInputDialog) * 50;SnakeJPanel snakeJPanel = new SnakeJPanel(speed);//创建一个JFrame窗口,将游戏面板添加进行窗口中JFrame jFrame = new JFrame();//设置窗口的某些属性jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);jFrame.setSize(920, 750);jFrame.add(snakeJPanel);jFrame.setLocationRelativeTo(null);jFrame.setVisible(true);}}
package com.snake.view;import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;public class SnakeJPanel extends JPanel implements ActionListener{private boolean start;//当前游戏状态private int speed;//速度private boolean exist;//当前是否存在食物private int foodType;//食物种类private int x;//豆子的横坐标private int y;//豆子的纵坐标private ArrayList<int[]> localList;//蛇public String direction;//方向private String direction2;//引导方向public boolean flag;Random rand = new Random();private ImageIcon up;private ImageIcon down;private ImageIcon right;private ImageIcon left;private ImageIcon body;private ImageIcon food;private ImageIcon title;Timer time;private int score;//当前得分情况private int num;//吃到的食物个数//    private Image offScreenImage;  //图形缓存//图片绘制@Overridepublic void paint(Graphics g) {direction = direction2;g.setColor(Color.WHITE);g.fillRect(0, 0, 900, 700);//绘制游戏框//标题框
//		g.drawRect(25, 30, 800, 75);title.paintIcon(this, g, 25, 10);//内容框g.setColor(Color.black);g.fillRect(25, 75, 850, 600);//绘制食物的坐标位置if(!exist) {//如果当前不存在豆子,随机绘制一个豆子	if(num % 5 == 0) {foodType = 1;}else {foodType = 0;}boolean isProduce = true;while(isProduce) {isProduce = false;x = rand.nextInt(33) * 25 + 25;		y = rand.nextInt(23) * 25 + 75;			for (int[] arr:localList) {if(x == arr[0] && y == arr[1]) {	isProduce = true;break;	}}}			System.out.println(x + "---" + y);}if(eat()) {exist = false;}else {exist = true;}if(foodType == 0) {//绘制食物g.setColor(Color.blue);
//			g.fillRect(x, y, 25, 25);g.drawImage(food.getImage(),x, y, 25, 25,null);}else {//绘制食物g.setColor(Color.WHITE);g.fillRect(x, y, 25, 25);
//			g.drawImage(food.getImage(),x, y, 25, 25,null);}//绘制头g.setColor(Color.red);
//		g.fillRect(localList.get(0)[0], localList.get(0)[1], 25, 25);	ImageIcon head = null;//判断当前方向if(direction.equals("R")) {head = right;}else if(direction.equals("L")) {head = left;}else if(direction.equals("U")) {head = up;}else if(direction.equals("D")) {head = down;}		
//		g.drawImage(head.getImage(), localList.get(0)[0], localList.get(0)[1], 25, 25,null);head.paintIcon(this, g,localList.get(0)[0], localList.get(0)[1]);//绘制身体g.setColor(Color.white);for (int i = 1; i < localList.size(); i++) {
//			g.fillRect(localList.get(i)[0], localList.get(i)[1], 25, 25);
//			g.drawImage(body.getImage(), localList.get(i)[0], localList.get(i)[1], 25, 25,null);body.paintIcon(this, g, localList.get(i)[0], localList.get(i)[1]);}
//		g.fillRect(localList.get(1)[0], localList.get(1)[1], 25, 25);
//		g.fillRect(localList.get(2)[0], localList.get(2)[1], 25, 25);//绘制分数和长度//长度g.setColor(Color.GREEN);g.setFont(new Font("宋体", Font.BOLD, 18));g.drawString("长度:" + (localList.size() - 1), 25, 30);//分数g.drawString("分数:" + score, 25, 48);if(!start) {//如果游戏未启动,结束移动和重绘g.setColor(Color.white);g.setFont(new Font("宋体", Font.BOLD, 30));g.drawString("暂停/开始(请按任意键开始,空格键暂停)", 150, 300);time.stop();}else {time.start();}//		speed();//移动后进行下一次绘制		
//      move();//移动
//		repaint();//重新绘制		}//	//解决闪烁问题
//	//如果为JFrame 为重量级  程序不会调用update()方法
//	//如果为Frame 为轻量级  重写update()方法 做双缓冲
//	//如果为JPanel 不会闪烁
//	  @Override
//	    public void update(Graphics g)
//	    {
//	    	System.out.println("update");
//	           if(offScreenImage == null)
//	              offScreenImage = this.createImage(900, 700);  //新建一个图像缓存空间,这里图像大小为800*600
//	              Graphics gImage = offScreenImage.getGraphics();  //把它的画笔拿过来,给gImage保存着
//	              paint(gImage);                                   //将要画的东西画到图像缓存空间去
//	              g.drawImage(offScreenImage, 0, 0, null);         //然后一次性显示出来
//	    }@Overridepublic void actionPerformed(ActionEvent e) {	    //移动后进行下一次绘制		move();//移动repaint();//重新绘制		}/*** 绘制速度*/
//	private void speed() {
//		try {//按一定速度进行移动
//			Thread.sleep(speed);//控制移动速度
//		} catch (InterruptedException e) {
//			// TODO 自动生成的 catch 块
//			e.printStackTrace();
//		}
//	}/*** 初始化图片*/private void drawImage() {up = new ImageIcon("images/up.png");down = new ImageIcon("images/down.png");right = new ImageIcon("images/right.png");left = new ImageIcon("images/left.png");body = new ImageIcon("images/body.png");food = new ImageIcon("images/food.png");title = new ImageIcon("images/title.jpg");}private boolean eat() {if(localList.get(0)[0] == x && localList.get(0)[1] == y) {//如果当前蛇头吃到了豆子System.out.println("eat");num++;if(foodType == 0) {score += 10;}else {score += (rand.nextInt(5) * 10 + 10);}int last = localList.size() - 1;//蛇尾			//在蛇尾后面添加一节身体localList.add(new int[] {localList.get(last)[0],localList.get(last)[1]});return true;}return false;}//移动方法public void move() {//判断是否游戏结束if(isbody()) {System.out.println("game over");start = false;//结束游戏移动JOptionPane.showMessageDialog(null,"游戏已结束!");time.stop();init();		}if(flag && localList != null) {//如果长度不为空且游戏未结束				int last = localList.size() - 1;//记录蛇尾for (int i = last; i > 0; i--) {//从蛇尾开始,每节身体移动到前一节身体的位置上localList.set(i,new int[] {localList.get(i - 1)[0],localList.get(i - 1)[1]});}//记录头位置int[] local = localList.get(0);//判断当前方向,并进行模拟移动,判断是否与边界重合if(direction.equals("R")) {if(local[0] >= 850) {local[0] = 25;}else {local[0] += 25;}}else if(direction.equals("L")) {if(local[0] <= 25) {local[0] = 850;}else {local[0] -= 25;}}else if(direction.equals("U")) {if(local[1] <= 75) {local[1] = 650;}else {local[1] -= 25;}}else if(direction.equals("D")) {if(local[1] >= 650) {local[1] = 75;}else {local[1] += 25;}}			//更改头的位置localList.set(0, local);		}	}//判断下一步是否为蛇身private boolean isbody() {// TODO 自动生成的方法存根//记录头位置int x = localList.get(0)[0];int y = localList.get(0)[1];//判断当前方向,并进行模拟移动,判断是否与边界重合if(direction.equals("R")) {x += 25;}else if(direction.equals("L")) {x -= 25;}else if(direction.equals("U")) {y -= 25;}else if(direction.equals("D")) {y += 25;}			for (int i = 1; i < localList.size(); i++) {if(localList.get(i)[0] == x && localList.get(i)[1] == y) {return true;}}return false;}//	//判断下一步是否为边界
//	private boolean isborder() {
//		// TODO 自动生成的方法存根
//		//记录头位置
//		// TODO 自动生成的方法存根
//		//记录头位置
//		int x = localList.get(0)[0];
//		int y = localList.get(0)[1];
//
//		//判断当前方向,并进行模拟移动,判断是否与边界重合
//		if(direction.equals("R")) {
//			x += 25;
//		}else if(direction.equals("L")) {
//			x -= 25;
//		}else if(direction.equals("U")) {
//			y -= 25;
//		}else if(direction.equals("D")) {
//			y += 25;
//		}	
//				
//		if(x < 25 || x > (33 * 25 + 25)) {
//			return true;//当x坐标超出边界,则返回true
//		}
//		if(y < 105 || y > (23 * 25 + 105)) {
//			return true;//当y坐标超出边界,则返回true
//		}
//		return false;//蛇头移动后未超出边界,返回false
//		
//	}/*** Create the frame.*/public SnakeJPanel(int speed) {this.speed = speed; //初始化速度//初始化游戏面板的基本信息this.setSize(900, 700);this.setLocation(0, 30);this.setFocusable(true);init();//初始化界面drawImage();//绘制图片moveByKey();//给界面添加一个键盘监听}/** 键盘监听* 通过键盘输入上下左右来控制当前蛇头移动的方向* 先判断当前蛇头方向,再来改变引导方向* 当进行绘制时再修改蛇的方向* 保证不会因为在短时间内快速变换方向导致蛇头逆向转向*/private void moveByKey() {addKeyListener(new KeyAdapter() {@Overridepublic void keyPressed(KeyEvent e) {int key = e.getKeyCode();//边界值判断switch(key) {case 65:case 37:{//向左走if(!direction.equals("R")) {direction2 = "L";}break;}				case 87:case 38:{//向上走if(!direction.equals("D")) {direction2 = "U";}				break;}				case 68:case 39:{//向右走if(!direction.equals("L")) {direction2 = "R";}break;}case 83:case 40:{//向下走if(!direction.equals("U")) {direction2 = "D";}					break;}case KeyEvent.VK_SPACE:{//如果当前键盘输入为空格start = !start;//调整游戏状态System.out.println("暂停/开始");repaint();//重绘}}//任意键开始if(!start && key != KeyEvent.VK_SPACE) {//如果当前状态为暂停状态,且键盘输入不是空格start = true;repaint();//重绘}				}});}/*** 初始化游戏基本信息*/private void init() {start = false;exist = true;direction2 = "U";flag = true;localList = new ArrayList<int[]>();localList.add(0,new int[] {75,125});//蛇头localList.add(1,new int[] {75,150});//蛇身1localList.add(2,new int[] {75,175});//蛇身2//创建第一个食物的位置//通过循环保证当前生成的食物不在身体所在的坐标上boolean isProduce = true;while(isProduce) {//循环生成食物坐标isProduce = false;//结束本次循环x = rand.nextInt(33) * 25 + 25;		y = rand.nextInt(23) * 25 + 75;			for (int[] arr:localList) {//循环遍历蛇头及蛇身的坐标if(x == arr[0] && y == arr[1]) {//如果食物坐标和蛇的某一节坐标重合isProduce = true;//跳转循环状态,继续下一次食物生成break;	}}//蛇身遍历完成,没有重合坐标,结束食物坐标生成}time = new Timer(speed, this);setLayout(null);score = 0;num = 0;foodType = 0;//		repaint();}}

 结束力

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/189177.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux中的进程终止(详解)

Linux中的进程终止 1. 进程退出场景2. 进程常见退出方法2.1 _exit函数2.2 exit函数2.3 return退出 1. 进程退出场景 代码运行完毕&#xff0c;结果正确代码运行完毕&#xff0c;结果不正确代码异常终止 2. 进程常见退出方法 正常终止&#xff08;可以通过 echo $? 查看进程…

使用键盘管理器更改键盘快捷键,让键盘真正迎合你的使用习惯

如果默认快捷键不适合你&#xff0c;你肯定会想知道如何在Windows 11中更改键盘快捷键。 也许你已经习惯了macOS键盘&#xff0c;或者像我一样在Windows和Mac之间切换工作/游戏——如果是这样的话&#xff0c;重新配置默认的Windows快捷方式&#xff0c;使其与Mac上的快捷方式…

Linux环境下C++ 接入OpenSSL

接上一篇&#xff1a;Windows环境下C 安装OpenSSL库 源码编译及使用&#xff08;VS2019&#xff09;_vs2019安装openssl_肥宝Fable的博客-CSDN博客 解决完本地windows环境&#xff0c;想赶紧在外网环境看看是否也正常。毕竟现在只是HelloWorld级别的&#xff0c;等东西多了&am…

Hessian协议详解

前言 Hessian协议是一种基于二进制的轻量级远程调用协议&#xff0c;用于在分布式系统中进行跨语言的通信。它使用简单的二进制格式来序列化和反序列化数据&#xff0c;并支持多种编程语言&#xff0c;如Java、C#、Python等。Hessian协议相对于其他协议的优势在于其简单性和高…

虚拟机配置网络ip,主打一个详细

文章目录 一、前言二、安装vim编辑器三、检查联网状态1. 使用ping命令 四、查看ip五、ens33网卡六、开机启动ens33网卡七、获取子网地址和子网掩码八、配置网关与子网掩码1. 编辑虚拟网络信息2. 配置网关3. 配置ens33网卡信息 九、动态ip配置十、静态ip配置 一、前言 本文主要…

Pycharm之配置python虚拟环境

最近给身边的人写了脚本&#xff0c;在自己电脑可以正常运行。分享给我身边的人&#xff0c;却运行不起来&#xff0c;然后把报错的截图给我看了&#xff0c;所以难道不会利用pycharm搭建虚拟的环境&#xff1f;记录一下配置的过程。 第一步&#xff1a;右键要打开的python的代…

IDEA 集成 Docker 插件一键部署 SpringBoot 应用

目录 前言IDEA 安装 Docker 插件配置 Docker 远程服务器编写 DockerFileSpringBoot 项目部署配置SpringBoot 项目部署结语 前言 随着容器化技术的崛起&#xff0c;Docker成为了现代软件开发的关键工具。在Java开发中&#xff0c;Spring Boot是一款备受青睐的框架&#xff0c;然…

element ui修改select选择框背景色和边框色

一、修改时间输入框的背景和边框字体颜色 <div class"hright"><el-date-picker :popper-append-to-body"false" class"custom-timeselect" v-model"form.timevalue" type"daterange" range-separator"至"…

安装 eslint 配置指南 及 遇到的一些问题记录

前端eslint配置指南 背景 当前前端项目风格混乱&#xff0c;每个人有自己的开发习惯&#xff0c;有自己的格式化习惯&#xff0c;不便于项目的风格统一&#xff0c;不利于代码维护有的项目eslint没有用起来&#xff0c;没有起到规范代码的作用&#xff0c;导致出现一些基础代码…

似然(likelihood)、极大似然、对数似然、最大后验等

1 似然 设总体X服从分布P(x&#xff1b;θ)&#xff08;当X是连续型随机变量时为概率密度&#xff0c;当X为离散型随机变量时为概率分布&#xff09;&#xff0c;θ为待估参数&#xff08;或者说系统参数&#xff09;&#xff0c;X1,X2,…Xn是来自于总体X的样本&#xff0c;x1…

HP惠普暗影精灵9笔记本电脑OMEN by HP Transcend 16英寸游戏本16-u0000原厂Windows11系统

惠普暗影9恢复出厂开箱状态&#xff0c;原装出厂Win11-22H2系统ISO镜像 下载链接&#xff1a;https://pan.baidu.com/s/17ftbBHEMFSEOw22tnYvPog?pwd91p1 提取码&#xff1a;91p1 适用型号&#xff1a;16-u0006TX、16-u0007TX、16-u0008TX、16-u0009TX、16-u0017TX 原厂系…

SSL证书哪个品牌最好用?

现在市面上的SSL证书品牌有很多&#xff0c;选购SSL证书时有很多人并不是很清楚&#xff0c;因此有很多伙伴对于选择哪个SSL证书品牌而感到疑惑。今天JoySSL小编就专门介绍下哪些比较好用的SSL证书品牌。 SSL证书兼容性主要包含操作系统、浏览器、服务器三个方面&#xff0c;好…