Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Snake Lite by kurosawa4434
ACTION = ("L", "R", "F")
CHERRY = 'C'
TREE = 'T'
SNAKE_HEAD = '0'
SNAKE = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
EMPTY = "."
SIZE = 10
def snake(field_map):
cherrys = []
snake = {}
for i, row in enumerate(field_map):
for j, ch in enumerate(row):
if ch in SNAKE:
snake[ch] = (i, j)
if ch == CHERRY:
cherrys.append((i, j))
def route_search(start, goal):
dist = 1
find_target = False
next_cells = [goal]
guide_map = [['X' for _ in range(SIZE)] for _ in range(SIZE)]
guide_map[goal[0]][goal[1]] = 0
while next_cells or not find_target:
search_cells = next_cells[:]
next_cells = []
for p in search_cells:
py, px = p[0], p[1]
for sp in [(py - 1, px), (py + 1, px), (py, px + 1), (py, px - 1)]:
sy, sx = sp[0], sp[1]
if 0 <= sy < SIZE and 0 <= sx < SIZE:
if (sy, sx) == start:
find_target = True
break
ch = field_map[sy][sx]
if ch == TREE:
continue
if ch in SNAKE:
if int(ch) < len(snake) - 1:
continue
if guide_map[sy][sx] != 'X':
continue
guide_map[sy][sx] = dist
next_cells.append((sy, sx))
if find_target:
break
dist += 1
return guide_map, dist
guide_map1, dist1 = route_search(snake['0'], cherrys[0])
guide_map2, dist2 = route_search(snake['0'], cherrys[1])
guide_map = guide_map1 if dist1 < dist2 else guide_map2
def dir_evaluate(prev, cur, next):
py, px = prev
cy, cx = cur
y_def, x_def = cy - py, cx - px
dir_dic = {}
n, w, e, s = (cy - 1, cx), (cy, cx - 1), (cy, cx + 1), (cy + 1, cx)
if y_def == -1:
dir_dic = {n: 'F', e: 'R', w: 'L'}
elif y_def == 1:
dir_dic = {s: 'F', w: 'R', e: 'L'}
elif x_def == -1:
dir_dic = {w: 'F', n: 'R', s: 'L'}
elif x_def == 1:
dir_dic = {e: 'F', s: 'R', n: 'L'}
return dir_dic[next]
min_dist = 99
steps = ''
cur_cell = snake['0']
prev_cell = snake['1']
next_cell = ()
while min_dist > 0:
dr = ''
cy, cx = cur_cell
for np in [(cy - 1, cx), (cy + 1, cx), (cy, cx + 1), (cy, cx - 1)]:
ny, nx = np
if 0 <= ny < SIZE and 0 <= nx < SIZE:
num = guide_map[ny][nx]
if num != 'X' and num < min_dist:
next_cell = (ny, nx)
min_dist = num
dr = dir_evaluate(prev_cell, cur_cell, next_cell)
prev_cell = cur_cell
cur_cell = next_cell
steps += dr
return steps
July 18, 2016
Comments: