我正在寫迷宮發生器,在某些時候我必須選擇一個單元格的隨機未訪問鄰居。第一個想法是枚舉左邊= 0,頂部= 1,右邊= 2,底部= 3的鄰居,並使用rand()%4生成隨機數並選擇合適的單元格。然而,並非所有的細胞設有4個鄰居,讓我不得不寫下面的代碼:行動決策模式
Cell* getRandomNeighbour(const Maze* const maze, const Cell* const currentCell) {
int randomNumb = rand() % 4;
int timer = 1;
while(timer > 0) {
if (randomNumb == 0 && currentCell->x < maze->width-1 && maze->map[currentCell->y][currentCell->x+1].isUnvisited)
return &maze->map[currentCell->y][currentCell->x+1];
if (randomNumb == 1 && currentCell->x > 0 && maze->map[currentCell->y][currentCell->x-1].isUnvisited)
return &maze->map[currentCell->y][currentCell->x-1];
if (randomNumb == 2 && currentCell->y < maze->height-1 && maze->map[currentCell->y+1][currentCell->x].isUnvisited)
return &maze->map[currentCell->y+1][currentCell->x];
if (randomNumb == 3 && currentCell->y > 0 && maze->map[currentCell->y-1][currentCell->x].isUnvisited)
return &maze->map[currentCell->y-1][currentCell->x];
timer--;
randomNumb = rand() % 4;
}
if (currentCell->x < maze->width-1 && maze->map[currentCell->y][currentCell->x+1].isUnvisited)
return &maze->map[currentCell->y][currentCell->x+1];
if (currentCell->x > 0 && maze->map[currentCell->y][currentCell->x-1].isUnvisited)
return &maze->map[currentCell->y][currentCell->x-1];
if (currentCell->y < maze->height-1 && maze->map[currentCell->y+1][currentCell->x].isUnvisited)
return &maze->map[currentCell->y+1][currentCell->x];
if (currentCell->y > 0 && maze->map[currentCell->y-1][currentCell->x].isUnvisited)
return &maze->map[currentCell->y-1][currentCell->x];
return NULL;
}
所以,如果在10次迭代沒有選擇正確的決定,它將被強力回升。這種方法似乎很好,因爲變量變量定時器改變了迷宮的複雜度:更少的定時器是更直接的迷宮。不過,如果我唯一的目的是完全隨機生成迷宮,則需要很長的執行時間,並且看起來有點難看。有沒有任何模式(使用C語言)或重構的方式,可以使我無需長時間切換和大量if-else結構來處理這種情況?
你問一個算法。設計模式完全不同。 – Olaf
爲什麼不把合法的鄰居推到堆棧(帶有深度計數器的數組)上,並隨機選取其中一個元素,並將深度作爲模數。 – pat
@pat謝謝,這聽起來像是一個很好的解決方案,我會嘗試。 – NikitaRock