设置了条件为什么不能生效?
import randomclass Fish:
move = 1
class Turtle:
move = 2
life = 100
x = 0
y = 0
def born(self,x,y):
self.x = random.randint(0,x)
self.y = random.randint(0,y)
print(self.x,self.y)
return self.x,self.y
def swim(self,x,y):
direction = random.randint(1,4)
print('方向为%d'%direction)
print('现在的坐标是:x= %d,y= %d'%(self.x,self.y))
if direction == 1 and x > 0:
self.x -= self.move
print('乌龟向左移动两步')
elif direction == 2 and x < 10:
print(direction == 2 and x < 10)
self.x += self.move
print('乌龟向右移动两步')
elif direction == 3 and y < 10:
self.y += self.move
print('乌龟向上移动两步')
elif direction == 4 and y > 0:
self.y -= self.move
print('乌龟向下移动两步')
turtle = Turtle()
x,y = turtle.born(10,10)
while turtle.life >= 0:
turtle.swim(x,y)
turtle.life -= 1
print(turtle.life)
为什么设置了条件,王八还是会游出范围?
现在的坐标是:x= 1,y= -12
乌龟向下移动两步
9
方向为1
现在的坐标是:x= 1,y= -14
乌龟向左移动两步
8
方向为2
现在的坐标是:x= -1,y= -14
True
乌龟向右移动两步
7
方向为2 import random
class Fish:
move = 1
class Turtle:
move = 2
life = 100
x = 0
y = 0
def born(self,x,y):
self.x = random.randint(0,x)
self.y = random.randint(0,y)
print(self.x,self.y)
return self.x,self.y
def swim(self):
direction = random.randint(1,4)
print('方向为%d'%direction)
if self.x > 10:
self.x = 9
if self.y > 10:
self.y = 9
print('现在的坐标是:x= %d,y= %d'%(self.x,self.y))
if direction == 1 and self.x > 0:
self.x -= self.move
print('乌龟向左移动两步')
elif direction == 2 and self.x < 10:
self.x += self.move
print('乌龟向右移动两步')
elif direction == 3 and self.y < 10:
self.y += self.move
print('乌龟向上移动两步')
elif direction == 4 and self.y > 0:
self.y -= self.move
print('乌龟向下移动两步')
turtle = Turtle()
x,y = turtle.born(10,10)
while turtle.life >= 0:
turtle.swim()
turtle.life -= 1
print(turtle.life) qiuyouzhi 发表于 2020-5-19 16:07
没毛病!
页:
[1]