[英]I am running a java based game on netbeans . How do I figure out the data flow in it?
[英]I am making a turn based combat thing in Java just to see if I can figure it out myself, But I have a problem
因此,當我嘗試制作 rpg 時,我正在 java 中進行回合制戰斗 class。 我將在下面提供代碼。 我有一個名為 state 的公共 static 字符串和一個名為 sc 的掃描儀,以及一個用於 state 的 switch 語句。 在 switch 語句之前,state = "0"。 switch 語句的 case "0" 打印出 "A Slime appears\n(1)Attack\n(2)Defend" 並使 state = "1"。 case "1" 中有另一個用於 sc.nextLine 的 switch 語句。 在這個 switch 語句中,案例“1”對我和史萊姆產生傷害,從我們的 hp 中減去它們,並打印出攻擊消息,並使 state = “2”。 案例“2”產生史萊姆的一半傷害並打印出史萊姆傷害的消息,是它的一半,你在攻擊中防御,並使 state = “2”。 因此,無論是進攻還是防守,它都會使 state = "2"。 然后對於第一個switch語句,case“2”再次打印出攻擊和防御選項,使state =“1”。 當我運行代碼時,它會打印第一條消息說粘液出現並攻擊或防御,但我無法在控制台中輸入任何內容並且代碼被終止。 我正在使用 Eclipse。
package dfguy;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static String state;
public static int cmhp = 40;
public static int cchp = 40;
public static int smhp = 20;
public static int schp;
public static Random dmg = new Random();
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
state = "0";
switch(state) {
case "0":
System.out.println("A Slime appears!\n(1)Attack\n(2)Defend");
schp = smhp;
state = "1";
break;
case "1":
switch(sc.nextLine()) {
case "1":
int cdmg = (dmg.nextInt(6) + 5);
int sdmg = (dmg.nextInt(5) + 4);
System.out.println("You attack the Slime for " + cdmg + "damage!\nThe Slime attacks "
+ "you for " + sdmg + "damage!");
schp = schp - cdmg;
cchp = cchp - sdmg;
state = "2";
break;
case "2":
int sbdmg = (dmg.nextInt(3) + 2);
cchp = cchp - sbdmg;
System.out.println("You defend against attack! The Slme attacks for " + sbdmg + "damage!");
state = "2";
break;
}
break;
case "2":
System.out.println("(1)Attack\n(2)Defend");
state = "1";
break;
}
}
}
switch
周圍沒有循環可以多次運行它 - 所以你 go 通過 state=0,將其翻轉到 state=1 然后你就完成了。
現在你可以擺脫while(true) { /*your switch*/ }
但最終你可能想要while(.dead) {... }
。 也可能將您的整個開關放入不同的方法中,而不是全部在main
中完成。
您正在編寫一個正確的 state 機器,但是關於 state 機器的一個關鍵是它需要反復調用。 第一次通過 state 是一回事,后來它變成了另一回事。
問題是,每個 state 都可能一遍又一遍地運行。 所以你必須在一個 state 中提出你的問題,然后等待下一個響應。 如果您將其留在 state 中,它將繼續發送垃圾郵件問題。 所以 state 0 應該問這個問題,然后 state 1 只是循環等待響應,響應將您發送到 state 2 或 3 以獲取更多文本。
或者您甚至可以在 state 機器中安裝 state 機器。 關鍵是循環代碼一直到達同一點,直到需要做其他事情為止。
整個事情必須在一個while循環內。 您可以使用 while(true) 或 while(1),甚至 for(;;),但我喜歡使用 boolean 值,這樣如果我想結束程序,我可以將其設置為 false 和程序結束。
偽代碼:
boolean running = true;
while(running){
switch(state){
// etc. etc. for the state machine.
// if you want to end the program somewhere then set running to false
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.