当前位置:网站首页>贪吃蛇项目(简单)
贪吃蛇项目(简单)
2022-07-31 15:15:00 【Jm呀】
文章目录
1.游戏规则
分为三个关卡,每个关卡需要吃掉15个食物,才可进入下一关。
当蛇头碰到自身时,游戏失败!
可随意穿墙,会从另一侧出来!
2.游戏操作
w:上
s:下
a:左
d:右
空格:暂停/继续
3.代码片段
1)GameWin(主入口)
package com;
import com.obj.BodyObj;
import com.obj.FoodObj;
import com.obj.HeadObj;
import com.utils.GameUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
public class GameWin extends JFrame {
//分数统计
public static int score=0;
//游戏状态 0.未开始 1.游戏中 2.暂停 3.失败 4.通关 5.失败后重新开始 6.下一关
public static int state=0;
/*//定义双缓存图片 Image offScreenImage=null;*/
//窗口宽高
int winWidth=800;
int winHight=600;
//蛇头对象
public HeadObj headObj=new HeadObj(GameUtils.rightImg,60,570,this);
//蛇身集合
public List<BodyObj> bodyObjList=new ArrayList<>();
//食物对象
public FoodObj foodObj=new FoodObj().getFood();
//先
public void launch(){
//设置窗口是否可见
this.setVisible(true);
//设置窗口的大小
this.setSize(winWidth,winHight);
//设置窗口不可调大小
this.setResizable(false);
//设置窗口的位置在屏幕上居中
this.setLocationRelativeTo(null);
//设置窗口的标题
this.setTitle("Jm养贪吃蛇");
//蛇身体的初始化
bodyObjList.add(new BodyObj(GameUtils.bodyImg,30,570,this));
bodyObjList.add(new BodyObj(GameUtils.bodyImg,0,570,this));
//键盘监听事件
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_SPACE){
switch (state){
//未开始
case 0:
state=1;
break;
//游戏中
case 1:
state=2;
repaint();
break;
//暂停中
case 2:
state=1;
break;
//失败了
case 3:
state=5;
break;
//通过当前关卡
case 4:
state=6;
break;
default:
break;
}
}
}
});
while (true){
//游戏中调用repaint()
if(state==1){
repaint();
}
//失败重启
if(state==5){
state=0;
resetGame();
}
//通过当前关卡
if(state==6){
if(GameUtils.level!=3)
{
state=1;
GameUtils.level++;
resetGame();
}else{
state=1;
GameUtils.level=1;
resetGame();
}
}
try {
//1s=1000ms
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//后
@Override
public void paint(Graphics gImage) {
/*//初始化双缓存图片 if(offScreenImage==null){ offScreenImage=this.createImage(winWidth,winHight); } //获取双缓存图片的graphics对象 Graphics gImage=offScreenImage.getGraphics();*/
//设置背景颜色
gImage.setColor(Color.GREEN);
gImage.fillRect(0,0,winWidth,winHight);
//网格线颜色
gImage.setColor(Color.BLACK);
//网格划线
for(int i=0;i<=20;i++)
{
//左上角为原点,向右为x轴正向,向下为y轴正向
//画横线
gImage.drawLine(0,30*i,600,30*i);
//画竖线
gImage.drawLine(30*i,0,30*i,600);
}
//绘制蛇身
for(int i=bodyObjList.size()-1;i>=0;i--){
bodyObjList.get(i).paintSelf(gImage);
}
//绘制蛇头
headObj.paintSelf(gImage);
//绘制食物
foodObj.paintSelf(gImage);
//绘制关卡
GameUtils.drawWord(gImage,"第"+GameUtils.level+"关",Color.ORANGE,40,640,260);
//绘制分数
GameUtils.drawWord(gImage,GameWin.score+"分",Color.red,40,650,320);
//绘制提示语
prompt(gImage);
/*//将双缓存图片绘制到窗口中 g.drawImage(offScreenImage,0,0,null);*/
}
//绘制提示音
void prompt(Graphics g){
//未开始
if(state==0){
g.setColor(Color.BLUE);
g.fillRect(100,200,400,100);
GameUtils.drawWord(g,"按下空格,游戏开始",Color.YELLOW,40,110,260);
}
//暂停
if(state==2){
g.setColor(Color.BLUE);
g.fillRect(100,200,400,100);
GameUtils.drawWord(g,"按下空格,游戏继续",Color.YELLOW,40,110,260);
}
//失败
if(state==3){
g.setColor(Color.BLUE);
g.fillRect(100,200,400,150);
GameUtils.drawWord(g,"很遗憾,游戏失败",Color.RED,40,110,260);
GameUtils.drawWord(g,"按下空格,重新开始",Color.RED,40,110,320);
}
//通过
if(state==4){
g.setColor(Color.BLUE);
if(GameUtils.level==3){
g.fillRect(100,200,400,150);
GameUtils.drawWord(g,"达成条件,游戏通关",Color.GREEN,40,110,260);
GameUtils.drawWord(g,"按下空格,再玩一次",Color.GREEN,40,110,320);
}else {
g.fillRect(100,200,400,100);
GameUtils.drawWord(g,"按下空格,进入下一关",Color.GREEN,40,110,260);
}
}
}
//游戏重置
public void resetGame(){
//分数重置
score=0;
//关闭当前窗口
this.dispose();
//开启新的窗口
String[] args={
};
main(args);
}
//程序主入口
public static void main(String[] args) {
//创建窗口对象
GameWin gameWin=new GameWin();
//调用方法,设置窗口
gameWin.launch();
}
}
2)GameObj(游戏物品类)
package com.obj;
import com.GameWin;
import java.awt.*;
//物品类
public class GameObj {
//图片
Image img;
//坐标
int x;
int y;
//宽高
int width = 30;
int height = 30;
//窗口类的引用
GameWin frame;
//setter 和 getter
public Image getImg() {
return img;
}
public void setImg(Image img) {
this.img = img;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public GameWin getFrame() {
return frame;
}
public void setFrame(GameWin frame) {
this.frame = frame;
}
//无参构造
public GameObj() {
}
//有参构造
public GameObj(Image img, int x, int y, GameWin frame) {
this.img = img;
this.x = x;
this.y = y;
this.frame = frame;
}
//有参构造
public GameObj(Image img, int x, int y, int width, int height, GameWin frame) {
this.img = img;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.frame = frame;
}
public void paintSelf(Graphics g){
g.drawImage(img,x,y,null);
}
}
3)GameUtils(游戏工具类)
package com.utils;
import java.awt.*;
//工具类
public class GameUtils {
//蛇头
public static Image upImg = Toolkit.getDefaultToolkit().getImage("src/img/up.png");
public static Image downImg = Toolkit.getDefaultToolkit().getImage("src/img/down.png");
public static Image leftImg = Toolkit.getDefaultToolkit().getImage("src/img/left.png");
public static Image rightImg = Toolkit.getDefaultToolkit().getImage("src/img/right.png");
//蛇身
public static Image bodyImg = Toolkit.getDefaultToolkit().getImage("src/img/body.png");
//食物
public static Image foodImg = Toolkit.getDefaultToolkit().getImage("src/img/food.png");
//关卡
public static int level=1;
//绘制文字
public static void drawWord(Graphics g,String str,Color color,int size,int x,int y){
g.setColor(color);
//设计字体显示效果 Font mf = new Font(String 字体,int 风格,int 字号);
g.setFont(new Font("宋体",Font.BOLD,size));
g.drawString(str,x,y);
}
}
4)HeadObj(蛇头类)
package com.obj;
import com.GameWin;
import com.utils.GameUtils;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
//蛇头类
public class HeadObj extends GameObj{
//方向 up down left right
private String direction = "right";
//setter 和 getter
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
//构造方法
public HeadObj() {
}
public HeadObj(Image img, int x, int y, GameWin frame) {
super(img,x,y,frame);
//键盘监听事件
this.frame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
changeDirection(e);
}
});
}
//控制移动方向 -a:左(lft) -d:右(right) -w:上(up) -s:下(down)
public void changeDirection(KeyEvent e){
switch (e.getKeyCode()){
case KeyEvent.VK_A:
//不能向相反的方向移动
if(!"right".equals(direction)){
direction="left";
//改变蛇头方向图案
img= GameUtils.leftImg;
}
break;
case KeyEvent.VK_D:
if(!"left".equals(direction)){
direction="right";
//改变蛇头方向图案
img= GameUtils.rightImg;
}
break;
case KeyEvent.VK_W:
if(!"down".equals(direction)){
direction="up";
//改变蛇头方向图案
img= GameUtils.upImg;
}
break;
case KeyEvent.VK_S:
if(!"up".equals(direction)){
direction="down";
//改变蛇头方向图
// 案
img= GameUtils.downImg;
}
break;
default:
break;
}
}
//蛇的移动
public void move(){
//蛇身移动
for(int i=this.frame.bodyObjList.size()-1;i>=1;i--){
this.frame.bodyObjList.get(i).x=this.frame.bodyObjList.get(i-1).x;
this.frame.bodyObjList.get(i).y=this.frame.bodyObjList.get(i-1).y;
//蛇头与身体碰撞
if(this.x==this.frame.bodyObjList.get(i).x&&this.y==this.frame.bodyObjList.get(i).y){
//失败
GameWin.state=3;
}
}
this.frame.bodyObjList.get(0).x=this.x;
this.frame.bodyObjList.get(0).y=this.y;
//蛇头移动
switch (direction){
case "up":
y-=height;
break;
case "down":
y+=height;
break;
case "left":
x-=width;
break;
case "right":
x+=width;
break;
default:
break;
}
}
@Override
public void paintSelf(Graphics g) {
super.paintSelf(g);
Integer newX=null;
Integer newY=null;
//蛇吃食物
FoodObj food=this.frame.foodObj;
if(food.x==this.x&&food.y==this.y){
//生成新的食物位置
this.frame.foodObj=food.getFood();
//获取最后一节身体
BodyObj lastBody=this.frame.bodyObjList.get(this.frame.bodyObjList.size()-1);
newX=lastBody.x;
newY=lastBody.y;
//增加长度
GameWin.score++;
}
//通关判断
if(GameWin.score>=15){
//通过
GameWin.state=4;
}
//移动蛇头
move();
//move结束之后,新的bodyObj对象添加到bodyObjList
if(newX!=null&&newY!=null){
this.frame.bodyObjList.add(new BodyObj(GameUtils.bodyImg,newX,newY,this.frame));
}
//越界处理
if (x < 0){
x = 570;
} else if (x > 570){
x = 0;
} else if (y < 30){
y = 570;
}else if (y > 570){
y = 30;
}
}
}
5)BodyObj(蛇身类)
package com.obj;
import com.GameWin;
import java.awt.*;
public class BodyObj extends GameObj{
public BodyObj(Image img, int x, int y,GameWin frame) {
super(img,x,y,frame);
}
@Override
public void paintSelf(Graphics g) {
super.paintSelf(g);
}
}
6)FoodObj(食物类)
package com.obj;
import com.GameWin;
import com.utils.GameUtils;
import java.awt.*;
import java.util.Random;
public class FoodObj extends GameObj{
//随机数对象
Random random=new Random();
public FoodObj() {
super();
}
public FoodObj(Image img, int x, int y, GameWin frame) {
super(img, x, y, frame);
}
public FoodObj getFood(){
return new FoodObj(GameUtils.foodImg,random.nextInt(20)*30,(1+random.nextInt(19))*30,this.frame);
}
@Override
public void paintSelf(Graphics g) {
super.paintSelf(g);
}
}
边栏推荐
- 为什么黑客领域几乎一片男生?
- 四象限时间管理有多好用?
- Getting started with UnityShader (1) - GPU and Shader
- 修改SQL语言实现Mysql 多表关联查询优化
- Why don't you make a confession during the graduation season?
- TRACE32——常用操作
- R language test whether the sample conforms to normality (test whether the sample comes from a normally distributed population): shapiro.test function tests whether the sample conforms to the normal d
- R language ggplot2 visualization: use the ggboxplot function of the ggpubr package to visualize the box plot, use the font function to customize the font size, color, style (bold, italic) of the legen
- Getting started with UnityShader (3) - Unity's Shader
- 思路迪医药冲刺港股:5个月亏2.9亿 泰格医药与先声药业是股东
猜你喜欢
使用 GraphiQL 可视化 GraphQL 架构
LeetCode二叉树系列——110.平衡二叉树
Essential Learning for Getting Started with Unity Shader - Transparency Effect
定时器的类型
《微信小程序-进阶篇》Lin-ui组件库源码分析-Icon组件
leetcode303场周赛复盘
01 邂逅typescript,环境搭建
01 Encounter typescript, build environment
LeetCode二叉树系列——222.完全二叉树的节点个数
Ubantu专题4:xshell、xftp连接接虚拟机以及设置xshell复制粘贴快捷键
随机推荐
leetcode303 Weekly Match Replay
Destruction order of thread_local variables
Codeforces Round #796 (Div. 2)(A-D)
Doing things software development - the importance of law and understanding of reasonable conclusions
四象限时间管理有多好用?
The meaning of node_exporter performance monitoring information collection in Prometheus
Unity中实现点选RenderTexture中的3D模型
乡村基冲刺港交所:5个月期内亏2224万 SIG与红杉中国是股东
R语言ggstatsplot包ggbarstats函数可视化条形图、并添加假设检验结果(包含样本数、统计量、效应大小及其置信区间、显著性、组间两两比较、贝叶斯假设)、检验结果报告符合APA标准
SIGABRT 报错时的注意事项和解决方法
数据库的范式(第一范式,第二范式,第三范式,BCNF范式)「建议收藏」
R语言的画图代码及差异性分析[通俗易懂]
RecyclerView高效使用第三节
NC | 中国农大草业学院杨高文组揭示发现多因子干扰会降低土壤微生物多样性的积极效应...
org.apache.jasperException(could not initialize class org)
01 邂逅typescript,环境搭建
Synchronized and volatile interview brief summary
How to clean up the lodash.memoize cache in the element-plus virtual table virtual-list component?
Matlab matrix basic operations (definition, operation)
Efficient use of RecyclerView Section 1