(JAVA)基于文本的游戏,可能存在Thread.sleep()问题

时间:2018-05-19 23:26:47

标签: java text-based

目前我正在为我的高级编程课程做最后的项目。它背后的想法是游戏王国之心的基于文本的版本。在制作这个游戏时,我遇到了一个大问题。问题是滞后(我认为这是由使用 Thread.sleep()引起的)。我听说使用Timers比使用 Thread.sleep()要好得多,但我太无知了,无法调查它们。

游戏课程:

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.*;

public class Game extends JFrame{
    static JTextArea console = new JTextArea();
    static JTextField input = new JTextField();
    ImageIcon bgImage = new ImageIcon(getClass().getResource("menu1.png"));
    ImageIcon bgImage2 = new ImageIcon(getClass().getResource("menu2.png"));
    ImageIcon bgImage3 = new ImageIcon(getClass().getResource("menu3.png"));
    static int chapter = 0, section = 0;
    static int[] saveInformation = {chapter, section};
    static int cLoc = 0;
    static int sLoc = 1;
    static boolean c1s1 = false;
    static boolean c1s3 = false;
    static boolean isChosen = false;
    JLabel bg = new JLabel(bgImage);
    boolean isMenu = true;
public Game() throws InterruptedException {
    setTitle("Kingdom Hearts v1.24");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 263);
    setLocationRelativeTo(null);
    setResizable(false);
    setVisible(true);
    //MENU
    setLayout(new BorderLayout());
    setContentPane(bg);
    addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == 10) {
                if (bg.getIcon().equals(bgImage)) {
                    isMenu = false;
                }
                else if (bg.getIcon().equals(bgImage2)) {
                    isMenu = false;
                    readGame("save1.txt");
                }
                else if (bg.getIcon().equals(bgImage3) && isMenu == true) {
                    System.exit(0);
                }
            }
            else if (e.getKeyCode() == KeyEvent.VK_UP ) {
                if (bg.getIcon().equals(bgImage)) {
                    bgImage3.getImage().flush();
                    bg.setIcon(bgImage3);
                }
                else if (bg.getIcon().equals(bgImage2)) {
                    bgImage.getImage().flush();
                    bg.setIcon(bgImage);
                }
                else if (bg.getIcon().equals(bgImage3)) {
                    bgImage2.getImage().flush();
                    bg.setIcon(bgImage2);
                }
            }
            else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
                if (bg.getIcon().equals(bgImage)) {
                    bgImage2.getImage().flush();
                    bg.setIcon(bgImage2);
                }
                else if (bg.getIcon().equals(bgImage2)) {
                    bgImage3.getImage().flush();
                    bg.setIcon(bgImage3);
                }
                else if (bg.getIcon().equals(bgImage3)) {
                    bgImage.getImage().flush();
                    bg.setIcon(bgImage);
                }
            }
        }
    });
    while (isMenu == true) {
        Thread.sleep(1000);
    }
    //IN GAME CONTENT
    setLayout(null);
    console.setEditable(false);
    add(console);
    console.setBounds(0, 0, 385, 200);
    input.setEditable(true);
    add(input);
    input.setBounds(0, 200, 385, 25);
    input.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == 10) {
                try {
                    activateEvent(input.getText());
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                input.setText("");
            }
        }
    });
    try {
        activateEvent("intro");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
private void readGame(String filePath) {
    File inputFile;
    BufferedReader inputReader;

    try {
        inputFile = new File(filePath);
        inputReader = new BufferedReader(new FileReader(inputFile));
        for (int i = 0; i < saveInformation.length; i++) {
            saveInformation[i] = Integer.parseInt(inputReader.readLine());
        }
        chapter = saveInformation[cLoc];
        section = saveInformation[sLoc];
        inputReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public static void saveGame(String filePath) {
    File outputFile;
    BufferedWriter outputWriter;

    try {
        outputFile = new File(filePath);

        outputWriter = new BufferedWriter(new FileWriter(outputFile));

        saveInformation[cLoc] = chapter;
        saveInformation[sLoc] = section;

        for (int i = 0; i < saveInformation.length; i++) {
            outputWriter.write(Integer.toString(saveInformation[i]));
            outputWriter.newLine();
        }

        outputWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) throws InterruptedException {
    new Game();
}
public static void clearConsole() {
    console.setText("");
}
public static void addToConsole(String anotherString) {
    console.append(anotherString);
}
public static void toConsole(String anotherString) {
    clearConsole();
    addToConsole(anotherString);
}
public void activateEvent(String anotherString) throws InterruptedException {
    Events event = new Events();
    try {
        event.EventList(anotherString);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
public static void slowPrintToConsole(String message, long millisPerChar)
{
    for (int i = 0; i < message.length(); i++)
    {
        addToConsole(Character.toString(message.charAt(i)));

        try
        {
            Thread.sleep(millisPerChar);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
  }
}

活动类:

public class Events {
boolean isLoaded = false;
public Events() {

}
public void EventList(String s) throws InterruptedException {
    String event = s;
    if (event.equalsIgnoreCase("intro")) {
        try {
            Play(Game.chapter, Game.section);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    else if (event.equalsIgnoreCase("save")) {
        Game.saveGame("save1.txt");
    }
    else if (event.equalsIgnoreCase("move forward")) {
        if (Game.chapter == 1 && Game.section == 1) {
            Game.c1s1 = true;
        }
    }
    else if (event.equalsIgnoreCase("move help") && ((Game.chapter == 1 && Game.section == 1))) {
        Game.toConsole("VALID LOCATIONS: ");
        if (Game.chapter == 1 && Game.section == 1) {
            Game.addToConsole("'FORWARD'");
        }
    }
    else if (event.equalsIgnoreCase("shield") && Game.chapter == 1 && Game.section == 3) {
        Game.isChosen = true;
        Game.c1s3 = true;
        Game.clearConsole();
        Game.slowPrintToConsole("The power of the guardian.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("\nKindness to aid friends.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("\nA shield to repel all.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("\n\nIs this the power you seek?", 50);
        Game.c1s3 = false;
    }
    else if (event.equalsIgnoreCase("sword") && Game.chapter == 1 && Game.section == 3) {
        Game.isChosen = true;
        Game.clearConsole();
        Game.slowPrintToConsole("The power of the warrior.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("\nInvincible courage.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("\nA sword of terrible destruction.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("\n\nIs this the power you seek?", 50);
    }
    else if (event.equalsIgnoreCase("staff") && Game.chapter == 1 && Game.section == 3) {
        Game.isChosen = true;
        Game.clearConsole();
        Game.slowPrintToConsole("The power of the mystic.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("\nInner strength.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("\nA staff of wonder and ruin.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("\n\nIs this the power you seek?", 50);
    }
    else if (event.equalsIgnoreCase("y") || event.equalsIgnoreCase("yes")) {
        if (Game.chapter == 1 && Game.section == 3 && Game.isChosen == true) {
            Game.clearConsole();
            Game.section = 4;
            Play(1, 4);
        }
    }
    else if (event.equalsIgnoreCase("n") || event.equalsIgnoreCase("no")) {
        if (Game.chapter == 1 && Game.section == 3 && Game.isChosen == true) {
            Game.clearConsole();
            Game.toConsole("Sword, Staff, and Shield.\nChoose well.");
        }
    }
    else {
        System.out.println("Invalid command.");
    }
    if (isLoaded == false) {
        isLoaded = true;
        if (Game.section < 1 && Game.chapter < 1) {
        }
    }

}
public void Play(int chapter, int section) throws InterruptedException {
    // INTRO
    if (section == 0 && chapter == 0) {
        Thread.sleep(500);
        Game.slowPrintToConsole("Sora: ", 50);
        Thread.sleep(1000);
        Game.slowPrintToConsole("I've been having these weird thoughts lately...", 50);
        Thread.sleep(4000);
        Game.clearConsole();
        Game.toConsole("Sora: ");
        Thread.sleep(500);
        Game.slowPrintToConsole("Like, ", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("is any of this for real...", 50);
        Thread.sleep(1000);
        Game.slowPrintToConsole(" or not?", 50);
        Thread.sleep(4000);
        Game.clearConsole();
        Game.slowPrintToConsole("You feel as though you are falling.", 100);
        Thread.sleep(3000);
        Game.clearConsole();
        Game.slowPrintToConsole("As you begin to wake,", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole(" you get the feeling of being underwater. ", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("You see \nan increasingly bright light and you appear on a beach.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole(" The sun is \nshining in your eyes, but you notice your friend Riku in the water facing \nthe opposite direction.", 50);
        Thread.sleep(3000);
        Game.clearConsole();
        Game.slowPrintToConsole("Before attempting to sneak up on him, you realize just how far out he \nis in the water.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("A large wave begins to build up. ", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("Riku calmly turns to you and reaches \nout his hand.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole(" You rush to your friend but are knocked back by the wave.\n", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("Upon opening your eyes while underwater, ", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("you notice Riku is still \nstanding with his hand extended.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("You attempt to grab his hand but the current is too strong and pushes \nyou back.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("While floating back up, you notice the sun is now setting. ", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("Upon \nsurfacing, your friend Kairi can be seen waving to you.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("You wave back happily and make your way towards her. ", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("She smiles.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("Out of breath. you greet her with a smile.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("Kairi giggles but immediately aims her attention to something else.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("You turn your head to see what she is looking at, ", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("only to see what \nlooks like yourself falling from the clouds, followed by shooting stars.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("The more you watch, the more unbalanced you feel. ", 100);
        Thread.sleep(3000);
        Game.clearConsole();
        Game.slowPrintToConsole("You fall backwards into the water.", 75);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("The water is deeper than before, so you just keep sinking.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("Kairi desperately tries to grab you but you are too far down.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("You fall asleep again.", 100);
        Thread.sleep(4000);
        Game.clearConsole();
        Thread.sleep(1000);
        Game.slowPrintToConsole("You wake up, still underwater. ", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("You are so deep that you cannot see the \nsun, but you can feel the ground.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("Surrounded by darkness, you take your first step.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("The darkness of the ground transforms into doves which fly away. ", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("As \nthe darkness disappears, the floor begins to reveal a stained glass \nplatform depicting Snow White.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Thread.sleep(1000);
        Game.slowPrintToConsole("Is this a dream?", 100);
        Thread.sleep(3000);
        Game.clearConsole();
        Game.chapter = 1;
        Play(1, 0);
    }
    // CHAPTER 1 SECTION 0
    if (chapter == 1 && section == 0) {
        Thread.sleep(2000);
        Game.slowPrintToConsole("Chapter 1: Awakening.", 100);
        Thread.sleep(3000);
        Game.clearConsole();
        Thread.sleep(2000);
        Game.slowPrintToConsole("So much to do, ", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("so little time...", 50);
        Thread.sleep(1000);
        Game.clearConsole();
        Thread.sleep(500);
        Game.slowPrintToConsole("Take your time.", 50);
        Thread.sleep(1500);
        Game.clearConsole();
        Game.slowPrintToConsole("Don't be afraid.", 50);
        Thread.sleep(1000);
        Game.clearConsole();
        Thread.sleep(1000);
        Game.slowPrintToConsole("The door is still shut.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("Now, step forward.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("\nCan you do it?", 50);
        Thread.sleep(3000);
        Game.clearConsole();
        Game.section = 1;
        Play(1, 1);
    }
    // CHAPTER 1 SECTION 1
    if (chapter == 1 && section == 1) {
        Game.toConsole("Use 'MOVE' to navigate around your current surroundings.\nTo find valid locations to move, use 'MOVE HELP'.");
        while (Game.c1s1 == false) {
            Thread.sleep(1000);
        }
        Game.clearConsole();
        Game.section = 2;
        Play(1, 2);
    }
    //CHAPTER 1 SECTION 2
    if (chapter == 1 && section == 2) {
        Game.slowPrintToConsole("As you walk forward, three pedestals rise from the ground.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("Power sleeps within you.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("If you give it form...", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("It will give you strength.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.slowPrintToConsole("Above each pedestal holds an item.", 50);
        Thread.sleep(2000);
        Game.clearConsole();
        Game.section = 3;
        Play(1, 3);
    }
    //CHAPTER 1 SECTION 3
    if (Game.chapter == 1 && Game.section == 3 && Game.c1s3 == false) {
        Game.slowPrintToConsole("Sword, Staff, and Shield.", 50);
        Thread.sleep(500);
        Game.slowPrintToConsole("\nChoose well.", 50);
        Game.c1s3 = true;
    }
    //CHAPTER 1 SECTION 4
    if (Game.chapter == 1 && Game.section == 4) {
        System.out.println("Everything worked successfully.");
    }
  }
}

任何输入都会很棒,无论是我犯了一个非常愚蠢的错误还是一个小错误。谢谢!

0 个答案:

没有答案