乌龟吃小鱼
import random as fclass Turtle:
def __init__(self):
self.energy=100
self.x=f.randint(0,10)
self.y=f.randint(0,10)
def eat(self):
self.energy+=20
if self.energy>100:
self.energy=100
def move(self):
self.energy-=1
self.x_new=f.choice()+self.x
self.y_new=f.choice()+self.y
if self.x_new>10:
self.x=10-(self.x_new-10)
elif self.x_new<0:
self.x=-(self.x_new)
else:
self.x=self.x_new
if self.y_new>10:
self.y=10-(self.y_new-10)
elif self.y_new<0:
self.y=-(self.y_new)
else:
self.y=self.y_new
return (self.x,self.y)
class Fish:
def __init__(self):
self.x=f.randint(0,10)
self.y=f.randint(0,10)
def move(self):
self.x_new=f.choice()+self.x
self.y_new=f.choice()+self.y
if self.x_new>10:
self.x=10-(self.x_new-10)
elif self.x_new<0:
self.x=-(self.x_new)
else:
self.x=self.x_new
if self.y_new>10:
self.y=10-(self.y_new-10)
elif self.y_new<0:
self.y=-(self.y_new)
else:
self.y=self.y_new
return(self.x,self.y)
turtle=Turtle()
fish=Fish()
all_fish=10
while True:
if turtle.energy==0:
print('乌龟体力用光了,游戏结束')
break
if all_fish==0:
print('鱼被吃光了,游戏结束')
break
if fish.move()==turtle.move():
print('一条鱼被吃了')
all_fish-=1
turtle.eat()
else:
turtle.move()
fish.move()
这个代码运行与小甲鱼老师的结果差异有点大,总数吃两三条就累死了这是哪里出错了吗{:10_266:}
你没有创造 10 个鱼类,而是只实例化了一个鱼
你代码是一个鱼 有 10 次生命值了
本帖最后由 小伤口 于 2020-11-29 02:22 编辑
,哦
Twilight6 发表于 2020-11-26 17:40
你没有创造 10 个鱼类,而是只实例化了一个鱼
你代码是一个鱼 有 10 次生命值了
能纠正一下吗{:10_266:}
必须得{:10_245:}for循环吗 本帖最后由 小伤口 于 2020-11-26 23:12 编辑
Twilight6 发表于 2020-11-26 17:40
你没有创造 10 个鱼类,而是只实例化了一个鱼
你代码是一个鱼 有 10 次生命值了
import random as r
class Wugui:
def __init__(self):
self.nengliang=100
def move1(self):
self.x=r.randint(0,10)
self.y=r.randint(0,10)
x1=self.x+r.choice()
y1=self.y+r.choice()
if x1<0:
self.x=-x1
elif x1>10:
self.x=10-(x1-self.x)
else:
self.x=x1
if y1<0:
self.y=-y1
elif y1>10:
self.y=10-(y1-self.y)
else:
self.y=y1
self.nengliang=self.nengliang-1
return(self.x,self.y)
def tili(self):
self.nengliang+=20
if self.nengliang>100:
self.nengliang=100
class Fish:
def leave(self):
self.a=r.randint(0,10)
self.b=r.randint(0,10)
a1=self.a+r.choice()
b1=self.b+r.choice()
if a1<0:
self.a=-a1
elif a1>10:
self.a=10-(a1-self.a)
else:
self.a=a1
if b1<0:
self.b=-b1
elif b1>10:
self.b=10-(b1-self.b)
else:
self.b=b1
return(self.a,self.b)
c=Wugui()
d=[]
for i in range(0,10):
e=Fish()
d.append(e)
while True:
f=len(d)
if f==0:
print('鱼儿被吃光了')
break
ifc.nengliang==0:
print('龟龟被累死了')
break
pos=c.move1()
for i in d[:]:
if i.leave()==pos:
c.tili()
d.remove(i)
print('有一条鱼儿被吃了')
这样好像还是不行{:10_266:} 小伤口 发表于 2020-11-26 17:45
import random as r
class Wugui:
def __init__(self):
可以正常运行呀,你要多跑几次,因为本身这游戏对乌龟就很不公平的 小伤口 发表于 2020-11-26 17:42
能纠正一下吗
必须得for循环吗
不是必须 for 循环,这里 for 循环只是方便将 Fish() 实例对象放入列表中去,也方便后续 10 只鱼的移动
Twilight6 发表于 2020-11-26 17:52
不是必须 for 循环,这里 for 循环只是方便将 Fish() 实例对象放入列表中去,也方便后续 10 只鱼的移 ...
谢谢,非常感谢{:10_297:} 小伤口 发表于 2020-11-26 17:56
谢谢,非常感谢
客气了~
页:
[1]