037乌龟吃鱼练习题的一些思考
我把037的例题1乌龟吃鱼那个题更形象地写出来了,写了三个小时,我觉得我比小甲鱼的更直观,附上代码供大家讨论。import random as r
importtime
def change_loc(loc_x ,loc_y ,ob) :#将哪个对象的什么位置添加到列表里
temp = list(game_map)
temp = ob
temp = ''.join(temp)
game_map = temp
return game_map
class Tortoise :
#定义🐢类的属性和方法
def __init__(self) :
self.strength = 100
self.loc_x = r.randint(1 ,10 )
self.loc_y = r.randint(1 ,10 )
self.loc =
def move(self) : #仅考虑移动一次
direction = r.randint(1, 4)# 用1—4表示移动方向(上下左右)
if (direction == 1 and self.loc_y != 10) or (direction == 3 and self.loc_y == 1):# 向上走
self.loc_y += 1
print('你的🐢向右走了一步')
elif (direction == 2 and self.loc_x != 10) or (direction == 4 and self.loc_x == 1):# 向右走
self.loc_x += 1
print('你的🐢向下走了一步')
elif (direction == 3 and self.loc_y != 1) or (direction == 1 and self.loc_y == 10):# 向下走
self.loc_y -= 1
print('你的🐢向左走了一步')
elif (direction == 4 and self.loc_x != 1) or (direction == 2 and self.loc_x == 10):# 向左走
self.loc_x -= 1
print('你的🐢向上走了一步')
self.strength -= 1 #先暂时不考虑体力为0的情况
self.loc =
return self.loc
def eat(self) :
self.strength += 20
if self.strength >= 100 : #判断是否超过体力上限
self.strength = 100
print('你的🐢吃了一条🐟,回复20点体力')
class Fish :
#定义🐟类的属性和方法
def __init__(self) :
self.loc_x = r.randint(1 ,10 )
self.loc_y = r.randint(1 ,10 )
self.loc =
#初始化🐢和🐟
tortoise = Tortoise()
fish_loclist = []#用列表存放十条鱼的位置
#将抽象的列表形象化
game_map = []
for w in range(10) : #初始化地图
game_map.append('☐☐☐☐☐☐☐☐☐☐')
#把🐢和🐟添加到地图上
for q in range(10) :
fish = Fish()
while fish.loc in fish_loclist : #保证每条🐟的位置不同
fish = Fish()
fish_loclist.append(fish.loc)
game_map = change_loc(fish.loc_x ,fish.loc_y ,'🐟')
game_map = change_loc(tortoise.loc_x ,tortoise.loc_y ,'🐢')
for i in game_map :
print(i)
#开始迭代🐢吃🐟
while tortoise.strength != 0 :
print('体力: %d' % tortoise.strength)
step = r.randint(1 ,2 )
#while step > 2 :
# print('你的🐢只能走一步或者两步')
# step = int(input('请输入要走的步数:'))
while step :
#print(tortoise.loc) #debug
game_map = change_loc(tortoise.loc_x, tortoise.loc_y, '☐')
tortoise.move()
#print(tortoise.loc) #debug
game_map = change_loc(tortoise.loc_x, tortoise.loc_y, '🐢')
#判断🐢和🐟是否重合
if tortoise.loc in fish_loclist :
fish_loclist.remove(tortoise.loc)
tortoise.eat()
step -= 1
time.sleep(0.7)
for i in game_map:
print(i)
if tortoise.strength == 0 :
print('体力为零,游戏结束,你输了')
if len(fish_loclist) == 0 :
print('🐟都被吃光了,你赢了')
其中🐢和🐟分别是乌龟和鱼的emoji,无奈论坛好像不能识别,大伙凑合看吧。 果然新人发帖没人理 本帖最后由 枵央 于 2020-5-17 19:51 编辑
{:5_109:} 本帖最后由 枵央 于 2020-5-17 19:51 编辑
{:5_109:} 今天才动手了乌龟吃鱼,楼主加了上下左右和位置重叠的判断,值得学习{:10_279:}{:10_279:},看着挺长,但思路挺清晰的!
(自娱自乐属实{:10_256:})
页:
[1]