用Java写一个电子宠物系统
时间: 2023-12-31 08:05:39 浏览: 26
好的,我可以给您提供一个简单的电子宠物系统Java代码示例,仅供参考:
```
import java.util.Scanner;
public class VirtualPet {
private String name;
private int hunger;
private int thirst;
private int boredom;
public VirtualPet(String name) {
this.name = name;
this.hunger = 50;
this.thirst = 50;
this.boredom = 50;
}
public void feed() {
hunger -= 10;
thirst += 5;
boredom += 5;
}
public void water() {
thirst -= 10;
boredom += 5;
}
public void play() {
boredom -= 10;
hunger += 5;
thirst += 5;
}
public void tick() {
hunger += 5;
thirst += 5;
boredom += 5;
}
public String getName() {
return name;
}
public int getHunger() {
return hunger;
}
public int getThirst() {
return thirst;
}
public int getBoredom() {
return boredom;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Virtual Pet!");
System.out.print("Enter pet name: ");
String petName = scanner.nextLine();
VirtualPet pet = new VirtualPet(petName);
while (true) {
System.out.println("\n" + pet.getName() + " status:");
System.out.println("Hunger: " + pet.getHunger());
System.out.println("Thirst: " + pet.getThirst());
System.out.println("Boredom: " + pet.getBoredom());
System.out.println("\nWhat do you want to do?");
System.out.println("1. Feed " + pet.getName());
System.out.println("2. Water " + pet.getName());
System.out.println("3. Play with " + pet.getName());
System.out.println("4. Do nothing");
int choice = scanner.nextInt();
switch (choice) {
case 1:
pet.feed();
break;
case 2:
pet.water();
break;
case 3:
pet.play();
break;
default:
break;
}
pet.tick();
}
}
}
```
这个电子宠物系统有三个需要关注的状态:饥饿、口渴和无聊。您可以通过输入不同的数字来决定喂食、给水或者玩耍。每个操作都会对状态有不同的影响,同时系统也会定期自动增加状态值,如果任何一个状态达到了100,你的电子宠物就会死亡。
这只是一个简单的示例,您可以根据自己的需要来修改和扩展代码。