|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我把037的例题1乌龟吃鱼那个题更形象地写出来了,写了三个小时,我觉得我比小甲鱼的更直观,附上代码供大家讨论。
import random as r
import time
def change_loc(loc_x ,loc_y ,ob) : #将哪个对象的什么位置添加到列表里
temp = list(game_map[loc_x - 1])
temp[loc_y - 1] = ob
temp = ''.join(temp)
game_map[loc_x - 1] = 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 = [self.loc_x , self.loc_y]
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 = [self.loc_x, self.loc_y]
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 = [self.loc_x , self.loc_y]
#初始化🐢和🐟
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('🐟都被吃光了,你赢了')
|
|