天天看点

Playground 学习编程1-逻辑运算符

第五章|逻辑运算符

    • 1. 使用“非”运算符
    • 2. 非之螺旋
    • 3. 检查这个与那个
    • 4. 检查这个或那个
    • 5. 逻辑迷宫

1. 使用“非”运算符

func turnAround() {
    turnLeft()
    turnLeft()
}
for i in 1 ... 4 {
    moveForward()
    if !isOnGem {
        turnLeft()
        moveForward()
        moveForward()
        collectGem()
        turnAround()
        moveForward()
        moveForward()
        turnLeft()
    } else{
        collectGem()
    }
}
           

2. 非之螺旋

for i in 1 ... 16 {
    if !isBlocked {
        moveForward()
    } else{
        turnLeft()
    }
}
toggleSwitch()
           

3. 检查这个与那个

func turnAround() {
    turnLeft()
    turnLeft()
}
for i in 1 ... 7 {
    moveForward()
    if isOnGem && isBlockedLeft {
        collectGem()
        turnRight()
        moveForward()
        moveForward()
        toggleSwitch()
        turnAround()
        moveForward()
        moveForward()
        turnRight()
    } else if isOnGem {
        collectGem()
    }
}
           

4. 检查这个或那个

func runNext(){
    for i in 1 ... 12 {
        if isBlocked || isBlockedLeft {
            turnRight()
            moveForward()
        } else {
            moveForward()
        }
    }
}
runNext()
collectGem()
           

5. 逻辑迷宫

func turnAround(){
    turnLeft()
    turnLeft()
}
func oneNext(){
    turnRight()
    moveForward()
    moveForward()
    collectGem()
    turnAround()
    moveForward()
    moveForward()
    turnRight()
}
for i in 1 ... 8 {
    moveForward()
    if isOnGem && isOnClosedSwitch {
        collectGem()
        toggleSwitch()
        oneNext()
    }else if isOnClosedSwitch {
        toggleSwitch()
        turnLeft()
    }else if isOnGem{
        collectGem()
    }
}