玩家让老鼠随机外出找粮食,每次一只老鼠外出java代码
时间: 2023-10-21 17:07:15 浏览: 74
以下是一个简单的 Java 代码示例,用于模拟玩家让老鼠随机外出找粮食的情景:
```java
import java.util.Random;
public class Mouse {
private int id;
private String name;
public Mouse(int id, String name) {
this.id = id;
this.name = name;
}
public void goOutForFood() {
Random random = new Random();
boolean foundFood = random.nextBoolean();
if (foundFood) {
System.out.println(name + " (" + id + ")" + " found food outside!");
} else {
System.out.println(name + " (" + id + ")" + " didn't find any food outside.");
}
}
}
public class Game {
public static void main(String[] args) {
Mouse mouse1 = new Mouse(1, "Mickey");
Mouse mouse2 = new Mouse(2, "Jerry");
Mouse mouse3 = new Mouse(3, "Speedy");
mouse1.goOutForFood();
mouse2.goOutForFood();
mouse3.goOutForFood();
}
}
```
在这个示例中,我们定义了一个 `Mouse` 类,其中包含老鼠的 ID 和名称,并且有一个 `goOutForFood()` 方法,该方法模拟老鼠外出寻找食物的行为。方法内部使用 `java.util.Random` 类生成一个随机布尔值,以表示老鼠是否找到了食物。在 `Game` 类中,我们创建了三只老鼠,并让它们分别外出寻找食物。
阅读全文