我在为自己制作小游戏时遇到一些问题。我遇到问题的代码是用户输入超时。例如:游戏将在屏幕上显示一个字母。用户必须在特定时间之前输入该字母;如果他们不这样做,他们就会受到伤害。如果有人可以解释我可以用什么来解决这个问题,那就太好了。
package weapons;
import java.util.Random;
import java.util.Scanner;
class wepons {
public static void main(String args[]){
int weapondamage =0 , health = 0 , hits = 0, potion = 0, beast = 0, beastdmg = 0, letter = 0;
String weapon;
;
Scanner in = new Scanner (System.in);
System.out.println ("please pick a wepon that will kill the boss \n");
weapon = in.nextLine().toLowerCase();
if (weapon.equals("sword")){
System.out.println("you have picked the sword");
weapondamage = (int) ((Math.random()*100));
health = weapondamage*3;
}
System.out.println("Sword damage is " + weapondamage);
System.out.println("Boss health is " + health);
System.out.println("Enter the amount of hits it will take to kill the boss.");
hits = in.nextInt();
if(hits == health/weapondamage) {
System.out.println("you have killed the boss.The boss had droped a potion.\nYou pick up the potion and drink it!\nYour health has now gone up to 350hp");
}
else {
System.out.print("You have failed to kill the boss");
}
potion = (int)350;
beastdmg = (int) ((Math.random()*60));
System.out.println("By killing the boss you have awoken the beast!");
System.out.println("The beast nocks you onto your back");
System.out.println("The beast will hit you for"+beastdmg+"damage");
System.out.println("You can block the beast damage by hitting the write key");
Random r = new Random();
int c = r.nextInt(26) + (byte)'a';
System.out.println((char)c);
letter = in.next().charAt(0);
if( letter == ((char)c)){
System.out.println("You blocked the beast damage");
}
else {
System.out.print("You took damage");
}
}
} // main
最佳答案
有多种方法可以做到这一点,我正在以最简单的方式使用OP的风格来回答,因此测量用户按下字母的时间。这是一个功能片段:
System.out.println("You can block the beast damage by hitting the write key");
long startTime = System.currentTimeMillis();
Random r = new Random();
int c = r.nextInt(26) + (byte) 'a';
System.out.println((char) c);
char letter = in.next().charAt(0);
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
if (letter == ((char) c) && elapsedTime <=5000) {
System.out.println("You blocked the beast damage");
} else {
System.out.print("You took damage");
}
希望有帮助。
关于java - 用户输入的时间限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27532502/