Swift — Crank Up and Down

Objective: Initialize two monsters, then have one collect all gems with the other moving platforms up and down as needed.
E3D759B1-6AD6-4708-875A-D00949294A2F.png

My assumption was to start with top left gems and then move down to lower level before finishing with far right top level. A bit heavy handed when it came to running the code — do this, then do that — with far less func’s than I’d preferred.

I suspected there was a better way, and this solution proves it. By completing the entire top level first and then moving down to complete the lower level it’s possible to complete with 30% less code!

My solution

let expert = Expert()
let character = Character()
func turnLock(up:Bool, turns: Int) {
if up == true {
for i in 1…turns {
expert.turnLockUp()
}
} else {
for i in 1…turns {
expert.turnLockDown()
}
}
expert.turnRight()
}
func getGem(move: Int) {
for i in 1…move {
character.moveForward()
}
if character.isOnGem {
character.collectGem()
}
character.turnRight()
character.turnRight()
}
func moveFwd(move: Int) {
for i in 1…move {
character.moveForward()
}
character.turnLeft()
}
getGem(move: 2)
character.turnLeft()
turnLock(up: true, turns: 4)
getGem(move: 2)
moveFwd(move: 1)
character.turnRight()
character.turnRight()
expert.turnLeft()
turnLock(up: false, turns: 3)
getGem(move: 1)
moveFwd(move: 2)
turnLock(up: true, turns: 1)
getGem(move: 2)
moveFwd(move: 2)
moveFwd(move: 2)
turnLock(up: true, turns: 1)
getGem(move: 2)
moveFwd(move: 2)
turnLock(up: true, turns: 1)
getGem(move: 2)
moveFwd(move: 1)
expert.turnLeft()
turnLock(up: true, turns: 3)
moveFwd(move: 1)
character.turnLeft()
getGem(move: 2)

Jyjy Game solution

let expert = Expert()
let character = Character()
var gemCounter = 0
func checkGem() {
if character.isOnGem {
character.collectGem()
gemCounter += 1
}
}
for i in 1…4 {
expert.turnLockUp(up: true, numberOfTimes: 4)
expert.turnLeft()
}
while gemCounter < 3 {
character.move(distance: 2)
if !character.isBlockedRight {
character.turnRight()
}
checkGem()
}
character.moveForward()
for i in 1…4 {
expert.turnLock(up: false, numberOfTimes: 3)
expert.turnLeft()
}
character.turnLeft()
character.moveForward()
checkGem()
while gemCounter < 7 {
if !character.isBlockedRight {
character.turnRight()
} else if character.isBlocked {
character.turnLeft()
character.turnLeft()
}
character.move(distance: 2)
checkGem()
}

 
12
Kudos
 
12
Kudos

Now read this

an unforgettable morning

Have you ever awoke before dawn, feeling refreshed and full of energy? That was my beginning; and since my girls were still fast asleep, I had a couple hours to myself. (What to do?!) Not wanting to waste it, I quickly checked my... Continue →