|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import random
class Tutle:
mv=random.choice(range(1,3))
x=random.choice(range(0,11))
y=random.choice(range(0,11))
direct=random.choice(['left','right','up','down'])
def __init__(self):#初始体力
self.num=1
pos=[]
self.pos=[self.x,self.y]#初始位置
def move(self):
for i in range(self.num):#按体力次数循环
self.mv=random.choice(range(1,3))
for i in range(self.mv):#一次移动后的位置变化
self.direct=random.choice(['left','right','up','down'])
if self.direct=='right':
if self.x+1 > 10:
self.x=9
else:
self.x=self.x+1
elif self.direct=='leif':
if self.x-1 <0:
self.x=1
else:
self.x=self.x-1
elif self.direct=='up':
if self.y+1 > 10:
self.y=9
else:
self.y=self.y+1
else :
if self.y-1 <0:
self.y=1
else:
self.y=self.y-1
self.pos=[self.x,self.y]
class Fish:
mv=1
## x=random.choice(range(0,11))
## y=random.choice(range(0,11))
## start=[x,y]
direct=random.choice(['left','right','up','down'])
def __init__(self,i=10,fishs={}):
self.num=i
self.fishs={}
for i in range(self.num):
self.fishs['fish%d'%(i+1)]=[random.choice(range(0,11)),random.choice(range(0,11))] #定义每只鱼的初始位置
print(self.fishs)
def move(self):
for i in range(self.num):#建立一个字典,不同的鱼,对应不同的位置
[self.x,self.y]=self.fishs['fish%d'%(i+1)]
for step in range(1):#移动 步后,输出位置
self.direct=random.choice(['left','right','up','down'])
if self.direct=='right':
if self.x+1 > 10:
self.x=9
else:
self.x=self.x+1
elif self.direct=='leif':
if self.x-1 <0:
self.x=1
else:
self.x=self.x-1
elif self.direct=='up':
if self.y+1 > 10:
self.y=9
else:
self.y=self.y+1
else :
if self.y-1 <0:
self.y=1
else:
self.y=self.y-1
self.fishs['fish%d'%(i+1)]=[self.x,self.y]
t= Tutle()
f= Fish()
n=100#循环一百次,每次乌龟和鱼移动后都对比位置是否相同,若相同,减少一只鱼
while 1:
t.move()
f.move()
print(t.pos)
## print(f.fishs)
for compare in f.fishs:
if f.fishs[compare]==t.pos:
f.fishs.pop(compare)
print('编号为%s的鱼被吃掉了'%compare)
n+=2
n-=1
if n==0:
print('还剩%d只鱼'%(len(f.fishs)))
print('乌龟累死了,游戏结束')
break
if len(f.fishs)==0:
print('you win!')
在执行过程中,会报错
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\课堂练习\37-1.py", line 108, in <module>
for compare in f.fishs:
RuntimeError: dictionary changed size during iteration
我看网上的解决办法,说字典的遍历改成key
就是说
for compare in f.fishs:
if f.fishs[compare]==t.pos:
改成
for compare in f.fishs.keys():
if f.fishs[compare]==t.pos:
但报错还是一样的,是因为网上的方便是python2.7的么?还是其他地方还有问题?
|
|