[Beginner] Create a competitive game with basic Java knowledge

1.First of all

1. Motivation

I created it because I realized that "If you understand the basics of Java (or object-oriented), you can create a competitive game!" If you are thinking, "I don't know what to make, so I don't know the motivation for learning," I would like you to take a look! !!

2. Output

画像01.png

1. Game rules

A game in which dragons fight each other. First, select and generate yourself and the enemy dragon. <Selection / generation phase> Skill each other and finish when HP reaches 0.

2. Relationship with object orientation

  1. Generate the selected dragon with yourself and the enemy using the blueprint (= class) = object-oriented instantiation
  2. Refer to / update the value in the object for the result of using the technique (decrease in HP) = Use of getter and setter

2. Contents

1.First of all

1. Game rules

-In the selection / generation phase and the battle phase, the technique to be used with the dragon is determined by user selection. -Select one dragon for yourself and one for the enemy <Selection / Generation Phase> ・ Three dragons with different names, HP, and techniques are available. ・ Each dragon has 3 techniques. ・ Command the dragon to perform a battle ・ Skills are performed in the order of yourself → opponent. ・ Your dragon will randomly perform the selected technique, and your opponent's dragon will randomly perform one of the dragon's techniques. ・ When the opponent's HP is reduced by performing a technique, it is judged whether the opponent's HP is 0, and if it is 0, the attacking side wins.

2. Folder structure

├── DragonMain.java ├── bean │   ├── ButtleDragon.java │   ├── Action.java │   └── SimpleDragon.java └── util ├── buttle │   ├── ButtleContents.java │   ├── ButtleMain.java │   └── RandomEnemyChoice.java └── choice └── ChoiceDragon.java

Instantiate (generate) a dragon using the classes in the bean folder. In the selection / generation phase In the "selection" stage, select SimpleDragon.java ButtDragon.java and Action.java are used in the "generation" stage.

2. Overall processing

↓ main method

DragonMain.java


package dragon;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import dragon.bean.ButtleDragon;
import dragon.util.buttle.ButtleMain;
import dragon.util.choice.ChoiceDragon;

public class DragonMain{
	public static void main(String[] args)throws Exception {

	    System.out.println("Start the dragon battle");
	    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	   try{

        	    //Get a list of dragons
		   		ChoiceDragon.searchDrageon();

        	    //Choose which dragon to create
        	    String choiceMyDragon = null;
        	    String choiceOpponentDragon = null;
        	    System.out.print("Please select the dragon you use by id>");
        		choiceMyDragon = br.readLine();
        		System.out.print("Select the dragon you want your opponent to use by id>");
        		choiceOpponentDragon = br.readLine();


        	    //Dragon generation
        	    ButtleDragon myDragon = ChoiceDragon.makeDragon(Integer.parseInt(choiceMyDragon));
        	    ButtleDragon oppoDragon = ChoiceDragon.makeDragon(Integer.parseInt(choiceOpponentDragon));

        	    //Buttle
        	    ButtleMain.doButtle(myDragon,oppoDragon);

	   }catch(Exception e){
	       System.out.println("I got a serious error");
	   }

	}
}

ChoiceDragon.searchDrageon () ;: Get a list of dragons ChoiceDragon.makeDragon ()) ;: Create your own and enemy dragons and store them in "myDragon" and "oppoDragon" respectively. ButtleMain.doButtle () ;: Start the battle with "myDragon" and "oppoDragon" as arguments

3. Selection / generation phase

Get a list of dragons, generate the selected dragon, and link the technique to the dragon.

・ Class (Bean)

↓ Used to generate a simple dragon. Used to display a list of IDs and dragon names when selected without skill

SimpleDragon.java


package dragon.bean;

public class SimpleDragon {
	int dragonId;
	String dragonName;
	int hitPoint;


	//Simple dragon constructor
	public SimpleDragon(int dragonId,String dragonName, int hitPoint){
		this.dragonId = dragonId;
		this.dragonName = dragonName;
		this.hitPoint = hitPoint;
	}

	public int getDragonId() {
		return dragonId;
	}
	public void setDragonId(int dragonId) {
		this.dragonId = dragonId;
	}

	public String getDragonName() {
		return dragonName;
	}
	public void setDragonName(String dragonName) {
		this.dragonName = dragonName;
	}

	public int getHitPoint() {
		return hitPoint;
	}
	public void setHitPoint(int hitPoint) {
		this.hitPoint = hitPoint;
	}
}

↓ Used to create a battle dragon. Inherit the simple dragon class and have HP and skills to refer to during the battle.

ButtleDragon.java


package dragon.bean;

package dragon.bean;

import java.util.Map;

/**
 *
 *Dragon class used during battle
 *Used to increase or decrease HP
 */

public class ButtleDragon extends SimpleDragon {

    int buttleHp;

    int action1;
    int action2;
    int action3;
    Map<Integer, Action> actions;

    /**
     *Battle dragon constructor. The initial value of HP for battle is HP
     * @param dragonId
     * @param dragonName
     * @param hitPoint
     */
    public ButtleDragon(int dragonId, String dragonName, int hitPoint) {
        super(dragonId,dragonName,hitPoint);
        this.buttleHp = hitPoint;
    }

    public int getButtleHp() {
        return buttleHp;
    }
    public void setButtleHp(int buttleHp) {
        this.buttleHp = buttleHp;
    }

    public int getAction1() {
        return action1;
    }
    public void setAction1(int action1) {
        this.action1 = action1;
    }

    public int getAction2() {
        return action2;
    }
    public void setAction2(int action2) {
        this.action2 = action2;
    }

    public int getAction3() {
        return action3;
    }
    public void setAction3(int action3) {
        this.action3 = action3;
    }


    public Map<Integer, Action> getActions() {
        return actions;
    }
    public void setActions(Map<Integer, Action> actions) {
        this.actions = actions;
    }
}

↓ Used to create techniques.

Action.java


package dragon.bean;

/*
 *Technique class used during battle
 */
public class Action {
    int actionId;
    String actionName;
    int power;
    int actionPoint;
    int buttleActionPoint;

    /**
     *Technique constructor.
     *MP in battle[buttleActionPoint]Use to increase or decrease
     *
     * @param actionName
     * @param power
     * @param actionPoint
     */

    public Action(int actionId,String actionName, int power, int actionPoint) {
        this.actionId = actionId;
        this.actionName = actionName;
        this.power = power;
        this.actionPoint = actionPoint;
        this.buttleActionPoint = actionPoint;
    }

    public int getActionId() {
        return actionId;
    }
    public void setActionId(int actionId) {
        this.actionId = actionId;
    }

    public String getActionName() {
        return actionName;
    }
    public void setActionName(String actionName) {
        this.actionName = actionName;
    }

    public int getPower() {
        return power;
    }
    public void setPower(int power) {
        this.power = power;
    }

    public int getActionPoint() {
        return actionPoint;
    }
    public void setActionPoint(int actionPoint) {
        this.actionPoint = actionPoint;
    }

    public int getButtleActionPoint() {
        return buttleActionPoint;
    }

    public void setButtleActionPoint(int buttleActionPoint) {
        this.buttleActionPoint = buttleActionPoint;
    }

}

・ Choice Dragon ↓ Get a list to select a dragon and generate a selected dragon. It is also here to give the dragon a skill after it is generated.

ChoiceDragon.java


package dragon.util.choice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dragon.bean.Action;
import dragon.bean.ButtleDragon;
import dragon.bean.SimpleDragon;

public class ChoiceDragon {

    /**
     *Select a dragon
     ** It may be good to get this part from the DB
     * @throws Exception
     */
    public static void searchDrageon(){

        //Create a dragon that can be selected here
            SimpleDragon dragon1 = new SimpleDragon(1,"White dragon", 20);
            SimpleDragon dragon2 = new SimpleDragon(2,"blue Dragon", 25);
            SimpleDragon dragon3 = new SimpleDragon(3,"Red Dragon", 15);

        //List the created dragons
        List<SimpleDragon> choiceDragonList = new ArrayList<SimpleDragon>();
            choiceDragonList.add(dragon1);
            choiceDragonList.add(dragon2);
            choiceDragonList.add(dragon3);

        //Show list
        System.out.println("ID:\t dragon name");
        for(SimpleDragon list : choiceDragonList){
            System.out.println(list.getDragonId()+":\t"+list.getDragonName());
        }
    }

    /**
     *Create a dragon from the list based on the selected value
     *After that, give them a skill
     */
    public static ButtleDragon makeDragon(int DragonId){

    //Create a dragon
    ButtleDragon buttleDragon = makeButtleDragon(DragonId);

    //Get the trick list
    Map<Integer, Action> buttleActionMap = makeButtleAction() ;

    //Give the dragon a skill
    Map<Integer, Action> buttleDragonActionMap = new HashMap<>();

        //Get the id of the skill that the dragon has
        int actionId_1 = buttleDragon.getAction1();
        int actionId_2 = buttleDragon.getAction2();
        int actionId_3 = buttleDragon.getAction3();

        //Get the skill of the dragon from the skill list
        Action action1 = buttleActionMap.get(actionId_1);
        Action action2 = buttleActionMap.get(actionId_2);
        Action action3 = buttleActionMap.get(actionId_3);

        //Connect dragons and techniques
        buttleDragonActionMap.put(1, action1);
        buttleDragonActionMap.put(2, action2);
        buttleDragonActionMap.put(3, action3);
        buttleDragon.setActions(buttleDragonActionMap);

    return buttleDragon;
    }


    /**
     *Create a dragon and give each one an id in the skill list.
     ** I think it is better to use DB here.
     * @param dragonId
     * @return
     */
    private static ButtleDragon makeButtleDragon(int dragonId) {
        ButtleDragon makeDragon = null;

//Create different dragons depending on the argument

        switch(dragonId) {
        case 1:

//The arguments to the battle dragon constructor are ID, dragon name, and HP.
            ButtleDragon dragon1 = new ButtleDragon(1,"White dragon", 20);

//Set the technique on the battle dragon
            dragon1.setAction1(1);
            dragon1.setAction2(2);
            dragon1.setAction3(5);
            makeDragon = dragon1;
            break;
        case 2:
            ButtleDragon dragon2 = new ButtleDragon(2,"blue Dragon", 25);
            dragon2.setAction1(1);
            dragon2.setAction2(3);
            dragon2.setAction3(5);
            makeDragon = dragon2;
            break;
        case 3:
            ButtleDragon dragon3 = new ButtleDragon(3,"Red Dragon", 15);
            dragon3.setAction1(1);
            dragon3.setAction2(4);
            dragon3.setAction3(5);
            makeDragon = dragon3;
            break;
        }

        return makeDragon;
    }

    /**
     *Get the technique list.
     ** I think it is better to use DB here.
     * @return
     */
    private static Map<Integer, Action> makeButtleAction() {

        //Declare a list of techniques
        Action action1 = new Action(1,"attack\t", 2, 20);
        Action action2 = new Action(2,"White breath", 4, 2);
        Action action3 = new Action(3,"Blue breath", 3, 2);
        Action action4 = new Action(4,"Red breath", 5, 2);
        Action action5 = new Action(5,"Strong attack", 6, 1);

        //Fill the map with the technique list
        Map<Integer, Action> actionList = new HashMap<>();
        actionList.put(1, action1);
        actionList.put(2, action2);
        actionList.put(3, action3);
        actionList.put(4, action4);
        actionList.put(5, action5);

        return actionList;
    }
}

1. Get a list of dragons

Do it in the ChoiceDragon.searchDrageon method. SimpleDragon dragon1 = new Create dragons with SimpleDragon (). Generate a SimpleDragon type dragon using the constructor and store id, name, and HP respectively. Store the dragons generated by choiceDragonList in the list and display them all.

2. Generating a dragon for battle

ChoiceDragon.make Do it in the Dragon method. 1: Generating a dragon for battle Generated from ButtleDragon (a class that adds the id of the technique used and the HP for battle (which decreases when attacked) to SimpleDragon) 2: Generate a list of techniques Generate id, technique name, power, MP as Action, and generate "Technique list list" map that links id and Action 3: Connect the generated dragon and the technique Since the id of the technique to be used is given to the dragon, the technique that matches it is acquired from the technique list and stored.

↓ Image 画像02.png

By performing the same content with the enemy dragon, two "dragons with skills" will be generated.

4. Battle phase

↓ The main method of battle. Continue your turn and your opponent's turn until either HP runs out.

ButtleMain.java


package dragon.util.buttle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import dragon.bean.ButtleDragon;

public class ButtleMain {
/**
 *Buttle's basic flow
 * @throws IOException
 */
public static void doButtle(ButtleDragon myDragon, ButtleDragon oppoDragon) throws IOException{

    boolean enemyDownFlg = false; //Determining if the enemy has fallen
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Start the dragon battle.");
        do{
            ButtleContents.outputActionList(myDragon);

            String str = null;
            str = br.readLine();

        System.out.println("This attack!");
        ButtleContents.useAction(myDragon.getActions().get(Integer.parseInt(str)), myDragon, oppoDragon);

        if(oppoDragon.getButtleHp() == 0){
            enemyDownFlg = true;
            break;
        }

        System.out.println("Opponent's attack!");
        RandomEnemyChoice.randomChoice(oppoDragon,myDragon);

    }while(myDragon.getButtleHp() != 0);

        ButtleContents.outputResult(enemyDownFlg);
        System.out.println("The battle is over");
}

}

↓ The flow when you perform a technique. Display text, reduce enemy HP, reduce MP of your skill.

ButtleContents.java


package dragon.util.buttle;

import dragon.bean.Action;
import dragon.bean.ButtleDragon;

public class ButtleContents {
    /**
     *Basic technique flow
     * @param offenceAction:Attacker's technique
     * @param offenceDragon:Attacking dragon
     * @param defenceDragon:Defending dragon
     */
    public static void useAction(Action offenceAction,ButtleDragon offenceDragon, ButtleDragon defenceDragon){

        int nokoriMP = offenceAction.getActionPoint(); //Current MP

         //Display of attack technique
         String actionName = offenceAction.getActionName().replaceAll("\t", "");//Remove the tab delimiter included in the technique name
         System.out.println(offenceDragon.getDragonName()+"of"+actionName+"!!");

         //Attack technique
            Attack(offenceAction,offenceDragon,defenceDragon);

        //MP reduction
        nokoriMP--;
        offenceAction.setButtleActionPoint(nokoriMP);
    }

    /**
     *Flow of attack technique
     * @param offenceAction
     * @param offenceDragon
     * @param defenceDragon
     */
    public static void Attack(Action offenceAction,ButtleDragon offenceDragon, ButtleDragon defenceDragon){


        int damage = offenceAction.getPower(); //Power of technique

        int defenceDragonNokoriHp = 0; //HP amount of defending dragon updated with buttle


        //Calculation of the opponent's remaining HP
        defenceDragonNokoriHp = defenceDragon.getButtleHp() - damage;
        if(defenceDragonNokoriHp <= 0){
            defenceDragon.setButtleHp(0);
        }else{
            defenceDragon.setButtleHp(defenceDragonNokoriHp);
        }


        System.out.println(defenceDragon.getDragonName()+"Is"+damage+"Remaining physical strength due to damage"+defenceDragon.getButtleHp()+"Became!");

    }

    /**
     *Display the technique list
     * @param myDragon
     */
    public static void outputActionList(ButtleDragon myDragon){
            System.out.println("\n command\t\t Technical name\t\t\t\t remaining points");
            System.out.println("\t1:\t\t"+myDragon.getActions().get(1).getActionName()+"\t\t"+myDragon.getActions().get(1).getButtleActionPoint() );
            System.out.println("\t2:\t\t"+myDragon.getActions().get(2).getActionName()+"\t\t"+myDragon.getActions().get(2).getButtleActionPoint() );
            System.out.println("\t3:\t\t"+myDragon.getActions().get(3).getActionName()+"\t\t"+myDragon.getActions().get(3).getButtleActionPoint() );
            System.out.print("Please choose a technique>");
    }



    /**
     *Display the result of victory or defeat
     * @param enemyDownFlg
     */
    public static void outputResult(boolean enemyDownFlg){
        if(enemyDownFlg){
        System.out.println("\n won!");
        }else{
        System.out.println("\n I lost ...");
        }
    }

}

↓ Randomly decide the technique to be delivered by the enemy and perform the technique

RandomEnemyChoice.java


package dragon.util.buttle;

import dragon.bean.ButtleDragon;

/**
 *A class that specifies random movements on the enemy side
 *
 */
public class RandomEnemyChoice {

    /**
     *Randomly generate and perform tricks
     * @param oppoDragon
     * @param myDragon
     */
    public static void randomChoice(ButtleDragon oppoDragon, ButtleDragon myDragon){

    //Randomly select a technique
    int randomChoice = 0;
    randomChoice = (int)(Math.random()*3 + 1);

    //Perform a technique
    ButtleContents.useAction(oppoDragon.getActions().get(randomChoice),oppoDragon, myDragon);

    }

}

1. Process flow (ButtleMain.java)

Continue the battle until the enemy collapses (oppoDragon.getButtleHp () == 0) or you collapse (myDragon.getButtleHp () == 0). Pass the input value to the ButtleContents.useAction method for your own attack, and pass the random value to the ButtleContents.useAction method in the RandomEnemyChoice.randomChoice method for processing the enemy attack.

Proceed with processing while updating (getter) and referencing (setter) the values held by the instantiated dragon.

画像03.png

2. Processing when a technique is selected (ButtleContents.useAction)

1. Method description

This method takes three arguments, "offenceAction, offerDragon, defenseDragon". In this game, when your dragon attacks using a technique, the opponent's dragon becomes the defending dragon (even if the attacking side is an enemy, the defending side becomes your own dragon). Therefore, when you attack and when the opponent attacks, just exchange the dragon passed to the 2nd and 3rd arguments, and the process that "the attacking side has damaged the defending side" is the attacking side = yourself, the attacking side = Also holds for the enemy. Also, at the time of entering this method, the technique selected by the attacker is passed as an argument (offenceAction).

2. Process flow when selecting a technique

1: Message display 2: Attack processing (ButtleContents.Attack) Obtain the power of the technique from the technique and calculate the remaining HP of the defender. Then set the calculated value to the defender's Butttle HP. 3: MP decrease Reduce the MP of the technique used by the attacker

3. Finally

Thank you for reading this far! We would appreciate it if you could imagine that a dragon is created / moved (= instantiated / used) by reading the contents or actually creating it.

Recommended Posts

[Beginner] Create a competitive game with basic Java knowledge
[Beginner] Try to make a simple RPG game with Java ①
[Rails6] Create a new app with Rails [Beginner]
Java basic knowledge 1
[Rails 5] Create a new app with Rails [Beginner]
Create a CSR with extended information in Java
Create a simple bulletin board with Java + MySQL
[Windows] [IntelliJ] [Java] [Tomcat] Create a Tomcat9 environment with IntelliJ
Let's create a timed process with Java Timer! !!
[Java] Create a collection with only one element
[Java] Create a filter
java basic knowledge memo
Learn Java with Progate → I will explain because I made a basic game myself
[Java] Let's create a mod for Minecraft 1.14.4 [0. Basic file]
[Java] Let's create a mod for Minecraft 1.16.1 [Basic file]
[Note] Create a java environment from scratch with docker
[Azure] I tried to create a Java application for free ~ Connect with FTP ~ [Beginner]
Basic Authentication with Java 11 HttpClient
Create a java method [Memo] [java11]
[Java] Create a temporary file
Create a playground with Xcode 12
[Beginner] Java basic "array" description
I tried to create a java8 development environment with Chocolatey
Create a SlackBot with AWS lambda & API Gateway in Java
Create a simple DRUD application with Java + SpringBoot + Gradle + thymeleaf (1)
Create an immutable class with JAVA
Create a simple web server with the Java standard library com.sun.net.httpserver
Create a Vue3 environment with Docker!
Build a Java project with Gradle
I can't create a Java class with a specific name in IntelliJ
Create a high-performance enum with fields and methods like Java with JavaScript
Connecting to a database with Java (Part 1) Maybe the basic method
Create a Java project using Eclipse
[Java] How to create a folder
Create exceptions with a fluid interface
[Basic knowledge of Java] Scope of variables
Create a Maven project with a command
Make a typing game with ruby
# 1 [Beginner] Create a web application (website) with Eclipse from knowledge 0. "Let's build an environment for creating web applications"
The story of making a game launcher with automatic loading function [Java]
[Java] Create a jar file with both compressed and uncompressed with the jar command
I want to create a dark web SNS with Jakarta EE 8 with Java 11
Let's go with Watson Assistant (formerly Conversation) ⑤ Create a chatbot with Watson + Java + Slack
Create a java web application development environment with docker for mac part2
[Java] Create and apply a slide master
With ruby ● × Game and Othello (basic review)
Profiling with Java Visual VM ~ Basic usage ~
Create a jar file with the command
Create a simple web application with Dropwizard
Concurrency Method in Java with basic example
Create a GUI JSON Viewer with Ruby/GTK3
[Rails withdrawal] Create a simple withdrawal function with rails
Create a MySQL environment with Docker from 0-> 1
Let's create a Java development environment (updating)
Create a simple bar chart with MPAndroidChart
Basic knowledge of Java development Note writing
Create a TODO app in Java 7 Create Header
Create a temporary class with new Object () {}
Game development with two people using java 2
Game development with two people using java 1
[Basic knowledge of Java] About type conversion