用Java创建定时文字游戏

时间:2015-06-04 03:19:46

标签: java

我一直在尝试如何创建一个游戏(在Java中),玩家需要在4秒内解读一个单词。

如果答案是对的,则游戏继续进行。如果错误,游戏结束,玩家将获得最终得分(每个答案1pt)。

我正在努力追踪积分。每次循环回来时,点会自行重置。此外,如果输入任何答案,游戏将继续。

我的代码是一个火车残骸,我可能需要重新开始,但我希望我可以指向正确的方向。

我是新来的,所以请让我知道任何格式或问题的任何问题,甚至在哪里可以获得更好的帮助。任何帮助是极大的赞赏!非常感谢!

import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JOptionPane;

class test {

    private String ans = "";

    keepScore Score = new keepScore();
    int scoree = 0;

    TimerTask task = new TimerTask() {

        public void run() {
            if (ans.equals("")) {
                JOptionPane.showMessageDialog(null, "Time's up!", "",
                        JOptionPane.INFORMATION_MESSAGE);
                JOptionPane.showMessageDialog(null, Score.keepScore(scoree),
                        "", JOptionPane.INFORMATION_MESSAGE);
                System.exit(0);
            }
        }
    };

    public void getInput() throws Exception {
        Timer timer = new Timer();
        dictionaryClass object = new dictionaryClass();

        timer.schedule(task, 4 * 1000);

        String word = "0";

        String a = "";
        int x = 0;
        randomLetters meth = new randomLetters();
        int randomSequence = meth.randomLetters(x);

        if (randomSequence == 1) {
            word = "1";
            ans = JOptionPane.showInputDialog("f s h i");
            if (ans.equals(object.dictionaryClass(word))) {
                scoree = Score.keepScore(scoree);
                System.out.println("ok: " + scoree);

            }
        }

        if (randomSequence == 2) {
            word = "2";
            ans = JOptionPane.showInputDialog("k p n i");
            if (ans.equals(object.dictionaryClass(word))) {
                scoree = Score.keepScore(scoree + 1);

            }
        }

        timer.cancel();
        System.out.println("you have entered: " + ans);

    }

    public static void main(String[] args) {

        // int forever=1;
        int count = 0;
        int points = 0;

        for (int aa = 0; aa < 10; aa++) {
            try {
                (new test()).getInput();
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.println("");

            count = count + 1;
            System.out.println("count:" + count);
        }

        JOptionPane.showMessageDialog(null, "Score: " + count, "Score",
                JOptionPane.INFORMATION_MESSAGE);
    }
 }

1 个答案:

答案 0 :(得分:0)

您可以使用FuturesExecutorService超时而不是TimerTask

使用ExecutorService在一个Thread中运行输入对话框,主线程等待对话框返回或发生超时。

可以这样实现

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.swing.JOptionPane;

public class WordGame {

    private static final int IDX_SCRUMBLED = 0;
    private static final int IDX_UNSCRUMBLED = 1;

    private static final  List<String[]> DICT;
    static {
        // TODO: think of the correct data structure
        List<String[]> tmp = new ArrayList<>();
        // list contains the scumbled word followed by the unscumbled word.
        tmp.add( new String[]{"k p n i", "pink" });
        tmp.add(new String[]{"f s h i", "fish" });
        DICT = Collections.unmodifiableList(tmp);
    }

    public WordGame() {
        random = new Random();
        fetchInputExecutor = Executors.newSingleThreadExecutor();
    }

    private final ExecutorService fetchInputExecutor;

    private final Random random;




    private int getNextNotNegativeRandomInt(int startIndex, int endIndex) {
        int value = -1;
        if (startIndex < 0 || endIndex < 0 || startIndex > endIndex 
                || endIndex > Integer.MAX_VALUE -1) 
            throw new IllegalArgumentException("Invalid bounds " + startIndex + " " + endIndex);
        do {
            value = random.nextInt(endIndex + 1);
        } while (value < startIndex || value > endIndex);
        return value;
    }

    public String fetchInput(final String scrumbled) 
            throws InterruptedException, ExecutionException, TimeoutException {



        Future<String> future = fetchInputExecutor.submit(new Callable<String>() {

            @Override
            public String call() throws Exception {
                return JOptionPane.showInputDialog(scrumbled);
            }

        });

        // wait 4 seconds 
        return future.get(4, TimeUnit.SECONDS); 
    }

    public int playRound(int oldScore) throws InterruptedException, ExecutionException {
        try {
            int idx = getNextNotNegativeRandomInt(0, DICT.size()-1);
            String answer = fetchInput(DICT.get(idx)[IDX_SCRUMBLED]);
            if (DICT.get(idx)[IDX_UNSCRUMBLED].equals(answer)) {
                return oldScore + 1;
            } 
            return oldScore;

        } catch (TimeoutException toe) {
            JOptionPane.getRootFrame().dispose();
            JOptionPane.showMessageDialog(null, "Time's up!", "",
                     JOptionPane.INFORMATION_MESSAGE);
             return oldScore;
        }
    }

    public int play() throws InterruptedException, ExecutionException {
        int score = 0;

        for (int aa = 0; aa < 10; aa++) {
            score = playRound(score);
        }
        return score;

    }


    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int score = new WordGame().play();

        JOptionPane.showMessageDialog(null, "Score: " + score, "Score",
                JOptionPane.INFORMATION_MESSAGE);

    }

}  

也可以使用TimerTimerTask来实施 在达到超时值后,TimerTask会杀死DialogMessageBox。

playRoundfetchInput可能类似于:

public String fetchInput(final String scrumbled)  {
       // we need something that prevents the timeup dialog if the answer was 
       // entered within the timeout value.
       // because we access it from two threads let's us a AtomicBoolean
       final AtomicBoolean completed = new AtomicBoolean(false);

       // start a Timer which kills the OptionPane after a specified delay.
       timer.schedule(new TimerTask() {

          @Override
          public void run() {

            if (!completed.get())
                JOptionPane.getRootFrame().dispose();

          }

       }, 4 * 1000L);

       String tmp = JOptionPane.showInputDialog(scrumbled); 
       // prevent killing one of the next Input Dialogs
       completed.set(true);


       return tmp;
}

public int playRound(int oldScore) {
        int idx = getNextNotNegativeRandomInt(0, DICT.size()-1);
        String answer = fetchInput(DICT.get(idx)[IDX_SCRUMBLED]);

       // if the dialog was disposed because of an timeout the result will be null 
       if (answer == null) {
           JOptionPane.showMessageDialog(null, "Time's up!", "",
                   JOptionPane.INFORMATION_MESSAGE);
           return oldScore;

       }

        if (DICT.get(idx)[IDX_UNSCRUMBLED].equals(answer)) {
            return oldScore + 1;
        } 
        return oldScore;
}