The second code of java learning (flying chess competition - tortoise and hare race), following the previous blog, is familiar with Arrays and Arrays

Keywords: Java React REST

The second code of java learning (flying chess competition - tortoise and hare race), following the previous blog, is familiar with Arrays and Arrays

Preface

Although this is a slag blog about the tortoise and rabbit race, please indicate the source of the reprint. Here, I will briefly introduce the idea, and then attach the source code.

Title Description

Write a race between the hare and the tortoise program, try to consider the scalability of the code. Tortoise and rabbit are running on the track with length of 100, the track is "-", the maximum speed of rabbit is 6, and the maximum speed of tortoise is 3. One group of special rungs will appear randomly in every 20 rungs on the runway, which are mine "@ @", conveyor "= =", downhill "^ ^", lucky star "* *", tree "| (that is, five different special rungs will appear in every 20 rungs). Rabbit and tortoise have different treatment to special running grid:

1. When the rabbit encounters a mine, it returns to the position of the last two mines, while the tortoise only returns to the position of the last mine;
2. When the rabbit meets the transmission door, it jumps to the next transmission door, and the tortoise jumps to the next two transmission doors;
3. The hare did not respond to the downhill, and the tortoise walked forward 10 steps;
4. The hare and the tortoise walk again when they meet the lucky star;
5. The hare had three breaks when he met the tree, but the tortoise didn't respond;



Among them, there is no linkage between the mine and the conveyor door (that is, if you blow it back, you won't blow it back because you are a bomb now), and other linkage phenomena (that is, you pick up the lucky star, and then you walk again and then encounter the lucky star, then walk again until you don't encounter a special running space).
In addition, the competition process is required to be controlled by the user's input return

thinking

1. Create a runway class (here only describes how to generate a runway, how to write it as a class is too simple, I will not introduce it):

1.1 initialize a track without special running space first:

Define an array with the element of String type, and store all "--"
Use the void fill (type [] A, type VAL) static method of the Arrays utility class to complete the array filling.

	Arrays.fill(road, "--");

1.2 reinitialize special rungs

Five different random numbers need to be generated for every 20 rungs. Here, the random order method is used.

  • Our husband is an array with length of 20. The element value of this array is the same as its index, that is, a[i] = i. Then we set a loop to scramble the numbers in the array, so the array is a random number with a data limit of 0-19 and a length of 20.
	int[] temp = new int[20];
	for(int i = 0;i < 20;i++)//Generate ordered 0-19
	{
		temp[i]=i;
	}
  • How to scramble: we can generate two random numbers to exchange data with the elements indexed by these two random numbers. However, in this program, the data we need is limited to 0-19 random numbers with a length of 5 arrays. Then, we only need to fix the first five numbers as one of the numbers participating in the exchange, that is, we only generate one random number, and another random number, we directly specify the first five numbers.
	for(int j = 0;j<5;j++)//The first five numbers need five special squares each time
	{
		int p = random.nextInt(20);
		exchange = temp[j];
		temp[j] = temp[p];
		temp[p] = exchange;
	}
  • We need to generate a group of special rungs for every 20 rungs, and five groups of random numbers for every 100 rungs. Then we need to write another layer of loop outside the loop to control the generation of five groups of random rungs. The data limit of each group is different. The first group is 0-19, the second group is 20-39, and so on. Then we can use the control conditions of outer loop to transform the data range. Namely

    When the first set of special rungs is generated, the outer loop control condition i = 0, then i * 20 + generate random number of 0-19 = limit random number of 0-19;
    When generating the second set of special running lattices, the outer loop control condition i = 1, then i * 20 + generate 0-19 random number = limit 20-39 random number

    And so on.

			for(int i = 0;i < 5;i++)//Five special rungs are generated every 20 rungs, so five rungs are generated
			{
				for(int j = 0;j<5;j++)//The first five numbers need five special squares each time
				{
					int p = random.nextInt(20);
					exchange = temp[j];
					temp[j] = temp[p];
					temp[p] = exchange;
				}
				// Modify runway
				road[temp[0] + i * 20] = "**";
				road[temp[1] + i * 20] = "==";
				road[temp[2] + i * 20] = "@@";
				road[temp[3] + i * 20] = "^^";
				road[temp[4] + i * 20] = "||";
			}
  • In addition, in order to facilitate the transfer gate and mine jump, we use two additional arrays to record our mines and transfer gate positions
		protal[i] = temp[1] + i * 20;
		landMine[i] =temp[2] + i * 20;

2. Create rules (define an interface)

Our game rules make our small animals compete. Different games have different rules. Our flying chess game makes the small animals have to make corresponding actions or reactions when they encounter special rungs. So, I wrote an interface LudoPlayer here to regulate the behavior of competitors

/**
 * LudoPlayer Interface < br >
 * 	As a flying chess player, the rules to be obeyed are different in different games < br >
 * 	Players can run on the track < br >
 * 	All players will encounter Lucky Star * *, portal = =, mine @ @, downhill ^ ^ and tree |. Players need to deal with it according to their abilities
 * @author wantingting666@gmail.com
 *
 */
public interface LudoPlayer {
	void luck();//Meet lucky star
	void portal(int[] nextPortal);//Portal
	void landMine(int[] pastLandMine);//mine
	void downhill();//Downhill slope
	void tree();//tree
}

3. Create small animals

3.1 to extend the program, create a parent class, Animal

Because the Animal class is a higher-level abstraction, we can't generate its objects (you say let me generate a rabbit, I can also know what it looks like, now you want me to generate an Animal, the ghost knows what it is), so we create an abstract class. We abstract the characteristics and behaviors of rabbits and tortoises, where small animals can run and sleep. In addition, in this game, small animals need to obey the rules. Then, let's use the Animal class to implement our interface.

Here, we will use a design mode, which is the default adapter mode, because when the rabbit encounters a downhill, it will not react. Similarly, when the tortoise encounters a tree, it will not respond. More importantly, a small animal may not respond to all special rungs, but the interface methods must be completely rewritten. What can we do? We can use its parent class to implement, but the implementation here is Empty realization (that is, there is no method body, and there is a lot of nonsense). Note that our little animals react the same when they encounter lucky stars, so we can directly realize it instead of empty realization

package runGame;

import java.util.Random;

/**
 * Animal Class < br >
 * 	Common characteristics of all animals, which cannot have objects < br >
 * @author wantingting666@gmail.com
 *
 */
public abstract class Animal implements LudoPlayer{
	protected String type;//species
	protected int maxSpeed;//Fastest speed 
	protected int position;//Current position
	protected boolean isWake;

	/**
	 * 	Construction method
	 */
	public Animal() {
		// TODO auto generated constructor stub
	}
	
	
	/**
	 * 	run Methods < br >
	 * 	Animals can move < br >
	 * 	And when animals move, they are limited to the maximum speed < br >
	 */
	public void run()
	{
		if(!this.isWake)
		{
			return;
		}
		
		Random  random = new Random();
		int step=random.nextInt(maxSpeed) + 1;
		position += step;
	}
	
	
	/**
	 * getPosition Methods < br >
	 * @return current location
	 */
	public int getPosition() {
		return position;
	}
	
	
	/**
	 * getType Methods < br >
	 * @return species
	 */
	public String getType() {
		return type;
	}
	
	
	/**
	 * getWake Method
	 * @return Do animals sleep
	 */
	public boolean getWake() {
		return isWake;
	}
	
	
	
	/**
	 * setWake Method
	 *	 Animals wake up
	 */
	public void setWake() {
		this.isWake=true;
	}
	
	@Override
	public void luck() {
		this.run();
	}
	@Override
	public void downhill() {
	}
	@Override
	public void tree() {
	}
}

3.2 write rabbit class and tortoise class (that is, inherit our Animal class, how to write the class is simple, not introduced)

Here's just how to jump when encountering mines and portals. We have saved the special runways when we created the runway, so here, we just need to query. The small animals step on the first few mines or conveyor gates. Here, we use the binary int binary search (type [] A, tyep key) of Arrays to query, because we are in ascending storage, and the binary method will be faster.

int i = Arrays.binarySearch(nextPortal,this.position);

source code

package runGame;

import java.util.Random;

/**
 * Animal Class < br >
 * 	Common characteristics of all animals, which cannot have objects < br >
 * @author wantingting666@gmail.com
 *
 */
public abstract class Animal implements LudoPlayer{
	protected String type;//species
	protected int maxSpeed;//Fastest speed 
	protected int position;//Current position
	protected boolean isWake;

	/**
	 * 	Construction method
	 */
	public Animal() {
		// TODO auto generated constructor stub
	}
	
	
	/**
	 * 	run Methods < br >
	 * 	Animals can move < br >
	 * 	And when animals move, they are limited to the maximum speed < br >
	 */
	public void run()
	{
		if(!this.isWake)
		{
			return;
		}
		
		Random  random = new Random();
		int step=random.nextInt(maxSpeed) + 1;
		position += step;
	}
	
	
	/**
	 * getPosition Methods < br >
	 * @return current location
	 */
	public int getPosition() {
		return position;
	}
	
	
	/**
	 * getType Methods < br >
	 * @return species
	 */
	public String getType() {
		return type;
	}
	
	
	/**
	 * getWake Method
	 * @return Do animals sleep
	 */
	public boolean getWake() {
		return isWake;
	}
	
	
	
	/**
	 * setWake Method
	 *	 Animals wake up
	 */
	public void setWake() {
		this.isWake=true;
	}
	
	@Override
	public void luck() {
		this.run();
	}
	@Override
	public void downhill() {
	}
	@Override
	public void tree() {
	}
}

package runGame;

import java.util.Arrays;


/**
 * Rabbit Class < br >
 * 	Rabbit of species < br >
 * @author wantingting666@gmail.com
 *
 */
public class Rabbit extends Animal {

	public Rabbit() {
		maxSpeed = 6;
		type = "Rabbit";
		position = 0;
		this.isWake = true;
	}
	@Override
	public void luck() {
		this.run();
	}

	@Override
	public void portal(int[] nextPortal) {
		int i = Arrays.binarySearch(nextPortal,this.position);
		this.position = (i <= nextPortal.length-2 ? nextPortal[i+1] : 100);
	}

	@Override
	public void landMine(int[] pastLandMine) {
		int i = Arrays.binarySearch(pastLandMine,this.position);
		this.position=(i >= 2?pastLandMine[i-2] : 0);
		
	}

	@Override
	public void tree() {
		this.isWake = false;
	}
	
	
	
	
}

package runGame;

import java.util.Arrays;

/**
 * Tortoise Class < br >
 * Tortoise of species < br >
 * @author wantingting666@gmail.com
 *
 */
public class Tortoise extends Animal {

	public Tortoise() {
		maxSpeed = 3;
		type = "Tortoise";
		position = 0;
		isWake = true;
	}

	@Override
	public void portal(int[] nextPortal) {
		int i = Arrays.binarySearch(nextPortal,this.position);
		this.position = ( i <= nextPortal.length-3 ? nextPortal[i+2] : 100);
	}
	
	
	@Override
	public void landMine(int[] pastLandMine) {
		int i = Arrays.binarySearch(pastLandMine,this.position);
		this.position = ( i >= 1 ? pastLandMine[i-1] : 0);
	}

	@Override
	public void downhill() {
		this.position += 10;
		
	}

}

package runGame;

/**
 * LudoPlayer Interface < br >
 * 	As a flying chess player, the rules to be obeyed are different in different games < br >
 * 	Players can run on the track < br >
 * 	All players will encounter Lucky Star * *, portal = =, mine @ @, downhill ^ ^ and tree |. Players need to deal with it according to their abilities
 * @author wantingting666@gmail.com
 *
 */
public interface LudoPlayer {
	void luck();//Meet lucky star
	void portal(int[] nextPortal);//Portal
	void landMine(int[] pastLandMine);//mine
	void downhill();//Downhill slope
	void tree();//tree
}

package runGame;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

/**
 * 	Ludo Class < br >
 * 	The whole process of the game, the integration of players, rules and game equipment < br >
 * @author wantingting666@gmail.com
 *
 */
public class Ludo {
	 /**
	  * 	Games need runways, players
	  */
	 private Track track = new Track();
	 private Tortoise tortoise = new Tortoise();
	 private Rabbit rabbit = new  Rabbit();
	 private static int flag = 0;//Record whether the rabbit should sleep
	 
	 
	/**
	 *	Track Class < br >
	 * 	There are many obstacles and rewards on the runway < br >
	 * 	But the track can't control the player's movement < br >
	 * 	The player's movement is determined by the game < br >
	 * 	The specific action of the player is decided by the player < br >
	 * 	For example, the runway is only for the use of players. When encountering mines, the game decides that players need to be punished, but the punishment is determined by the physical quality of players (here is the species) < br >
	 */
	 private class Track {
		
		public String[] road = new String[100];
		//Record special grids, transports and mines
		public int[] protal = new int[5];
		public int[] landMine = new int[5];
		
		
		/**
		 * 	Construction method < br >
		 * 	Initialize runway < br >
		 */
		public Track() {
			Arrays.fill(road, "--");
			Random random = new Random();
			int exchange;
			int[] temp = new int[20];
			for(int i = 0;i < 20;i++)//Generate ordered 0-19
			{
				temp[i]=i;
			}
			for(int i = 0;i < 5;i++)//Five special rungs are generated every 20 rungs, so five rungs are generated
			{
				for(int j = 0;j<5;j++)//The first five numbers need five special squares each time
				{
					int p = random.nextInt(20);
					exchange = temp[j];
					temp[j] = temp[p];
					temp[p] = exchange;
				}
				// Record special runways and modify runways
				road[temp[0] + i * 20] = "**";
				road[temp[1] + i * 20] = "==";
				road[temp[2] + i * 20] = "@@";
				road[temp[3] + i * 20] = "^^";
				road[temp[4] + i * 20] = "||";
				protal[i] = temp[1] + i * 20;
				landMine[i] =temp[2] + i * 20;
			}
			//Print runway
			System.out.println("Initial state:");
			for(String i : road)
			{
				System.out.print(i);
			}

		}
	}

	 /**
	  * 	judge Methods < br >
	  * 	Judge player's trend < br >
	  * 	For internal use only < br >
	  * 	@param Game player
	  */
	  private void judge(Animal animal) {
		 if(animal.getPosition() >= 100)
		 {
			 System.out.println(animal.getType() + "To the end");
			 return;
		 }
		switch (track.road[animal.getPosition()]) {
		case "**":
			animal.luck();
			System.out.println(animal.type + "Find lucky star");
			judge(animal);
			break;
		case "==":
			System.out.println(animal.type + "Gate encountered");
			animal.portal(this.track.protal);
			break;
		case "@@":
			System.out.println(animal.type + "Step on a mine");
			animal.landMine(this.track.landMine);
			break;
		case "^^":
			System.out.println(animal.type + "Encounter downhill");
			if(animal.type.equals("Tortoise"))
			{
				animal.downhill();
				judge(animal);
			}
			break;
		case "||":
			if(animal.getType().equals("Tortoise"))
			{
				System.out.println(animal.type + "Tree encountered");
			}
			else if(flag == 0)
			{
				animal.tree();
				flag = 3;
			}
			if(animal.getType().equals("Rabbit") && flag != 0)
			{
				System.out.println("Rabbit rest");
				flag--;
				if(flag == 0)
				{
					animal.setWake();
				}
			}
			break;
		default:
			System.out.println(animal.type + "Normal running");
			break;
		} 
	}
	  
	  
	  /**
	   * run Methods < br >
	   * 	The process of the game < br >
	   */
	public void run()
	 {
		 Scanner scanner = new Scanner(System.in);
		 for(int i = 1;;i++)
		 {
			 scanner.nextLine();
			 if(this.tortoise.getPosition() >= 100 || this.rabbit.getPosition() >= 100)
			 {
				 System.out.println((this.tortoise.getPosition() > this.rabbit.getPosition() ? "Tortoise" : "Rabbit") + "To the end");
				 System.out.println("game over");
				 break;
			 }
			 else
			 {
				 System.out.println("round" + i + ": ");
				this.tortoise.run();
				this.rabbit.run();
				judge(this.tortoise);
				judge(this.rabbit);
				print();
			 }
		 }
		 scanner.close();
	 }
	 
	
	
	/**
	 * print Methods < br >
	 *	 Print the current schedule < br >
	 */
	public void print()
	{
		for(int i = 0;i < this.track.road.length;i++)
		{
			if(i == rabbit.getPosition())
			{
				System.out.print("tu");
			}
			else if(i == tortoise.getPosition())
			{
				System.out.print("wu");
			}
			else 
			{
				System.out.print(this.track.road[i]);
			}
			
		}
	}
	 
	
	 public static void main(String[] args) {
		 Ludo ludo = new Ludo();
		 ludo.run();
		
	}
}

Posted by NZ_Kiwis on Tue, 05 May 2020 22:04:02 -0700