# 創造世界

## 繞 S 形走完全世界

![](/files/-M5gL-kj96YLSFMmJoAR)

上面是一個空白的 12 x 12 的世界，下面的程式碼會放一個 [Actor](/ios/swift-playgrounds/learn-to-code-2/types/actor.md) 在原點，並讓他向東走、繞 S 形走完全世界。

{% tabs %}
{% tab title="main" %}

```swift
// GridWorld
let theWorld = world

// 新增角色放到(0,0)、面向東方
let actor = Actor(0,0)

// 判斷角色是否已經走到世界盡頭
var isOver = false

// 當角色還沒到世界盡頭，就繼續走
while !isOver {
    actor.navigate(onMove: { 
        // 往前一步要做的動作放這裡
    }) { 
        // onExit：
        // 到世界盡頭要做的動作放這裡
        isOver = true
        actor.danceLikeNoOneIsWatching()
    }
}
```

{% endtab %}

{% tab title="Actor" %}

```swift
extension Actor {
    
    // 新增角色放到 (x,y)、預設面向東方。
    convenience init(_ x: Int, _ y: Int, facing dir: Direction = .east){
        self.init()
        theWorld.place(self, facing: dir, at: Coordinate(column: x, row: y))
    }
    
    typealias Handler = () -> Void
    
    // 讓角色從原點向東「走 S 形的路線」到達終點。
    func navigate(onMove:Handler, onExit:Handler) {
        
        if !isBlocked {   // 如果前面沒擋住，就往前走
            moveForward()
            onMove()
        } else {          // 否則就轉彎
            
            // 先判斷要往哪邊轉、轉彎時要做什麼動作
            let turn = heading == .east ? turnLeft : turnRight   // 向東走時轉左邊，否則轉右邊
            let act  = heading == .east ? turnUp   : headScratch // 向東走時裝興奮，否則抓抓頭
            
            turn()  // 轉彎
            
            if !isBlocked { // 如果還沒到世界盡頭，就往前走再轉彎
                act()
                moveForward()
                onMove()
                turn()
            } else {        // 不然就是已經到了盡頭，就做到了盡頭該做的事。
                onExit()
            }
            
        }//end: if
        
    }//end: naviagate()
}
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/ios/swift-playgrounds/learn-to-code-2/pages/world-creation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
