#講道理烏龜喫魚的嘛?
先上代碼,雖然感覺很多地方可以優化
import random
import time
class Tortoise:
x = random.randint(0,10)
y = random.randint(0,10)
def __init__(self):
self.life = 100
print('Tortoise: (%d,%d)'%(self.x,self.y))
print('life : %d'%(self.life))
def move(self):
step = random.randint(1,2)
direction = random.randint(-1,2)
self.life -= step
if direction == 2:
if self.x + step - 10 == 1:
self.x = 9
elif self.x + step - 10 == 2:
self.x = 8
else:
self.x += step
if direction == 1:
if self.y + step - 10 == 1:
self.y = 9
elif self.y + step - 10 == 2:
self.y = 8
else:
self.y += step
if direction == 0:
if self.x - step == -1:
self.x = 1
elif self.x - step == -2:
self.x = 2
else:
self.x -= step
if direction == -1:
if self.y - step == -1:
self.y = 1
elif self.y - step == -2:
self.y = 2
else:
self.y -= step
return (self.x,self.y)
class Fish:
def __init__(self,name):
self.name = name
self.x = random.randint(0,10)
self.y = random.randint(0,10)
print('%s: (%d,%d)'%(name,self.x,self.y))
def move(self):
direction = random.randint(-1,2)
if direction == 2:
if self.x + 1 - 10 == 1:
self.x = 9
else:
self.x += 1
if direction == 1:
if self.y + 1 - 10 == 1:
self.y = 9
else:
self.y += 1
if direction == 0:
if self.x - 1 == -1:
self.x = 1
else:
self.x -= 1
if direction == -1:
if self.y - 1 == -1:
self.y = 1
else:
self.y -= 1
return (self.x,self.y)
def game():
start_time = time.time()
fishlist = list()
fishObj = list()
for i in range(1,11):
name = 'fish' + str(i)
fishlist.append(name)
wugui = Tortoise()
for fish in fishlist:
fish = Fish(fish)
fishObj.append(fish)
while True:
(x,y) = wugui.move()
for fish in fishObj:
(a,b) = fish.move()
if (a,b) == (x,y) and wugui.life > 0:
fishObj.remove(fish)
print('%s魚被吃了'%(fish.name))
if wugui.life > 80:
wugui.life = 100
else:
wugui.life += 20
if wugui.life == 0:
print("烏龜累死了")
break
elif fishObj == []:
print('沒有魚了')
break
end_time = time.time()
print('%d只魚存活成功'%(len(fishObj)))
print('took %f second'%(end_time - start_time))
game()
運行結果如下:
心得體會:
問題:有的時候運行會卡住類似這樣
目前還不知道什麼原因導致。
掌握了random中randomint 與 choice 函數
在運動的方向選擇上可以進一步優化