-1

I want to add combat in my game, how would i make it so that a user only has a specific amount of time to enter a key - combo ex

String[] arr = {"A", "B", "C", "D", "E", "F"}; Random random = new Random();

    int fight = random.nextInt(arr.length);
    if (arr[fight].equals("A")) {
        System.out.println("You encountered an enemy!, Get ready to fight!");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException f) {
        }
        System.out.println("The enemy shoots a bullet!");
        System.out.print("Enter \"10110\" to dodge!: "); ---------
        pressp = i.next();-------- only 1 second to enter "10110"
        try {                             else you get shot by bullet.
            Thread.sleep(1000);
        } catch (InterruptedException f) {
        }
  • what should happen if timesout? Your next statement sleep is not going to be executed since you will be blocked and will be forced to enter the String – SMA Jan 18 '15 at 15:55
  • You forgot to ask a question. – JB Nizet Jan 18 '15 at 15:55
  • What have you tried so far, and where is your problem? This site is more meant for getting assistance with code that isn't working than for getting people to write code for you. See http://stackoverflow.com/help/how-to-ask – Andy Brown Jan 18 '15 at 15:56
  • 1
    This should help you http://stackoverflow.com/questions/5853989/time-limit-for-an-input – Zyga Jan 18 '15 at 15:59

1 Answers1

1

Your current code is going to get blocked on next method call on scanner and hence you wont be able to get what you exactly looking for. It will only sleep for a second once you enter some string. What you might need may be is:

//define a callable which will be executed asynchronously in a thread.
static class MyString implements Callable<String> {
    Scanner scanner;
    public MyString(Scanner scanner) {
        this.scanner = scanner;
    }

    @Override
    public String call() throws Exception {
        System.out.println("Enter now");
        return scanner.next();
    }
}

public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);
    ExecutorService executor = Executors.newFixedThreadPool(1);//just one thread
    MyString str = new MyString(userInput);
    Future<String> future = executor.submit(str);//it will ask user for input asynchronously and will return immediately future object which will hold string that user enters.
    try {
        String string = future.get(1, TimeUnit.SECONDS);//get user input within a second else you will get time out exception.
        System.out.println(string);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        e.printStackTrace();//if user failed to enter within a second..
    }
}    
SMA
  • 36,381
  • 8
  • 49
  • 73