2016-11-22 6 views
0

Привет, я сделал свою игру как текстовое приключение, которое тикает для случайных событий, и это произойдет, но это не тикает. Я делаю отметку в методе run, пытаясь получить 1 тик в секунду. Я думаю, что это из-за метода сна. Имейте в виду, я новичок, и это одна из моих первых игр Java спасибо :)Почему нет моей текстовой игры в java?

import java.lang.Runnable; 
import java.util.Random; 
import java.util.Scanner; 

public class Main implements Runnable { 

Thread thread; 
public boolean running = false; 

Scanner scan = new Scanner(System.in); 
Random rand = new Random(); 

public boolean playing = false; 
public String currentInput; 
public String allOptions[] = new String[] { "gather wood", "build a house" }; 
public String unlockedOptions[] = new String[allOptions.length]; 
public String commonRandomEvents[] = new String[] { "settler moves in", "settler dies", "settler born" }; 
public String rareRandomEvents[] = new String[] { "plague" }; 

public int housesBuilt = 0; 
public int wood = 10; 
public int woodGathered; 
public int houseCost = 10; 

public Main() { 
    unlockOption(0); 
    playing = true; 
    play(); 
} 

public static void main(String[] args) { 
    new Main().start(); 
} 

public void play() { 
    while (playing) { 
     printOptions(); 
     sleep(250); 
     getInput(); 
     System.out.println(); 
    } 
} 

public void getInput() { 
    boolean dontKnow = false; 
    System.out.println(); 
    printText("wyd?: "); 
    currentInput = scan.nextLine(); 
    currentInput = currentInput.toLowerCase(); 
    for (int i = 0; i < unlockedOptions.length; i++) { 
     if (currentInput.equals(unlockedOptions[i])) { 
      interpretOptionInput(i); 
      break; 
     } else if (currentInput.equals(allOptions[i])) { 
      { 
       printText("you haven't unlocked that yet..."); 
       break; 
      } 
     } else { 
      dontKnow = true; 
     } 
    } 
    if (dontKnow) { 
     System.out.println("you dont know how to " + currentInput); 
    } 
    currentInput = null; 
} 

public void printResources() { 

} 

public void interpretOptionInput(int arrayId) { 
    if (arrayId == 0) { 
     // gather wood 
     for (int i = 0; i < woodGathered; i++) 
      wood++; 
     printText("you gather " + woodGathered + " wood in the nearby forest."); 
     if (arrayId == 1) { 
      // build house 
      if (wood < houseCost) { 
       printText(
         "you don't have enough wood. there is a nearby forest. maybe we can get some wood from there?"); 
      } else { 
       wood -= houseCost; 
       housesBuilt++; 
       printText("you build a nice wood house with " + houseCost 
         + " wood. someone will move in, right? You have " + housesBuilt + " houses. You have " 
         + wood + " wood."); 
       houseCost += 10; 
      } 
     } 
    } 
} 

public void unlockOption(int optionId) { 
    if (allOptions[optionId] != unlockedOptions[optionId]) { 
     unlockedOptions[optionId] = allOptions[optionId]; 
    } else { 
     printText("option already unlocked. "); 
    } 
} 

public void generateRandomEvent() { 
    int commonRandomEventInt = rand.nextInt(2500); 
    int rareRandomEventInt = rand.nextInt(10000); 

    if (commonRandomEventInt == 1) { 
     int randomEventCommonInt = rand.nextInt(commonRandomEvents.length); 
     interpretRandomEvent("common", commonRandomEvents.length); 
    } 

    if (rareRandomEventInt == 1) { 
     int randomEventRareInt = rand.nextInt(rareRandomEvents.length); 
     interpretRandomEvent("rare", rareRandomEvents.length); 
    } 

} 

public void runCommonEvent(int arrayId) { 
    if (arrayId == 0) { 

    } 

    if (arrayId == 1) { 

    } 

    if (arrayId == 2) { 

    } 

    if (arrayId == 3) { 

    } 

} 

public void runRareEvent(int arrayId) { 
    if (arrayId == 0) { 

    } 

    if (arrayId == 1) { 

    } 

} 

public void interpretRandomEvent(String rarity, int arrayId) { 
    if (rarity.equals("common")) { 
     for (int i = 0; i < commonRandomEvents.length; i++) { 
      if (arrayId == i) { 
       runCommonEvent(i); 
      } 
     } 
    } 

    if (rarity.equals("rare")) { 
     for (int i = 0; i < rareRandomEvents.length; i++) { 
      if (arrayId == i) { 
       runRareEvent(i); 
      } 
     } 
    } 

} 

public void printOptions() { 
    printText("you can: "); 
    sleep(350); 
    for (int i = 0; i < unlockedOptions.length - 1; i++) { 
     if (allOptions[i] == unlockedOptions[i]) { 
      printText(unlockedOptions[i] + ", "); 
      sleep(350); 
     } 
    } 
    for (int i = 0; i <= unlockedOptions.length; i++) { 
     if (i == unlockedOptions.length) { 
      printText("or " + unlockedOptions[i - 1] + "."); 
     } 
    } 
} 

public void tick() { 
    System.out.println("tick"); 
} 

@Override 
public void run() { 

    int maxTps = 60; 
    double timePerTick = 1000000000/maxTps; 
    double deltaTicks = 0; 
    long now; 
    long lastTime = System.nanoTime(); 
    long timer = 0; 
    int ticks = 0; 

    while (running) { 
     now = System.nanoTime(); 
     deltaTicks += (now - lastTime)/timePerTick; 
     timer += now - lastTime; 
     lastTime = now; 

     if (deltaTicks >= 1) { 

      tick(); 
      ticks++; 
      deltaTicks--; 

     } 

     if (timer >= 1000000000) { 

      ticks = 0; 
      timer = 0; 

     } 

    } 

    stop(); 

} 

public void sleep(int milliseconds) { 
    try { 
     Thread.sleep(milliseconds); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

public synchronized void start() { 

    running = true; 
    thread = new Thread(this); 
    thread.start(); 

} 

public synchronized void stop() { 
    if (!running) 
     return; 
    running = false; 
    try { 
     thread.join(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

public void printText(String text) { 

    char[] textArray = text.toCharArray(); 

    for (int i = 0; i < textArray.length; i++) { 
     System.out.print(textArray[i]); 
     try { 
      if (textArray[i - 1] == '.') { 
       sleep(300); 
      } else if (textArray[i - 1] == ',') { 
       sleep(175); 
      } else { 
       sleep(20); 
      } 
     } catch (Exception e) { 

     } 
    } 
} 

}

+5

Пожалуйста, избавитесь от всего несоответствующего кода. Опубликуйте [mcve] - все, что вам нужно, это методы 'run()' и 'tick()'. –

ответ

1

Вы не tick ING, потому что вы никогда не начать нить.

Хотя вы вызываете:

new Main().start(); 

вы вызываете play() конструктор Main():

public Main() { 
    unlockOption(0); 
    playing = true; 
    play(); 
} 

и play() содержит цикл:

public void play() { 
    while (playing) { 
     printOptions(); 
     sleep(250); 
     getInput(); 
     System.out.println(); 
    } 
} 

и поэтому поток не будет начинаются до тех пор, пока цикл не разобьется.

Если вы хотите, чтобы эти сообщения tick отображались, пока цикл в play() все еще продолжается, вам нужно выполнить его в отдельном потоке.

+0

Итак, что я сделал, я просто добавил start(); к старту Главный конструктор. Это будет хорошо? – raze

 Смежные вопросы

  • Нет связанных вопросов^_^