请写出大鱼吃小鱼的代码
时间: 2023-07-16 18:17:00 浏览: 113
这里是一个简单的大鱼吃小鱼的 Python 代码示例:
```python
class Fish:
def __init__(self, size, direction):
self.size = size
self.direction = direction
def eat(self, other_fish):
if self.size > other_fish.size:
self.size += other_fish.size
return True
else:
return False
def move(self):
if self.direction == "right":
self.direction = "left"
else:
self.direction = "right"
class Aquarium:
def __init__(self, fish_list):
self.fish_list = fish_list
def update(self):
for i in range(len(self.fish_list)):
current_fish = self.fish_list[i]
# Move fish
current_fish.move()
# Check if fish can eat other fish
for j in range(i+1, len(self.fish_list)):
other_fish = self.fish_list[j]
if current_fish.direction == other_fish.direction:
continue
if current_fish.eat(other_fish):
self.fish_list.pop(j)
break
if __name__ == "__main__":
# Create fish
fish1 = Fish(5, "right")
fish2 = Fish(3, "left")
fish3 = Fish(2, "right")
fish4 = Fish(1, "left")
# Add fish to aquarium
aquarium = Aquarium([fish1, fish2, fish3, fish4])
# Simulate fish movement and eating for 10 iterations
for i in range(10):
aquarium.update()
print([fish.size for fish in aquarium.fish_list])
```
这个代码模拟了一个简单的水族馆环境,其中包含多条鱼。每条鱼有一个大小和一个移动方向(左或右)。在每个时间步长里,每条鱼都会移动,并且如果它的方向和其他鱼的方向不同,它会尝试吃掉其他鱼中大小比它小的鱼。如果它成功吃掉了一条鱼,那么它的大小会增加。每个时间步长后,程序将打印出每条鱼的大小。
阅读全文