2015-10-13 44 views
2

我曾經在TI-BASIC中編程,並經常使用goto語句。我已經轉向學習java,並且無法弄清楚如何將程序的執行發送到另一行。
這是我的全碼:轉到Java的替代品?

package inputs; 

import java.util.Scanner; 

public class Inputs { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
     String greeting = "Welcome to a new choose your own adventure game!"; 
     String help = "Use commands such as up, down, left, and right to move around the world"; 
     String error = "You can't do that"; 
    room1(); 
} 
public static String getNextLine() { 
    Scanner scan = new Scanner(System.in); 
    return scan.nextLine(); 
} 
public static String getNextWord() { 
    Scanner scan = new Scanner(System.in); 
    String base = scan.nextLine(); 
    String command = base; 
      //differentiate capital and lowcase 
    if ("north".equals(base)){ 
     command = "North"; 
    } 
    if ("south".equals(base)){ 
     command = "South"; 
    } 
    if ("east".equals(base)){ 
     command = "East"; 
    } 
    if ("west".equals(base)){ 
     command = "West"; 
    } 
    return command; 
} 
public static void room1(){ 
    System.out.println("There is a faint smell of rotting flesh around you. you look hazily around the room. There is a door to the north. It may be your way out..."); 
    String command = getNextWord(); 
    while(1==1){ 
     if ("North".equals(command)){ 
      hall(); 
     } 
     else{ 
      System.out.println("You can't do that."); 
     } 
    } 
} 
public static void hall(){ 
    System.out.println("You are in a hallway. The hallway continues in a northerly direction to another room. There is a room to your left"); 
    while(1==1){ 
    String command = getNextWord(); 
     if ("North".equals(command)){ 
      room3(); 
     } 
     if ("East".equals(command)){ 
      room2(); 
     } 
     if ("South".equals(command)) { 
      room1(); 
     } 
     else { 
      System.out.println("You can't do that."); 
     } 
    } 
} 
public static void room2(){ 
    while(1==1){ 
    String command = getNextWord(); 
     if("get".equals(command)){ 
      System.out.println("You picked up the key. Maby there is a door somewhere"); 

     } 
    } 
} 
public static void room3(){} 

}

正如你所看到的,我試圖創建一個文本的冒險遊戲,有4間房間。如果可能的話,我還想在room3中找到房間2中使用的鑰匙。老實說,我沒有ideea如何得到這個固定...

*編輯 作爲迴應被標記爲可能的重複,我的問題要求針對我的特定程序的具體行動方法,而不是在所有的行動方法

+0

狀態機? –

+1

轉換房間類和instanciate他們在主類 – Aroniaina

+0

@SotiriosDelimanolis什麼是狀態機?我從未在BASIC中遇到過 –

回答

3

Java沒有goto聲明,你不需要一個。

當前,您將房間表示爲方法。當前房間作爲調用堆棧中的最頂層。每個預先訪問過的房間都在下面。這種方法足以應付短小的冒險遊戲。但是:

  • 您正在學習Java,並且Java支持面向對象編程。
  • 如果有人玩了你的遊戲很長一段時間,最終堆棧溢出會發生很大的堆棧溢出。

另一種方法是考慮遊戲中的對象是什麼。您有:

  • 客房
  • 庫存
  • 庫存物品(如鑰匙)

這些對象可以被定義爲Java類或枚舉。房間和房間之間的連接構成了graph中的節點和邊緣。

你的方法可能是行動,比如從一個房間轉移用戶到另一個,或拿起或使用庫存項目。

+0

他也可以有一個播放器對象,它可以去(房間)或皮卡(項目) – Aaron

+0

好點。玩家有一個位置和一個庫存。 –