|  | 
 
| 
本帖最后由 uranometria 于 2020-10-6 16:03 编辑
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  
 # 1. 游戏编程:按以下要求定义一个乌龟类和鱼类并尝试编写游戏。(初学者不一定可以完整实现,但请务必先自己动手,你会从中学习到很多知识的^_^)
 # 假设游戏场景为范围(x, y)为0<=x<=10,0<=y<=10
 # 游戏生成1只乌龟和10条鱼
 # 它们的移动方向均随机
 # 乌龟的最大移动能力是2(Ta可以随机选择1还是2移动),鱼儿的最大移动能力是1
 # 当移动到场景边缘,自动向反方向移动
 # 乌龟初始化体力为100(上限)
 # 乌龟每移动一次,体力消耗1
 # 当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20
 # 鱼暂不计算体力
 # 当乌龟体力值为0(挂掉)或者鱼儿的数量为0游戏结束
 #
 import random
 
 class Fish:
 # x_i = random.randint(0, 10)
 # y_i = random.randint(0, 10)
 # x = random.randint(-1, 1)
 # y = random.randint(-1, 1)
 #  与下面 def __init__(self): 内容一样
 
 def __init__(self):
 self.x_i = random.randint(0, 10)
 self.y_i = random.randint(0, 10)
 
 def fish_move(self):
 self.x = random.randint(-1, 1)
 self.y = random.randint(-1, 1)
 if 1 < self.x_i - self.x < 9:
 self.x_i -= self.x
 else:
 if self.x_i - self.x <= 1:
 self.x_i += abs(self.x)
 elif self.x_i + self.x >= 9:
 self.x_i -= abs(self.x)
 
 if 1 < self.y_i - self.y < 9:
 self.y_i -= self.y
 else:
 if self.y_i - self.y <= 1:
 self.y_i += abs(self.y)
 elif self.y_i + self.y >= 9:
 self.y_i -= abs(self.y)
 
 return self.x_i, self.y_i
 
 class Turtle(Fish):
 def __init__(self):
 super().__init__()
 self.mp = 100
 
 def turtle_move(self):
 self.x = random.randint(-2, 2)
 self.y = random.randint(-2, 2)
 
 if 2 < self.x_i - self.x < 8:
 self.x_i -= self.x
 elif self.x_i - self.x <= 2:
 self.x_i += abs(self.x)
 elif self.x_i + self.x >= 8:
 self.x_i -= abs(self.x)
 
 if 2 < self.y_i - self.y < 8:
 self.y_i -= self.y
 elif self.y_i - self.y <= 2:
 self.y_i += abs(self.y)
 elif self.y_i + self.y >= 8:
 self.y_i -= abs(self.y)
 
 self.mp -= 1
 
 return self.x_i, self.y_i
 
 def eat(self):
 self.mp += 20
 if self.mp > 100:
 self.mp = 100
 
 list_fish = []
 for i in range(10):
 f = Fish()
 list_fish.append(f)
 # print(list_fish)
 t = Turtle()
 
 while True:
 if t.mp == 0:
 print('体力耗尽,乌龟挂掉')
 # print(t.mp)
 break
 elif len(list_fish) == 0:
 print('游戏结束')
 break
 print(t.mp)
 pos = t.turtle_move()
 for a in list_fish:
 # if a.fish_move() == t.turtle_move():  # 乌龟一直在动
 if a.fish_move() == pos:  # 乌龟位置固定
 # print('!!!乌龟坐标:%s;鱼的坐标:%s' % (str(t.turtle_move()), str(a.fish_move())))  # 只要加上这句,体力的消耗就会增加1,但是用小甲鱼的答案加上坐标提示的情况下,不会影响体力消耗,这是为什么呢?因为调用了类的方法吗?
 list_fish.remove(a)
 print('好吃好吃!现在还剩下%d条鱼~' % len(list_fish))
 t.eat()
 # print(t.mp)
 # if t.mp <= 0:
 #     print('die')
 #     print(t.mp)
 #     break
 
 
因为你又调用了一次move函数,乌龟移动了一次,自然体力就降了。要打印的话就像你上面写的 pos = t.turtle_move(),在比较鱼的坐标和乌龟的坐标前 加个pos1 =a.fish_move(),比较pos和pos1,然后打印pos和pos1 | 
 |