|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 heywilliam 于 2018-2-12 17:07 编辑
想求大神帮我看一下我自己写的代码有没有可以改进的地方,尽管能跑成功~感激不尽~~
题目: (题目跑到帖子最下方了)
我自己写的代码,其实我只写出了乌龟和鱼的类,剩下的乌龟吃鱼我不会写,是抄的答案.
我的代码:
- import random
- class Turtle:
- energy = 100
- def turtlemove(self):
- tx = random.randint(0, 11) # 乌龟初始位置x
- ty = random.randint(0, 11) # 乌龟初始位置y
- tmove = random.randint(1, 3) # 乌龟可移动距离
- tdirection = random.choice(['tx', 'ty'])
- #乌龟移动
- if tdirection == 'tx':
- tx += tmove
- else:
- ty += tmove
- #判断出界
- if tx > 10:
- tx = 10 - ( tx - 10 )
- if tx < 0:
- tx = 0 - tx
- if ty > 10:
- ty = 10 - ( ty - 10 )
- if ty < 0:
- ty = 0 - ty
- self.energy -= 1
- return (tx, ty)
- def eat(self):
- self.energy += 20
- if self.energy > 100:
- self.energy = 100
- class Fish:
- def fishmove(self):
- fx = random.randint(0, 11) # 鱼初始位置x
- fy = random.randint(0, 11) # 鱼初始位置y
- fmove = 1
- fdirection = random.choice(['fx','fy'])
- #鱼移动
- if fdirection == 'fx':
- fx += fmove
- else:
- fy += fmove
- # 判断出界
- if fx > 10:
- fx = 10 - (fx - 10)
- if fx < 0:
- fx = 0 - fx
- if fy > 10:
- fy = 10 - (fy - 10)
- if fy < 0:
- fy = 0 - fy
- return (fx, fy)
- ###############以下代码跟参考答案一样了############
- turtle = Turtle() #生成乌龟一只
- #生成鱼10只
- fish = []
- for i in range(10):
- new_fish = Fish()
- fish.append(new_fish)
- #游戏开始
- while True:
- if not len(fish):
- print("鱼都吃完了,游戏结束!")
- break
- if not turtle.energy:
- print("乌龟没力气了,游戏结束!")
- break
- pos = turtle.turtlemove()
- for each_fish in fish[:]:
- if each_fish.fishmove() == pos:
- #鱼儿被吃掉了
- turtle.eat()
- fish.remove(each_fish)
- print("有一条鱼儿被吃掉了...")
复制代码 |
-
|