跑毒的烏龜-0 : 隨機漫步

跑毒的烏龜-0 : 隨機漫步

故事背景:

有一隻烏龜,它被困在一個毒圈中,毒圈的輪廓可以是各種形狀,如果烏龜長期滯留在毒圈中會掛掉,所以我們要幫助它儘快脫離毒圈.烏龜只需走出毒圈輪廓的邊緣即可逃出生天.烏龜可以在毒圈中的任意不靠近邊緣的位置開始,每次可以移動一步,每次都可以朝着任意方向移動,每次也可以改變步長,也可以從始至終都朝着同一個方向.一旦離開毒圈,就可以停下.但是在一個陌生的環境下,烏龜事先並不知道,怎麼才能逃離,所以只能隨機漫步的遊走.
在這裏插入圖片描述
上圖中是烏龜可能的遊走路線, 黑色的爲毒圈邊界.

毒圈邊界的大小

  • x : [-35, 35]
  • y : [-35, 35]

烏龜隨機漫步模擬

import turtle
import pickle
import seaborn as sns
from tqdm import tqdm
import matplotlib.pyplot as plt
from random import randint,choice
%matplotlib inline
def escaped(position):
    x = int(position[0])
    y = int(position[1])
    return x <-35 or x > 35 or y < -35 or y > 35
def random_walk(angle=90, step_size=1, direction='left', random_flag=False):
    L = []   # Locations
    init_position = (randint(-5,5), randint(-5, 5))
    t = turtle.Turtle()
    t.penup()
    t.goto(init_position[0], init_position[1])
    t.pendown()
    L.append([init_position[0], init_position[1], escaped(init_position)])
    while not escaped(t.position()):
        if random_flag:
            #angle = choice([0,30, 45, 60, 90, 120, 180])
            angle = randint(0, 361)
            step_size = randint(1, 21)
            direction = choice(['left','right'])
        if random_flag==False:
            step_size = step_size+1
        t.forward(step_size)
        if direction == 'left':
            t.left(angle)
        else:
            t.right(angle)
        position = t.position()
        L.append([position[0], position[1], escaped(position)])
    t.clear()
    return L
def plot_trace(L): 
    x = [p[0] for p in L]
    y = [p[1] for p in L]
    plt.figure(figsize=(10, 7))
    plt.plot(x, y)
    plt.ylim(-60, 60)
    plt.xlim(-60, 60)
    plt.plot([-35, 35, 35, -35, -35], [35, 35, -35, -35, 35])
    plt.text(36, -36, 'Poison ring',fontsize=20)
    plt.scatter(x[0], y[0], c='green', s = 55, label='start')
    plt.scatter(x[-1], y[-1], c='red', s = 55, label='end')
    plt.grid()
    plt.legend()
沿着一條直線

這似乎是最短的逃離路線
在這裏插入圖片描述

90度螺旋路線

在這裏插入圖片描述

30度螺旋路線

在這裏插入圖片描述

45度螺旋路線

在這裏插入圖片描述

60度螺旋路線

在這裏插入圖片描述

120度螺旋路線

在這裏插入圖片描述

180度旋轉

在這裏插入圖片描述

隨機遊走200次

並保存隨機探索的路徑數據

for i in tqdm(range(1, 201)):
    L = random_walk(random_flag=True)
    filepath = './locations/random_%d.L'%i
    pickle.dump(L, open(filepath, 'wb'))
100%|█████████████████████████████████████████| 200/200 [12:06<00:00,  3.35s/it]

隨機漫步可視化1
在這裏插入圖片描述
隨機漫步可視化2
在這裏插入圖片描述
隨機漫步可視化3
在這裏插入圖片描述

200次隨機漫步的結果統計

烏龜跑毒圈的步數分佈情況

在這裏插入圖片描述

隨機漫步路徑

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章