Целью этого кода является запуск таймера в 5 секунд после каждого тика, позволяющего пользователю 5 секунд вводить ввод после каждого тика. Теперь я видел другие способы сделать это, такие как System.currentTimeMillis();
, но я не думаю, что это будет работать для этого экземпляра.
import java.util.Scanner; // Imports scanner utility
import java.util.Random; // Imports the random utility to generate a random number.
import java.lang.Math; // Imports the math utility used for mathematical functions.
import java.util.concurrent.TimeUnit; // Time utility used for time related functions.
import java.util.Timer;
import java.util.TimerTask;
import java.io.*;
class alienPet
{
alien ufo = new alien(); // The alien is created outside of a class so that it can be altered in different methods.
public static void main (String[] param)
{
// We want to call all of the functions
// and procedures to make an interactive
// alien program for the user.
alienPet a = new alienPet();
a.welcomeMessage(); // The class a is created in order to call non-static methods from a static method.
a.alienCreation();
a.tick();
// System.exit(0);
} // END main
/* ***************************************
* Define a method to obtain the users input
* and start the correct method.
*/
public String userInput (String message)
{
Scanner scan = new Scanner(System.in);
String inp;
if (message.equals("")){
}else{
print(message);
}
inp = scan.nextLine();
return inp;
} // END userInput
/* ***************************************
* Define a method to print messages.
*/
public void print (String message)
{
System.out.println(message);
return;
} // END print
/* ***************************************
* Define a method to welcome the user to the game
* and enlighten them on how to play.
*/
public void welcomeMessage ()
{
print("Thank you for playing the pet alien game");
print("In this game, you will have to look after your own alien.");
print("There is multiple aspects to looking after your alien, such as:");
print("Hunger, Behaviour and Thirst.");
print("The game ticks every five seconds, with the hunger and thirst levels dropping with each tick.");
print("");
print("When prompted, you can use the following commands:");
print("feed -> Replenishes alien to max hunger level");
print("drink -> Replenished thirst level to max");
print("exit -> Will end the game immediately.");
print("");
return;
} // END welcomeMessage
/* ***************************************
* Define a method to create alien
*/
public void alienCreation ()
{
ufo.name = userInput("What would you like to name your new alien?");
ufo.hungerRate = ranNum(1, 6);
print("Congratulations on your new alien, " + ufo.name);
print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
alienBehaviour(ufo.hungerRate);
return;
} // END alienCreation
/* ***************************************
* Define a method to display the current
* behaviour of the alien
*/
public void alienBehaviour (int hunger) {
if (hunger <= 2){
print(ufo.name + " is very hungry, and is dangerously angry!!");
String action = userInput("You should feed it as soon as possible. (by typing 'feed')");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("That is a dangerous decision.");
}
}else if (hunger <= 4) {
print(ufo.name + " is mildly hungry, but is in a calm state.");
String action = userInput("Would you like to take any actions?");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("Okay.");
}
}else if (hunger <= 6) {
print(ufo.name + " is not hungry and is in a happy state.");
String action = userInput("Would you like to take any actions?");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("Okay.");
}
}
} // END alienBehaviour
/* ***************************************
* Define a method to feed the alien
*/
public void feedAlien() {
ufo.hungerRate = 6;
print(ufo.name + "'s hunger level replenished to max level 6.");
print(ufo.name + " is now at a happy level.");
} // END feedAlien
/* ***************************************
* Define a method to hydrate the alien
*/
public void alienDrink() {
ufo.thirst = 6;
print(ufo.name + "'s thirst level replenished to max level 6.");
} // END alienDrink
/* ***************************************
* Define a method to do an in-game tick
*/
public void tick() {
print("");
ufo.age++;
if (ufo.age == 100) {
print("It is a sad day.");
print(ufo.name + " has finally reached the age of 100 after a good life and has gone to the after life.");
print("Well done!");
System.exit(0);
}
if (ufo.hungerRate < 0){
print("Oh no! " + ufo.name + " has died of hunger!");
print("GAME OVER!");
ufo.alive = false;
gameEnd();
} else if (ufo.thirst < 0){
print("Oh no! " + ufo.name + " has died of dehydration!");
print("GAME OVER!");
ufo.alive = false;
gameEnd();
}else {
print(ufo.name + "'s current stats:");
print("-Hunger level = " + ufo.hungerRate);
print("-Hydration level = " + ufo.thirst);
print("-Age = " + ufo.age + " days old");
print("");
}
if (ufo.hungerRate > 0){
if (ufo.age % 2 == 0) {
if (ufo.hungerRate <= 2){
print(ufo.name + " is very hungry, and is dangerously angry!!");
}else if (ufo.hungerRate <= 4) {
print(ufo.name + " is mildly hungry, but is in a calm state.");
}else if (ufo.hungerRate <= 6) {
print(ufo.name + " is not hungry and is in a happy state.");
}
}
}
ufo.hungerRate--;
ufo.thirst--;
try{
getInput();
}
catch (Exception e) {
}
finally{
tick();
}
} // END tick
private String act = "";
TimerTask task = new TimerTask()
{
public void run()
{
if( act.equals("") )
{
tick();
}
}
};
/* ***************************************
* Define a method to get a user input
* with a time limit of 5 seconds.
*/
public void getInput() throws Exception
{
Timer timer = new Timer();
timer.schedule( task, 5*1000 );
BufferedReader in = new BufferedReader(
new InputStreamReader( System.in ) );
act = in.readLine();
timer.cancel();
if (act.equals("feed")){
feedAlien();
}else if (act.equals("drink")) {
alienDrink();
}else if (act.equals("exit")) {
gameEnd();
}
tick();
} // END getInput
/* ***************************************
* Define a method to end the game and
* display the results
*/
public void gameEnd() {
if (ufo.alive == false) {
print("Your alien, " + ufo.name + ", lasted " + ufo.age + " days.");
}else {
print("Well done you kept your alien, " + ufo.name + ", alive for " + ufo.age + " days.");
}
System.exit(0);
}
public int ranNum(int min, int max){ // A function that generates a random integer wihin a given range.
Random random = new Random();
return random.ints(min,(max+1)).findFirst().getAsInt();
} // END ranNum
} // END class alienPet
class alien {
String name;
int age = 0;
int hungerRate;
int thirst = 6;
Boolean alive = true;
}
Процедура, которая вызывает исключение: getInput()
,Я хочу использовать это повторно, но кажется, что таймер запустится только один раз и не запустится снова, поэтому tick()
просто циклически повторяется снова и снова. Поскольку я - любитель Java, любая помощь будет принята с благодарностью.