|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在面相对象编程 小甲鱼 零基础python37课 的练习中, 有些问题不是很明白, 我把它们标注在了代码中, 求大佬们拍打小萌新。 爱你们
import random as r
legal_x = [0, 10]
legal_y = [0, 10]
class Turtle:
def __init__(self):
self.power = 100
# the initial location is random
self.x = r.randint(legal_x[0], legal_x[1])
# the num in [] is index, this line means generating random int between 0 and 10
self.y = r.randint(legal_y[0], legal_y[1])
def move(self):
# move to a new location (x,y) without a firm direction
new_x = self.x + r.choice([1,2,-1,-2])
new_y = self.y + r.choice([1,2,-1,-2])
# check if the new location is outside of the required area (x)
if new_x < legal_x[0]:
self.x = legal_x[0] - (new_x - legal_x[0])
elif new_x > legal_x[1]:
self.x= legal_x[1] - (new_x - legal_x[1])
else:
self.x = new_x
# check if the new location is outside of the required area (x)
if new_y < legal_y[0]:
self.y = legal_y[0] - (new_y - legal_y[0])
elif new_y > legal_y[1]:
self.y = legal_y[1] - (new_y - legal_y[1])
else:
self.y = new_y
# power customise
self.power -=1
# return the new location
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(legal_x[0], legal_x[1])
self.y = r.randint(legal_y[0], legal_y[1])
def move(self):
# move to a new location (x,y) without a firm direction
new_x = self.x + r.choice([1, -1])
new_y = self.y + r.choice([1, -1])
# check if the new location is outside of the required area (x)
if new_x < legal_x[0]:
self.x = legal_x[0] - (new_x - legal_x[0])
elif new_x > legal_x[1]:
self.x = legal_x[1] - (new_x - legal_x[1])
else:
self.x = new_x
# check if the new location is outside of the required area (x)
if new_y < legal_y[0]:
self.y = legal_y[0] - (new_y - legal_y[0])
elif new_y > legal_y[1]:
self.y = legal_y[1] - (new_y - legal_y[1])
else:
self.y = new_y
# return the new location
return (self.x, self.y)
turtle = Turtle()
fish = []
for i in range(10):
new_fish=Fish()
fish.append(new_fish)
while True: # 问题一: while True, 这里判断的是什么条件为True啊?
if not len(fish): # 问题二: 为什么这里判断fish列表为空呢?? if not len(fish) 在这里的用法??
print('all fishes have been eaten, game over')
break
if not turtle.power: # 问题三: 为什么这里不是 if turtle.power==0 这个条件呢?
print('the turtle has died because of the lack of the power')
break
pos = turtle.move()
for each_fish in fish[:]: # 问题四: 为什么这里不直接 for each_fish in fish ?
if each_fish.move() == pos:
# same location, fish is eaten
turtle.eat()
fish.remove(each_fish)
print('there is a fish was eaten, OMG')
问题二 fish 列表是存鱼的条数的,你每次被小乌龟吃掉一只就移除一只 直到列表全部被吃完,小乌龟胜利,
当列表全部被吃完时候 len(fish) == 0 的 0 等价于 False 你加上not 就变成了 True if 条件就成立 开始执行if 里面的语句
问题三:条件可以为if turtle.power==0
|
|