[Unity3D] Unity3D game development-implementation of a turn-based game prototype

Source: Internet
Author: User

Hello, everyone. Welcome to my blog. I am Qin Yuanpei and my blog address is blog.csdn.net/qinyuanpei.

Today, let's talk about the turn-based system. The blogger once admitted that he was a person who liked domestic RPG games. The games, such as legend of the fairy sword, xuanyuan sword, and Gu Jianqi tan, all brought many warm memories to the blogger. So what is the conversion system? Let's move our line of sight to the Three Kingdoms era. I saw Zhang Fei standing tall with eight snakes and spears, shouting: The three surnames of home slaves leave, fighting against me for three hundred rounds. Bu was furious. When he raised the spider, he wanted to stab him. This is the most primitive round impression in our memory. It can be seen that the round here refers to the confrontation between the military commanders of both sides, and the confrontation between people with the inertia of the horse. If both sides are not dead, they will turn to the horse, try again. This is the concept of the first round. In the age of stone guns chasing back to Europe, the two sides of the battle stood in a neat line according to their respective camps, and listened to the passwords and killed each other in order. After you finish shooting, you have to wait for me to take a shot. This is the essence of the turn-based system. In the "Assassin's Creed" and other games, we can have a glimpse of the magnificent European battlefield. Similarly, when two men are about to fight a duel, they fight one by one with a pistol until someone falls down. This is the turn-based system. This is how the great poet pusijin died. It can be seen that the turn-based system is a historical product that reflects the humanistic spirit, respects the rules, and respects the principles. In our life, basketball, poker, chess, and mahjong are all in turn. If they are not in turn, there will be no rules and order. The real chivalrous guest is not in martial arts, but at the right end. Instead, we stop calmly, quietly think about strategies, and plan the next round of attack and defense. This is the turn-based system. If the turn-based system represents the most primitive cultural form of mankind, it may be a backward form because the initial game was affected by the hardware level, the conversion system is one of the most discounted methods. From this point of view, the conversion system is not lagging behind, but it is also a bit elegant and classical. This is why domestic standalone games like to use the conversion mode, we do not envy foreign game masterpiece, we do not envy foreign game masterpiece luxury exquisite, we just want to find our original ownership. It is a blood that has been flowing for five thousand years. It is a story that tells the story of five thousand years. It is a dream that has persisted for five thousand years. Because of this, we know what love is, what is warmth, what is responsibility, and what is emotion. Now, let's talk about today's games. Let's start with today's content.



At the beginning of this article, we have explained the combat mode of the turn-based system clearly. So what if a turn-based game is implemented in the Unity3D game? We design the prototype of a turn-based game in the simplest one-to-one mode. We can divide the game status into the following three States:

1. If our role's life value is 0, the game ends and the role loses.

2. If the life of an enemy role is 0, the game ends and the role wins.

3. If neither role nor role has a life value of 0, perform the following procedure repeatedly:

When the current operation status is AI, the enemy acts according to the logic of the AI algorithm.
When the current operation status is player, the operation is performed based on player operations.

This is the prototype of the algorithms for implementing the turn-based game today. The following is an example of implementing a turn-based game based on this prototype. First, we create a simple game scenario ,:


In this game scenario, our Samuel Zai will be the main character of our game, and Gorilla will be our enemy. We create the corresponding script file Player. cs, EnemyAI. cs, and TurnGame. cs for global control respectively. The Player. cs script is responsible for implementing the Player-related logic, the EnemyAI script is responsible for the enemy's AI-related logic, and the TurnGame script is responsible for the core part of the game. Okay. Let's take a look at these three parts of the script code:

First, in the Player Script, we need to do three things: (1) display and hide the Player's operation interface, (2) set the Player attack tactics, and (3) design the Player's life value. Let's take a look at the Code:

Using UnityEngine; using System. collections; public class Player: MonoBehaviour {// defines the maximum Player life value as 100 public int HP = 100; // whether to wait for the Player to enter public bool isWaitPlayer = true; // current combination number private int index = 1; // Animation component private Animation mAnimation; void Start () {mAnimation = GetComponent <Animation> ();} // void OnDamage (int mValue) {HP-= mValue;} void OnGUI () {// if the player is waiting for input, the Operation window if (isWaitPlayer) is displayed) {GUI. window (0, new Rect (Screen. width/2 + 150, Screen. height/2-150,200,200), InitWindow, "select skill or fairy") ;}} void InitWindow (int ID) {if (GUI. button (new Rect (,), "") {mAnimation. play ("Attack"); // assign the operation permission to the enemy isWaitPlayer = false; Debug. log ("in the" + index + "round: the main character uses Yu jianshu"); index + = 1;} if (GUI. button (new Rect (,), "") {mAnimation. play ("Attack"); // assign the operation permission to the enemy isWaitPlayer = false; Debug. log ("in the" + index + "round: the protagonist used hichina"); index + = 1;} if (GUI. button (new Rect (,), "") {mAnimation. play ("Attack"); // assign the operation permission to the enemy isWaitPlayer = false; Debug. log ("in the" + index + "round: the main character uses xianfengjing"); index + = 1;} if (GUI. button (new Rect (0,110,200, 30), "true") {mAnimation. play ("Attack"); // assign the operation permission to the enemy isWaitPlayer = false; Debug. log ("in the" + index + "round: the main character uses true"); index + = 1;} if (GUI. button (new Rect (0,140,200, 30), "Wine God") {mAnimation. play ("Attack"); // assign the operation permission to the enemy isWaitPlayer = false; Debug. log ("in the" + index + "round: the main character uses the Wine God"); index + = 1 ;}}}
In this script, we set the maximum life of the role to 100, and then use a bool-type isWaitPlayer to determine whether it is waiting for the player to execute the next action, if the player is in the changed status, the operation interface is displayed, so that the player can display different skills. Here we use the system GUI system. The final effect is similar to that of the legend game,


Next, Let's explain the enemy's AI script. The enemy needs to perform a random operation after the player finishes executing the script. So we need to use the probability here. Let's take a look at the script:

Using UnityEngine; using System. collections; public class EnemyAI: MonoBehaviour {// defines the maximum enemy life value as 100 public int HP = 100; public bool isWaitPlayer = true; // the current number of private int indexes = 1; // Animation component private Animation mAnimation; void Start () {mAnimation = GetComponentInChildren <Animation> ();} void OnDamage (int mValue) {HP-= mValue ;} /// <summary> /// execute the enemy's AI algorithm /// </summary> public void StartAI () {if (! IsWaitPlayer) {if (HP> 20) {// attack method 1 if (Random. Range (80%) % 5! = 1) {Debug. log ("in the" + index + "round: the enemy used attack method 1"); mAnimation. play ("Howl"); // Add special effects and damage index + = 1 here; isWaitPlayer = true;} // 20% attack method 2 else {Debug. log ("in the" + index + "round: the enemy uses attack method 2"); mAnimation. play ("Howl"); index + = 1; isWaitPlayer = true ;}} else {switch (Random. range (1, 5) % 5) {case 0: Debug. log ("in the" + index + "round: the enemy used attack method 3"); mAnimation. play ("Howl"); index + = 1; isWaitPlayer = true; break; case 1: Debug. log ("in the" + index + "round: the enemy used the attack method 4"); mAnimation. play ("Howl"); index + = 1; isWaitPlayer = true; break; case 2: Debug. log ("in the" + index + "round: enemies use attack method 5"); mAnimation. play ("Howl"); index + = 1; isWaitPlayer = true; break ;}}}}}
Similarly, here we use an isWaitPlayer variable of the bool type to indicate whether the enemy is waiting for the player to perform the operation. If the value is false, it indicates that the player has completed the operation, at this time, the enemy should implement random attacks according to the AI algorithm. The probability part of the code is as follows:

Random.Range(1,5)%5!=1
This code indicates the probability of 80%, because the result is 1 only when the return value of Random. Range () is 5. We can use this method if we want to increase the probability of enemies in the game in the future. There are still many places where the game uses probability. For example, the escape rate, brute-force rate, and avoidance rate in the legend of xianjian Qixia are all achieved in this way. You may have noticed that I used an animation for all the skills or tricks in these two scripts, which of course aims to simplify the program and let us focus on the core implementation of the game, I hope you can understand this. The combination index of the two scripts is mainly used to facilitate program debugging. This variable is not used in specific applications. Now, after introducing the scripts for players and enemies, let's take a look at today's core script-TurnGame script:

Using UnityEngine; using System. collections; public class TurnGame: MonoBehaviour {/// <summary> /// prototype of the combat mode of the integrated game /// Note: This program uses the simplest one-to-one integrated game as an example, based on Unity3D games, you can implement a retrieval algorithm for games. // if you need to implement a retrieval algorithm for multiple players, the basic idea of designing the actionbar algorithm // is to divide the game status into three states: // 1. Our role's life value is 0, and the game ends, if a player loses // 2, the life of the enemy role is 0, the game ends, the player wins // 3, and the life of both sides is not 0, the following process is executed cyclically: /// when the current operation status is AI, the enemy performs operations based on the logic of the AI algorithm /// when the current operation status is player, perform operations based on player operations // </summary> // defines the player and the enemy public Transform mPlayer; public Transfo Rm mEnemy; // defines private Player playerScript for players and enemy scripts; private EnemyAI enemyScript; // The default operation status is private OperatorState mState = OperatorState for Player operations. player; // defines the operation status enumeration public enum OperatorState {Quit, // EnemyAI after the game ends, // AI logic Player // Player logic} void Start () {// obtain playerScript = mPlayer for players and enemies. getComponent <Player> (); enemyScript = mEnemy. getComponent <EnemyAI> () ;}// the operation interface IEnumerator WaitUI () {yield return new WaitForSeconds (1); en EmyScript. isWaitPlayer = true;} // wait for IEnumerator WaitAI () {yield return new WaitForSeconds (2.5F); enemyScript. isWaitPlayer = false;} // design a latency for AI so that it can initiate an attack on IEnumerator UpdateLater () {yield return new WaitForSeconds (2.5F) within 2.5F seconds after the end of our operation ); // The enemy stops waiting for enemyScript. isWaitPlayer = false; // The attacker executes AIenemyScript. startAI ();} void Update () {// if either of the two sides of the game has a life value of 0, the game ends if (playerScript. HP = 0) {mState = OperatorState. quit; Debug. log ("players lose" );} Else if (enemyScript. HP = 0) {mState = OperatorState. quit; Debug. log ("player win");} else {switch (mState) {case OperatorState. player: // if the Player operation ends, immediately hide the operation interface. Wait 2 seconds before the enemy's AI operation starts. if (! PlayerScript. isWaitPlayer) {// let the enemy wait for 2 seconds before launching the attack StartCoroutine ("UpdateLater"); // wait for the player after execution, and the operation interface is displayed after 5 seconds, players can continue to operate StartCoroutine ("WaitUI"); mState = OperatorState. enemyAI;} break; case OperatorState. enemyAI: // if the enemy's AI operation ends, the player starts to operate if (enemyScript. isWaitPlayer) {// playerScript operated by the player. isWaitPlayer = true; StartCoroutine ("WaitUI"); // after the operation is complete, run AIStartCoroutine ("WaitAI"); mState = OperatorState. player;} break ;}}}}
In this script, we define the State enumeration OperatorState according to the algorithm prototype designed at the beginning of the article, and then execute different logic according to different States. This piece of code is debugged many times by the blogger, so this part of the Code may be a bit messy. The previous two States are easy to determine, as long as the corresponding logic is added to the logic, such as displaying game victories and game failures. For the third state, we divide it into two states, and in these two states, we can switch the state by changing the state value. The basic idea is:

1. When it is the player's turn, if the player has completed the operation, the operation interface will be hidden. after a delay of 2 seconds, the enemy will initiate an attack. When the enemy finishes the attack, the operation interface will be displayed again in 5 seconds, prepare players for the next round of operations.

2. When it is the enemy's turn, if the enemy's AI operation has ended, it is the player's turn to operate. After the operation is completed, the operation is handed over to the enemy.

In this section, the blogger used coroutine, but the blogger felt that coroutine was not used very well here. If you have any good suggestions, please leave a message to me as a programmer who has a program, it is more important to accept others' suggestions than to build a car behind closed doors. Okay. Let's take a look at the effect of the final program running:

Of course, the blogger has not added the code for the damage part to the script. So far, the enemy and I have not actually caused any harm to the other party () method. As the file size is large today, you cannot send a GIF demonstration to everyone. Here we will show you how to download the GIF demo by yourself.


Reference: [Visual C ++] Game Development Note 16th describes a complete turn-based game demo

Learning game development recommendations simple blog: http://blog.csdn.net/poem_qianmo


Daily Rumor: Don't wait for anyone, and all the unexpected encounters are on the road.



Well, today's blog is like this. The blogger has gone to write his homework. If you like my blog, please remember my name: Qin Yuanpei. My blog address is blog.csdn.net/qinyuanpei.

Reprinted please indicate the source, Author: Qin Yuanpei, the source of this article: http://blog.csdn.net/qinyuanpei/article/details/28125171

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.