Java final project Big fish eats small fish (improved version - more than 95 points at the end of the semester)

Project name: Big fish eats small fish

Table of contents

        1 Basic information

1.1 System name

1.2 Development and operation environment

1.3 Core classes used

2. System requirements analysis

2.1 System feasibility analysis

2.2 System requirements analysis

3. System function design

3.1 Overall system design

3.2 Detailed design of system modules

3.3 Other analysis

4. Display and implementation of the overall system and functional modules

5. Summarize the experience


1 Basic information

1.1family name 

Big fish eats small fish

1.2 Development and operation environment

JDK1.8, Eclipse, photoshop, Windows operating system

1.3Core classes used 

1. GWindow class: window drawing, inherits the JFrame class, and its main settings are:

Window related information: width, height, whether the form is visible, centering the form, adding components, etc.

Related events: mouse events, keyboard events

Related methods: The logic() method is used to realize the continuous creation of fish, the reGame() method is used to restart the game, the paint() method is used to realize the drawing of images, and the thread sleep() method is used to call the repaint() method. .

Game status: 5 types, 0—not started, 1—in game, 2—failed to clear the level, 3—successful to clear the level, 4—paused, the status is defined through the switch statement.

2. GUtils class: Tool class, the stored contents are:

Game-related information: game background images, level levels, fish pictures, etc.

Method: The drawWord() method is used to draw the size, color, position, etc. of the text in the form.

3.Bg class: The entity class of the background image, used to draw the background in different game states. In state 0 (not started), the start will appear on the background, and in state 1 (in game), points, difficulty, level, and status will appear. Points, difficulty, level, and failure will appear in 2 (passing the level failed), points, difficulty, level, and success will appear in the state 3 (passing the level successfully), and points, difficulty, level, and game pause will appear in the state 4 (pause).

4. EnamyFish category: enemy fish, the stored contents are:

Define relevant information: object coordinates, body size, moving speed, moving direction, score, etc.

Method: paintSelf() implements the method of drawing itself, and getrRec() is the method of obtaining its own rectangle, which is used for collision detection.

5. MyFish category: Our fish, the stored content is:

Define relevant information: object coordinates, body size, movement speed, level, etc.

Method: paintSelf() implements the method of drawing itself, getrRec() is the method of obtaining its own rectangle, which is used for collision detection, and logic() is the method of returning our fish, adding control of the keyboard.

6. Music class: a class that implements playing background music. The main contents are:

The play() method is called in the run() method. The play() method is used to read the byte stream and play music through the player.

2. System requirements analysis

2.1 System feasibility analysis

1. Project Overview

"Big Fish Eat Little Fish" is a casual game released in 2011. The game takes players into a mysterious underwater world. Each level in the game has gameplay tips and knowledge about marine fish. In the seemingly calm sea, there are hidden dangers similar to those in the human world. Under the competition between the weak and the strong, underwater creatures must not only find food to fill their stomachs, but more importantly, learn to protect themselves.

2. Current development status of the project

This type of game can basically be installed on today’s mobile phones. Although the versions are different, the gameplay is no different from before. It is worth mentioning that the design of the operation is becoming more and more user-friendly.

3. Conditions required for project realization

The core algorithm of "Big Fish Eats Small Fish" is to realize movement and predation. We need to realize the basic functions of "Big Fish Eat Small Fish" in terms of direction movement and volume growth after preying.

4. Project implementation summary

The design of this project is mainly completed using Java language. The Java language is a cross-platform, object-oriented programming language adapted to distributed computing environments. Applications written in Java can run on different software and hardware platforms without substantial modification, making it simpler and more efficient.

2.2 System requirements analysis

The design of this project is mainly to complete the basic operations of the game, which needs to meet the following requirements:

1. Design the classes required in the game.

2. Write the source program file, debug and analyze the game, so that the program can run successfully.

3. System function design

3.1 Overall system design

See documentation

3.2 Detailed design of system modules

Part of the content is as follows:

3.2.1 Start the cover function module

When launching the cover module, the first thing you need to know is the five game states of the game:

//Game status 0—Not started 1—In game 2—Failed to clear the level 3—Successfully cleared the level 4—Paused

static int  state=0;//游戏默认状态  

//Use the switch statement to define the game state in the paint() method

public void paint(Graphics g) {

g.drawImage(offScreenImage, 0, 0, null);

switch (state) {

case 0:

g.drawImage(GUtils.image, 0, 0, null);// 启动页面背景图

break;

case 1:break;

case 2:break;

case 3:break;

case 4:break;

default:

}

}

3.2.2 Start the click event function module of the page

The startup page is displayed at the very beginning of the game, and the game status is 0 at this time. When the left button of the mouse clicks on the startup window, use if to determine whether the mouse can be clicked. The game enters the running state, the game status is 1, and the text on the startup page disappears. In the launch() method, add a mouse event to the page.

// 鼠标事件

this.addMouseListener(new MouseAdapter() {

// 使用MouseAdapter()可直接重写某个需要的方法

@Override

public void mouseClicked(MouseEvent e) {

super.mouseClicked(e);

// 用if判断鼠标可否点击,并进入游戏运行状态

if (e.getButton() == 1 && state == 0) {

// 鼠标点击了左键时,e.getButton()==1,进入游戏中修改state=1

state = 1;

// repaint()可再次调用paint方法,将改变后的窗口绘制出来

repaint();

}

}

});

3.2.3 Add function module to the background of game start

First, create a new entity class Bg of the background image. The process is as follows:

1. Write a method to draw the background and define the required parameters.

//Method for drawing background paintSelf()

public void paintSelf(Graphics g,int fishgrade) {

//定义所需参数

g.drawImage(GUtils.image, 0, 0, null);

}

2. Get the object of the background class in the form class.

//Get the object Bg of background class Bg bg=new Bg();

3. Put the method of drawing the background itself under the statement that the game state is 1.

public void paint(Graphics g) {

g.drawImage(offScreenImage, 0, 0, null);

switch (state) {

case 0:

g.drawImage(GUtils.image, 0, 0, null);// 启动页面背景图

g.setColor(Color.pink);//将画笔颜色改为粉色

g.setFont(new Font("仿宋",Font.BOLD,60));//设置字体样式

g.drawString("开始", 700, 500);//为启动页面添加文字

break;

case 1:bg.paintSelf(g);break;

case 2:break;

case 3:break;

case 4:break;

default:

}

}

4. Add a while loop in the launch() method and call the repaint method every 40 milliseconds.

while (true) {

repaint();

try {

Thread.sleep(40);

} catch (InterruptedException e) {

e.printStackTrace();

}

3.2.4 Double buffering function module to solve splash screen problem

In the background adding function module at the beginning of the game, after adding a while loop in the launch() method, you will find that the text on the launch page flashes. Use caching to solve the flashing problem. The idea is: re-create an empty picture, draw all the components to the empty picture first, and then draw the drawn picture to the main window at once. The process is as follows:

1. Define a member variable in the main window

Image offScreenImage;

2. Lazy loading mode initialization object in paint() method

public void paint(Graphics g) {

offScreenImage = createImage(width, height);

Graphics gImage = offScreenImage.getGraphics();

// 获取图片对应的画笔对象,把组件绘制到新的图片中

g.drawImage(offScreenImage, 0, 0, null);

switch (state) {

case 0: // 已在Bg类中定义

gImage.drawImage(GUtils.image, 0, 0, null);//启动页面背景图

gImage.setColor(Color.pink);//将画笔颜色改为粉色

gImage.setFont(new Font("仿宋",Font.BOLD,60));//设置字体样式

gImage.drawString("开始", 700, 500);//为启动页面添加文字

break;

case 1:bg.paintSelf(gImage);break;

case 2:break;

case 3:break;

case 4:break;

default:

}

}

3. Draw the new picture drawn in the memory into the main window at one time.

g.drawImage(offScreenImage, 0, 0, null);

3.2.5 Random generation function module of enemy fish

1. In the tool class (GUtils), create a collection of all enemy fish objects.

//enemy fish collection

public static List<EnamyFish> EnamyList=new ArrayList<>();

2. Create enemy fish (EnamyFish), add enemy fish, write the parent class of enemy fish, and define variables. Realize that the right fish inherits the left fish, and the left fish inherits the enemy fish parent class.

Image img; //定义图片

int x; int y; //定义物体坐标

int width; int height;

int speed; //定义移动速度

int dir=1; //定义方向:敌方鱼的移动方向,从左向右—1,从右向左— -1

int type; //定义敌方鱼的类型

int count; //定义分值

public void paintSelf(Graphics g){g.drawImage(img, x, y, width, height, null);} //绘制自身的方法

//获取自身矩形的方法,用于碰撞检测

public Rectangle getrRec(){return new Rectangle(x,y,width,height);}

3. Create a method in the window class to add enemy fish in batches and add enemy small fish to the collection of enemy fish.

//敌方鱼

EnamyFish enamy;

public void logic(){

enamy=new Enamy_1_L();

GUtils.EnamyList.add(enamy);

}

4. Because the fish generates too fast, you need to control the generation of enemy fish in the created method, define a variable, record the number of redraws of the game, that is, the number of paint calls, and increment it in the while.

int time=0;

while (true) {

repaint();

time++;

try {Thread.sleep(40);//调用sleep()方法

} catch (InterruptedException e) {

e.printStackTrace();}

}

5. Add a judgment statement to the code of the enemy fish, define a random number double random, and generate a fish every 20 times the paint method is called. In the code block where the game state of the paint method is 1, loop through the generation of enemy fish.

if(time%20 ==0){

if(random>0.5){ enamy =new Enamy_1_L();//将小鱼添加到集合中}

GUtils.EnamyList.add(enamy);}

// 循环遍历敌方鱼的生成, 绘制敌方鱼

for (EnamyFish enamy : GUtils.EnamyList) {enamy.paintSelf(gImage);}

6. Use a for each loop in the created method to define the local fish movement direction.

//foreach循环定义鱼类移动方向

for(EnamyFish enamy : GUtils.EnamyList){

enamy.x += enamy.dir*enamy.speed;}

3.2.6 Keyboard control of our fish’s mobile function module

Add your own fish and implement keyboard control. The process is as follows:

1. First add our fish chart in the tool class.

//我方鱼类

public static  Image myfish_l=

new ImageIcon("images/myfish/myfish_left.gif").getImage();

public static  Image myfish_r=

new ImageIcon("images/myfish/myfish_right.gif").getImage();

2. Create our fish (MyFish) and define object variables. The process is the same as EnemyFish.

3. Add direction determination in the tool class to control the direction in which our fish moves.

4. Define the logic() method in the MyFish class, and draw the keyboard control in paintSelf()

3.2.7 Fish collision detection function module

  1. By obtaining the fish's own rectangle, it is used to detect whether different rectangles intersect to determine fish collision. Generate a method for each fish that returns an object of class Rectangle. Afterwards, you can use the intersects() method in Java to compare whether the two returned Rectangle objects intersect to determine whether there is a collision between the fish.

2. When the volume of our fish increases, the volume during collision detection should also increase.

public  Rectangle getRec(){

return new Rectangle(x,y,width+GUtils.count,height+GUtils.count);}

3.2.8 Game points implementation function module

1. Define scores in tool class

//Define the score public static int count=0;

2. After the collision detection between our fish and the enemy fish is completed, the points will be increased by 1. In the window class, the points earned by our fish eating the enemy fish will be realized.

if(myFish.getRec().intersects(enamy.getrRec())){

System.out.println("碰撞了");

enamy.x=-200;

enamy.y=-200;

//碰撞了,积分加碰撞的敌方鱼数

GUtils.count=GUtils.count+enamy.count; }

3. In the window class paint method, in the code block where the game status is 1, print the points earned.

gImage.setColor(Color.pink);//将画笔颜色改为粉色

gImage.setFont(new Font("仿宋",Font.BOLD,60));//设置字体样式

gImage.drawString("积分", 200, 120);//为启动页面添加文字

3.2.9 Level setting function module

The level is set according to the points. If the target points are reached, the level will be passed and the level will be increased.

1. Define the level grade in the tool class. And set the level difficulty in the window class logic() method, and implement it when state=3 in the paint() method.

static int grade=0;

//关卡难度

if(GUtils.count<10){.grade=0; MyFish.grade=1;}

else if(GUtils.count<=50){ GUtils.grade=1; }

else if(GUtils.count<=100){ GUtils.grade=2; MyFish.grade=2;}

else if(GUtils.count<=150){ GUtils.grade=3; MyFish.grade=3; }

else if(GUtils.count<=200){ GUtils.grade=4; MyFish.grade=3; }

else if(GUtils.count>200){ state=3; }

//在paint()方法中state=3的情况下实现

case 3:

myFish.paintSelf(gImage);

gImage.setColor(Color.pink);//将画笔颜色改为粉色

gImage.setFont(new Font("仿宋",Font.BOLD,60));//设置字体样式

gImage.drawString("积分", 200, 120);//为启动页面添加文字

gImage.drawString("胜利", 400, 500);//为启动页面添加文字

break;

3.2.10 Boss fish appearance function module

3.2.11 Pause and restart functional modules

3.2.12 Background music function module

In order to increase the functionality of the game, create a Music class that inherits the Thread class to add background music to the game.

The run method needs to be overridden. And read the music in, create a Music object in the main class.

 public void play() throws FileNotFoundException, JavaLayerException { //通过字符缓冲流读入

     FileInputStream fis=new FileInputStream(music);

        BufferedInputStream buffer = new BufferedInputStream(fis);

        player = new Player(buffer);

        player.play();

    }

//重写Thread类中的run方法

     public void run() {

      try {

play();//调用play方法,并抛出异常

} catch (FileNotFoundException  |JavaLayerException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

new Music("Relax.mp3").start();

3.3 Other analysis

I applied the professional knowledge I learned to this project, as follows:

1. Introducing a third-party jar package: If a Java program wants to implement the background music function, it needs to download a jar package, that is, introduce a third-party jar package into this program. The jar package we need can be downloaded from the website. Steps to import jar package:

Create a new folder in the java project, and copy the jar package that needs to be imported into the new folder →→ Select the jar package in the new folder, right-click and click [Build Path] → [Add to Build Path].

2. Photoshop technology

Through Photoshop, I designed the pictures of fish in the game. The main things I achieved were:

a. Set dynamic fish in gif format.

b. Use Photoshop to make the background of a gif image transparent.

The steps are: Open a gif → Click on the timeline of the window → Select the first image to make its layer visible, select the magic wand tool, click on the background of the image, click the Delete key to delete the background → Select the following images in sequence layer and delete its background→→Click the small arrow below on the timeline to set the delay time, click play to see the dynamic effect→→After completion, store the image in the format used by the web→→Select the format as gif.

4. Display and implementation of the overall system and functional modules

5. Summarize the experience

Guess you like

Origin blog.csdn.net/qq_70311894/article/details/131075633
Recommended