当前位置:网站首页>Snake Project (Simple)
Snake Project (Simple)
2022-07-31 15:22:00 【Jm:】
文章目录
1.游戏规则
Divided into three levels,Each level needs to be eaten15个食物,to enter the next level.
当蛇头碰到自身时,游戏失败!
Can go through the wall at will,will come out on the other side!
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);
//Serpent body collection
public List<BodyObj> bodyObjList=new ArrayList<>();
//食物对象
public FoodObj foodObj=new FoodObj().getFood();
//先
public void launch(){
//设置窗口是否可见
this.setVisible(true);
//设置窗口的大小
this.setSize(winWidth,winHight);
//The settings window is not resizable
this.setResizable(false);
//Sets the position of the window to be centered on the screen
this.setLocationRelativeTo(null);
//设置窗口的标题
this.setTitle("JmRaise greedy snakes");
//Initialization of snake body
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;
//Pass the current level
case 4:
state=6;
break;
default:
break;
}
}
}
});
while (true){
//游戏中调用repaint()
if(state==1){
repaint();
}
//失败重启
if(state==5){
state=0;
resetGame();
}
//Pass the current level
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); } //Get double-cached imagesgraphics对象 Graphics gImage=offScreenImage.getGraphics();*/
//设置背景颜色
gImage.setColor(Color.GREEN);
gImage.fillRect(0,0,winWidth,winHight);
//网格线颜色
gImage.setColor(Color.BLACK);
//Grid line
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);*/
}
//Draw a beep
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(Game item class)
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(Snakeheads)
package com.obj;
import com.GameWin;
import com.utils.GameUtils;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
//Snakeheads
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:
//Cannot move in the opposite direction
if(!"right".equals(direction)){
direction="left";
//Change the snake head direction pattern
img= GameUtils.leftImg;
}
break;
case KeyEvent.VK_D:
if(!"left".equals(direction)){
direction="right";
//Change the snake head direction pattern
img= GameUtils.rightImg;
}
break;
case KeyEvent.VK_W:
if(!"down".equals(direction)){
direction="up";
//Change the snake head direction pattern
img= GameUtils.upImg;
}
break;
case KeyEvent.VK_S:
if(!"up".equals(direction)){
direction="down";
//Change the snake head orientation map
// 案
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;
//The snake head collided with the body
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){
//Generate new food locations
this.frame.foodObj=food.getFood();
//Get the last section of the body
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(snake body)
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);
}
}
边栏推荐
- radiobutton的使用
- 【MySQL】Mysql范式及外键作用
- 力扣:714. 买卖股票的最佳时机含手续费
- Implement anti-shake and throttling functions
- R语言ggplot2可视化:使用ggpubr包的ggboxplot函数可视化分组箱图、使用ggpar函数改变图形化参数(caption、添加、修改可视化图像的题注、脚注内容)
- 女性服务社群产品设计
- R语言ggstatsplot包ggbarstats函数可视化条形图、并添加假设检验结果(包含样本数、统计量、效应大小及其置信区间、显著性、组间两两比较、贝叶斯假设)、检验结果报告符合APA标准
- 模板与泛型编程值typelist实现
- Excel快速对齐表格的中姓名(两个字姓名和三个字姓名对齐)
- Kubernetes原理剖析与实战应用手册,太全了
猜你喜欢
01 Encounter typescript, build environment
Browser's built-in color picker
格林美瑞交所IPO:募资3.8亿美元 更多中国企业将赴欧洲上市
AVH Deployment Practice (1) | Deploying the Flying Paddle Model on Arm Virtual Hardware
LeetCode二叉树系列——226.翻转二叉树
使用 PyTorch 检测眼部疾病
TRACE32——C源码关联
网银被盗?这篇文章告诉你如何安全使用网银
mongo enters error
DBeaver连接MySQL 8.x时Public Key Retrieval is not allowed 错误解决
随机推荐
为什么毕业季不要表白?
梅克尔工作室-第一次
JVM parameter analysis Xmx, Xms, Xmn, NewRatio, SurvivorRatio, PermSize, PrintGC "recommended collection"
为什么黑客领域几乎一片男生?
Doing things software development - the importance of law and understanding of reasonable conclusions
Ubuntu Topic 5: Setting a Static IP Address
WPF项目--控件入门基础用法,必知必会XAML
Vb how to connect mysql_vb how to connect to the database collection "advice"
Matlab matrix basic operations (definition, operation)
DBeaver连接MySQL 8.x时Public Key Retrieval is not allowed 错误解决
ASP.NET Core 产生连续 Guid
使用 Chainlink Keepers 实现智能合约函数的自动化执行
NC | 中国农大草业学院杨高文组揭示发现多因子干扰会降低土壤微生物多样性的积极效应...
四象限时间管理有多好用?
R语言ggplot2可视化:使用ggpubr包的ggboxplot函数可视化箱图、使用font函数自定义图例标题文本(legend.title)字体的大小、颜色、样式(粗体、斜体)
mysql黑窗口~建库建表
乡村基冲刺港交所:5个月期内亏2224万 SIG与红杉中国是股东
Public Key Retrieval is not allowed error solution when DBeaver connects to MySQL 8.x
ASP.NET Core 产生连续 Guid
TRACE32——基于SNOOPer的变量记录