用Java写一个掠食者和被掠食者
时间: 2024-03-25 18:41:25 浏览: 22
以下是用 Java 写的掠食者和被掠食者的示例代码:
```
public class Predator {
private int energy;
private int x;
private int y;
public Predator(int x, int y) {
this.energy = 10;
this.x = x;
this.y = y;
}
public void move(int dx, int dy) {
this.x += dx;
this.y += dy;
this.energy--;
}
public void eat(Prey prey) {
this.energy += prey.getNutritionValue();
}
public int getEnergy() {
return this.energy;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
public class Prey {
private int nutritionValue;
private int x;
private int y;
public Prey(int x, int y) {
this.nutritionValue = 5;
this.x = x;
this.y = y;
}
public void move(int dx, int dy) {
this.x += dx;
this.y += dy;
}
public int getNutritionValue() {
return this.nutritionValue;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
```
以上代码定义了两个类,`Predator` 和 `Prey`,分别代表掠食者和被掠食者。`Predator` 类有 `energy`、`x` 和 `y` 三个属性,分别代表能量、横坐标和纵坐标;`Prey` 类有 `nutritionValue`、`x` 和 `y` 三个属性,分别代表营养价值、横坐标和纵坐标。
`Predator` 类有 `move` 和 `eat` 两个方法,分别代表移动和吃掉被掠食者。`Prey` 类有 `move` 方法,代表移动。两个类都有 `getX` 和 `getY` 方法,分别返回横坐标和纵坐标。`Predator` 类还有一个 `getEnergy` 方法,返回当前能量值。
这只是一个简单的示例,可以根据需要进一步扩展。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)