|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
关于贪吃蛇的优化寻路实现有没有好的思路,我很想它能贴着蛇身走,避免过早把自己困死,
却没有很好地思路,代码我发出来,有兴趣大家可以试着玩下,不需要什么模块,然后提下
寻路优化建议
- import random
- import time
- class snake():
-
- def __init__(self,ite):
- self.ite = ite
- self.snk = ['o','o','O']
- self.way = [[5,4],[5,5],[5,6]]
- self.tail = [0,0]
- self.ite[5][4],self.ite[5][5],self.ite[5][6]='o','o','O'
-
- def move(self,a,b):
- self.way.append([a,b])
- self.tail = self.way.pop(0)
- for c,(i,j) in enumerate(self.way):
- self.ite[i][j] = self.snk[c]
- self.ite[self.tail[0]][self.tail[1]] = ' '
- return self.ite
- class food():
- def __init__(self,ite):
- self.ite = ite
- def prod(self,way):
- while True:
- a,b = random.randint(0,9),random.randint(0,9)
- if [a,b] not in way:
- self.ite[a][b] = 'Q'
- break
- return [a,b]
-
- def show(ite):
- #print(' ','--'*10)
- for i in ite:
- print('|',end='')
- for j in i:
- print(j,end=' ')
- print('|')
- #print(' ','--'*10)
- print()
- def find(c,d): #寻路函数,每一步找的都是最靠近食物的点,然后横竖上,哪一方距离
- f = [] #离远,走哪一边,但这个优化很不理想。
- [a,b] = visit.pop(0)
- if a == c and b == d:
- return True
- cot = 0
- for ste in step:
- a1 = a + ste[0]
- b1 = b + ste[1]
- if 0<=a1<10 and 0<=b1<10 and [a1,b1] not in S.way:
- cot = abs(a1-c)+abs(b1-d)
- f.append([cot,[a1,b1],ste])
- cot = min(f)[0]
- for i in f:
- if i[0] == cot:
- if abs(a-c) >= abs(b-d) and i[2][1] == 0:
- visit.append(i[1])
- temp = i[1]
- break
- elif abs(b-d) > abs(a-c) and i[2][0] == 0:
- visit.append(i[1])
- temp = i[1]
- break
- if not len(visit):
- visit.append(min(f)[1])
- temp=min(f)[1]
- S.move(temp[0],temp[1])
- if temp[0] == c and temp[1] == d:
- S.snk.insert(0,'o')
- S.way.insert(0,S.tail)
- ite[S.tail[0]][S.tail[1]] = 'o'
- return 0
- show(ite)
-
- ite = [[' ']*10 for i in range(10)]
- S = snake(ite)
- F = food(ite)
- step = [(1,0),(-1,0),(0,1),(0,-1)]
- a,b = F.prod(S.way)
- visit = [[5,6]]
- right = {}
- while True:
- if [a,b] == S.way[-1] :
- a,b = F.prod(S.way)
- show(ite)
- visit = [S.way[-1]]
- while True:
- if find(a,b):
- break
- time.sleep(0.5)
复制代码
|
|