|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 布响拉锯 于 2024-6-4 19:07 编辑
import random as r
class Turtle:
def __init__(self):
self.power = 100
self.x = r.randint(0,10)
self.y = r.randint(0,10)
def move(self):
new_x =self.x+r.choice([1,2,-1,-2])
new_y = self.y + r.choice([1,2,-1,-2])
if new_x <0:
self.x = 0-new_x
elif new_x >10:
self.x = 20-new_x
else:
self.x = new_x
if new_y <0:
self.y = 0-new_y
elif new_y>10:
self.y = 20 -new_y
else:
self.y = new_y
self.power -= 1
return (self.x,self.y)
def eat(self):
self.power +=20
if self.power>100:
self.power =100
class Fish:
def __init__(self):
self.x = r.randint(0, 10)
self.y = r.randint(0, 10)
def move(self):
new_x =self.x+r.choice([1,-1])
new_y = self.y + r.choice([1,-1])
if new_x < 0:
self.x = 0 - new_x
elif new_x > 10:
self.x = 20 - new_x
else:
self.x = new_x
if new_y < 0:
self.y = 0 - new_y
elif new_y > 10:
self.y = 20 - new_y
else:
self.y = new_y
return (self.x, self.y)
turtle = Turtle()
fish = []
for i in range(10):
new_fish = Fish()
fish.append(new_fish)
while True:
if not turtle.power:
print('没体力了,游戏结束')
if not len(fish):
print('小鱼都被你吃完了,游戏胜利')
print("乌龟移动前坐标:", (turtle.x ,turtle.y))
turtle.move()
print("乌龟移动后坐标:", (turtle.x ,turtle.y))
for item in fish:
print("鱼移动前坐标:", (item.x ,item.y))
item.move()
print("鱼移动后坐标:", (item.x ,item.y))
if item.x==turtle.x and item.y==turtle.y:
turtle.eat()
fish.remove(item)
print("死了一只鱼")
print("乌龟最新体力值为 %d"%turtle.power)
为什么卡在while循环了呢
在你的代码中,while循环内部缺少对乌龟的移动操作。导致程序在第一次迭代后陷入无限循环。
为了解决这个问题,你需要在while循环内部添加乌龟的移动操作。可以像下面这样修改代码:
while True:
if not turtle.power:
print('没体力了,游戏结束')
break
if not len(fish):
print('小鱼都被你吃完了,游戏胜利')
break
print("乌龟移动前坐标:", (turtle.x ,turtle.y))
turtle.move()
print("乌龟移动后坐标:", (turtle.x ,turtle.y))
for item in fish:
print("鱼移动前坐标:", (item.x ,item.y))
item.move()
print("鱼移动后坐标:", (item.x ,item.y))
if item.x==turtle.x and item.y==turtle.y:
turtle.eat()
fish.remove(item)
print("死了一只鱼")
print("乌龟最新体力值为 %d"%turtle.power)
这样,乌龟每次移动前会打印出移动前的坐标,然后进行移动操作,再打印出移动后的坐标。同时,也会对每条鱼进行移动操作,判断是否与乌龟的位置重合,若重合则乌龟会吃掉该条鱼,并打印相应信息。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
|
|