import collections
import random
class CheckerBoard(object):
"""
初始化棋盘
"""
def __init__(self, LEN):
self.LEN = LEN
self.position_has_gone = set()
def init_checkerboard(self):
position = []
for i in range(1, self.LEN + 1):
line = []
for j in range(1, self.LEN + 1):
line.append((i, j))
position.append(line)
return position
def init_hourse_position(self):
x = random.randint(1, self.LEN)
y = random.randint(1, self.LEN)
self.position_has_gone.add((x, y))
return (x, y)
def get_next_positions(self, init_position):
next_position = []
x, y = init_position
if x - 1 >= 1:
if y - 2 >= 1:
next_position.append((x - 1, y - 2))
if y + 2 <= self.LEN:
next_position.append((x - 1, y + 2))
if x - 2 >= 1:
if y - 1 >= 1:
next_position.append((x - 2, y - 1))
if y + 1 <= self.LEN:
next_position.append((x - 2, y + 1))
if x + 1 <= 8:
if y - 2 >= 1:
next_position.append((x + 1, y - 2))
if y + 2 <= self.LEN:
next_position.append((x + 1, y + 2))
if x + 2 <= self.LEN:
if y - 1 >= 1:
next_position.append((x + 2, y - 1))
if y + 1 <= self.LEN:
next_position.append((x + 2, y + 1))
return list(set(next_position) - self.position_has_gone) # 列表
def choose_next_position(self, next_positions, no_ok_position):
"""
贪心选择下一步的下一步选择方案最小的路
:param next_positions: 下一步可以选择的位置
:param house_position: 本身的位置
:return:下一步走的位置
"""
min_choice = 9
min_index = 0
if no_ok_position:
next_positions = list(set(next_positions) - set(no_ok_position))
if len(next_positions) == 0:
print('saaa')
return False
for index, position in enumerate(next_positions):
choice = len(self.get_next_positions(position))
if choice < min_choice:
min_choice = choice
min_index = index
self.position_has_gone.add(next_positions[min_index])
return next_positions[min_index]
LEN = 8
trace = [] # 有序字典,用于记录每步的位置
checkerboard_obj = CheckerBoard(LEN)
checkerboard = checkerboard_obj.init_checkerboard() # 获取棋盘所有格子
house_position = checkerboard_obj.init_hourse_position() # 获取马的初始位置
trace.append(house_position)
# 获取马的下一个可能位置
print('初始化位置', house_position)
while len(checkerboard_obj.position_has_gone) < LEN * LEN: # 当没有走完全部格子时,继续走下一步直至走完
next_positions = checkerboard_obj.get_next_positions(house_position)
next_step = checkerboard_obj.choose_next_position(next_positions, no_ok_position=None)
if next_step == False:
break
else:
house_position = next_step
trace.append(next_step)
print(trace)
showList = []
for i in range(8):
line = []
for j in range(8):
line.append(j)
showList.append(line)
for index, item in enumerate(trace):
showList[item[0] - 1][item[1] - 1] = index + 1
for item in showList:
print(item)