|
|

楼主 |
发表于 2017-1-5 16:07:46
|
显示全部楼层
谢谢大神,你说的没错,我改了,改后代码如下:
import random
class Turtle:
energy = 100
x_low_bound = y_low_bound = 0
x_high_bound = y_high_bound = 10
x_begin = int(random.randint(0,10))
y_begin = int(random.randint(0,10))
def move(self):
step = random.choice([1,2])
x_direction = random.choice([-2,-1,1,2]) #控制方向
y_direction = random.choice([-2,-1,1,2])
if x_direction == 1 or x_direction == 2:
if self.x_begin + step <= self.x_high_bound:
self.x_begin += step
else: #再走step会碰到边界,先走完离边界剩下的步数,再走相反的步数
self.x_begin = self.x_begin + (10 - self.x_begin) - (step - (10-self.x_begin))
elif x_direction == -1 or x_direction == -2:
if self.x_begin - step >= self.x_low_bound :
self.x_begin -= step
else:
self.x_begin = self.x_begin - (self.x_begin-0) + (step - (self.x_begin-0))
if y_direction == 1 or y_direction == 2:
if self.y_begin + step <= self.y_high_bound :
self.y_begin += step
else:
self.y_begin = self.y_begin + (10 - self.y_begin) - (step - (10-self.y_begin))
elif y_direction == -1 or y_direction == -2:
if self.y_begin - step >= self.y_low_bound :
self.y_begin -= step
else:
self.y_begin = self.y_begin - (self.y_begin-0) + (step - (self.y_begin-0))
self.energy -= 1
return (self.x_begin,self.y_begin)
#if self.energy == 0:
#print('The turtile is dead')
class Fish:
x_begin = int(random.randint(0,10))
y_begin = int(random.randint(0,10))
x_low_bound = y_low_bound = 0
x_high_bound = y_high_bound = 10
step = 1
def move(self): #鱼随机移动
x_status = int(random.randint(-1,1))
if self.x_low_bound <= self.x_begin + self.step * x_status <= self.x_high_bound :
self.x_begin = self.x_begin + self.step * x_status
else: #碰到边缘向相反方向移动
self.x_begin = self.x_begin - self.step * x_status
y_status = int(random.randint(-1,1))
if self.y_low_bound <= self.y_begin + self.step * y_status <= self.y_high_bound :
self.y_begin = self.y_begin + self.step * y_status
else:
self.y_begin = self.y_begin - self.step * y_status
return (self.x_begin,self.y_begin)
def Game_begin():
turtle=Turtle()
fish = []
fish_num = 10
for i in range(0,fish_num): #初始化生成10条鱼
fish.append(Fish())
while True:
pos_turtle = turtle.move()
pos_fish = []
for i in range(0,fish_num):
pos_fish.append(fish[i].move()) #下标越界
if pos_turtle == pos_fish[i] :
turtle.energy += 20
if turtle.energy >= 100:
turtle.energy = 100
print('有一条鱼被吃掉啦~~~')
del fish[i] #鱼被吃掉了
fish_num -= 1
break
if turtle.energy == 0:
break
return 'Game Over !'
|
|