Sponsored

Collapse

Announcement

Collapse
No announcement yet.

Build a Loop - Swift Playgrounds

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Build a Loop - Swift Playgrounds

    The challenge of this level is to build your world and collect a randomly determined number of gems, represented by the totalGems constant.

    In this puzzle, a random number of gems is generated each time you run your code. Your goal is to modify the puzzle world so you can effectively navigate around it, picking up gems until you've collected all of them. The number of gems is determined by a value stored in the constant totalGems.

    Keep track of the number of gems collected to figure out when to stop running your code.

    Click image for larger version

Name:	Screen Shot 2017-01-05 at 5.47.59 PM.png
Views:	1
Size:	169.2 KB
ID:	1821

    Hint: First you'll need to build out part of the puzzle world so that you can reach the locations where the gems are generated. Create and place an instance of your character to move around the puzzle and collect gems. Remember, there are many ways to solve this puzzle, but you should first think through a solution that might work, and then code and test that solution.

    Code:
    let totalGems = randomNumberOfGems
    var gemCounter = 0
    let character = Character()
    
    world.place(Block(), atColumn: 3, row: 3)
    world.place(Block(), atColumn: 0, row: 2)
    world.place(character, facing: west, atColumn: 2, row: 3)
    
    while gemCounter < totalGems {
     if character.isOnGem {
      character.collectGem()
      gemCounter += 1
     }
     character.moveForward()
    }
    Masterful! Now it's time to start modifying every part of the puzzle world. Are you ready?

    The next lesson, which is the final lesson in World Building is "A Puzzle of Your Own".

  • #2
     

    Comment


    • #3
      Code:
      var gemCounter = 0
      
      let character = Character()
      
      
      
      
      world.place(Block(), atColumn: 3, row: 3)
      
      world.place(Block(), atColumn: 0, row: 2)
      
      world.place(character, facing: east, atColumn: 2, row: 3)
      
      
      
      
      while gemCounter < totalGems {
      
          if character.isOnGem {
      
              character.collectGem()
      
              gemCounter += 1
      
          }
      
          character.moveForward()
      
          if character.isBlocked && character.isBlockedLeft && !character.isBlockedRight {
      
              character.turnRight()
      
          } else if character.isBlocked && character.isBlockedRight && character.isBlockedLeft {
      
              character.turnLeft();character.turnLeft()
      
          } else if character.isBlocked && character.isBlockedRight && !character.isBlockedLeft {
      
              character.turnLeft()
      
          }
      
      }

      Comment

      Working...
      X