当前位置:网站首页>贪吃蛇项目(简单)
贪吃蛇项目(简单)
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);
}
}
边栏推荐
- RecyclerView高效使用第三节
- R语言ggplot2可视化:使用ggpubr包的ggboxplot函数可视化分组箱图、使用ggpar函数改变图形化参数(legend、修改可视化图像的图例在整图中的位置)
- 名创优品斥资6.95亿购买创始人叶国富所持办公楼股权
- 763.划分字母区间——之打开新世界
- leetcode303场周赛复盘
- JVM parameter analysis Xmx, Xms, Xmn, NewRatio, SurvivorRatio, PermSize, PrintGC "recommended collection"
- thread_local 变量的析构顺序
- Female service community product design
- Excel快速对齐表格的中姓名(两个字姓名和三个字姓名对齐)
- R language ggplot2 visualization: use the ggboxplot function of the ggpubr package to visualize the grouped box plot, use the ggpar function to change the graphical parameters (caption, add, modify th
猜你喜欢

网银被盗?这篇文章告诉你如何安全使用网银

如何进行需求分析评审

Internet banking stolen?This article tells you how to use online banking safely

2021 OWASP TOP 10 Vulnerability Guide

abaqus find contact pairs报错:surface name is already in use

11 pinia使用

WeChat chat record search in a red envelope

button控件的使用

自适应控制——仿真实验三 用超稳定性理论设计模型参考自适应系统

Excel快速对齐表格的中姓名(两个字姓名和三个字姓名对齐)
随机推荐
Female service community product design
删除 状态良好(恢复分区)的磁盘
435. 无重叠区间
763.划分字母区间——之打开新世界
使用 GraphiQL 可视化 GraphQL 架构
7、常见面试口语提问问题汇总
Gorm—Go语言数据库框架
R language ggplot2 visualization: use the ggboxplot function of the ggpubr package to visualize the grouped box plot, use the ggpar function to change the graphical parameters (caption, add, modify th
c语言hello world代码(代码编程入门)
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
LeetCode二叉树系列——110.平衡二叉树
Efficient use of RecyclerView Section 2
工程水文学名词解释总结
Ubantu project 4: xshell, XFTP connected the virtual machine and set xshell copy and paste the shortcut
R语言ggplot2可视化:使用ggpubr包的ggboxplot函数可视化分组箱图、使用ggpar函数改变图形化参数(legend、修改可视化图像的图例在整图中的位置)
R语言ggplot2可视化:使用ggpubr包的ggmaplot函数可视化MA图(MA-plot)、font.legend参数和font.main参数设置标题和图例字体加粗
R语言的画图代码及差异性分析[通俗易懂]
Doing things software development - the importance of law and understanding of reasonable conclusions
思路迪医药冲刺港股:5个月亏2.9亿 泰格医药与先声药业是股东
Ubuntu Topic 5: Setting a Static IP Address