|
发表于 2020-3-2 20:10:14
|
显示全部楼层
用全局变量修改的代码
- import random
- def pos_cur():#生成鱼和乌龟的初始化位置和行动方向
- turtlelfx=random.randint(0,1)#横方向
- if turtlelfx==0:
- turtlelfx=-1
- turtlehfx=random.randint(0,1)#竖方向
- if turtlehfx==0:
- turtlehfx=-1
- turtleh=random.randint(0,10)
- turtlel=random.randint(0,10)
- turtle_pos=[turtlelfx,turtlehfx,[turtlel,turtleh],100]
- fish_pos=dict1.fromkeys(range(10),[0,0,0,0])#初始化的10条鱼的行动方向位置均为[0,0,0,0]
- for i in range(10):#给每条鱼设置不同的行动方向和位置
- fishlfx=random.randint(0,1)
- if fishlfx==0:
- fishlfx=-1
- fishhfx=random.randint(0,1)
- if fishhfx==0:
- fishhfx=-1
- fishh=random.randint(0,10)
- fishl=random.randint(0,10)
- fish_pos[i]=[fishlfx,fishhfx,[fishl,fishh]]
- return [fish_pos,turtle_pos]
- def fish_move(fish_pos):
- k=random.randint(0,1)
- if k==1:
- fish_pos[2][0]+=fish_pos[0]
- else:
- fish_pos[2][1]+=fish_pos[1]
- return fish_pos
- def turtle_move(turtle_pos):
- k=random.randint(0,5)
- if k==0:
- turtle_pos[2][0]+=turtle_pos[0]
- turtle_pos[3]-=1
- elif k==1:
- turtle_pos[2][1]+=turtle_pos[1]
- turtle_pos[3]-=1
- elif k in [2,3]:
- turtle_pos[2][0]+=turtle_pos[0]
- turtle_pos[2][1]+=turtle_pos[1]
- turtle_pos[3]-=2
- elif k in [4,5]:
- turtle_pos[3]-=2
- return turtle_pos
- def panduan(pos):
- global a,b
- a=len(pos[0])
- if a==0:
- print('鱼死光了')
- return 1
- b=pos[1][3]
- if b<=0:
- print('龟死了,还剩%i条鱼' % a)
- return 0
- print(b*a)
- # if b*a>0:
- while a>0 and b>0:
- for i in list(pos[0].keys()):
- if pos[0][i][2]==pos[1][2]:#当乌龟吃掉鱼的时候,把鱼抛出
- pos[0].pop(i)
- print('乌龟把鱼%d吃掉了'%i)
- if pos[1][3]<=80:
- pos[1][3]+=20
- else:
- pos[1][3]=100
- else:
- if pos[0][i][2][0] in [0,10]:
- if pos[0][i][2][0] == 0:
- pos[0][i][0]=1
- else:
- pos[0][i][0]=-1
- if pos[0][i][2][1] in [0,10]:
- if pos[0][i][2][1] == 0:
- pos[0][i][1]=1
- else:
- pos[0][i][1]=-1
- pos[0][i]=fish_move(pos[0][i])
- #乌龟边界值反向
- if pos[1][2][0] in [0,10]:
- if pos[1][2][0] == 0:
- pos[1][0]=1
- else:
- pos[1][0]=-1
- if pos[1][2][1] in [0,10]:
- if pos[1][2][1] == 0:
- pos[1][1]=1
- else:
- pos[1][1]=-1
- #乌龟的行动
- pos[1]=turtle_move(pos[1])
- panduan(pos)#只要还有鱼并且龟活着的时候继续执行
- # else:
- # if a==0:
- # return 1
- # else:
- # return 0
- dict1={}
- a=0
- b=0
- pos1=pos_cur()#获取初始化的鱼和龟的位置
- turtle_life=panduan(pos1)#执行游戏
- if turtle_life==0:
- print('龟挂了,游戏结束')
- elif turtle_life==1:
- print('龟赢了')
复制代码 |
|