我在为自己做一个小游戏时遇到一些问题。我遇到问题的代码是用户输入超时。例如:游戏将在屏幕上显示一个字母。用户必须在一定时间内输入该字母;如果他们不这样做,就会受到伤害。如果有人可以解释我可以用什么来解决这个问题,那就太好了。
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
答案 0 :(得分:2)
有多种方法可以做到这一点,我正在以最简单的方式回答使用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");
}
希望它有所帮助。
答案 1 :(得分:0)
你需要看一下Threads。
使用线程,您可以一次执行多个进程,而不是逐行执行线性编码。
例如,您可以说:
while(health > 0){
Thread.sleep(5000); //parameter for sleep is milliseconds, so this is 5 seconds
if(weapon == null){
health -= damage;
}else{ break; }
}
这个问题是你可能需要创建一个单独的类来扩展Thread以调用损失...如果定时方面是必要的,我会建议读取线程。不要从字面上理解这个代码,这只是一个基本的大纲......根据我对线程的经验,你需要创建一个返回武器值的方法,因为你希望你的线程检查用户是否输入了值对于武器。
您可能还想参考这个线程教程:
https://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html