W1165 Karel Introduction

From Coder Merlin
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
CoderMerlin™ Karel

Prerequisites[edit]

Background[edit]

Richard Pattis
Karel the Robot
Karel Čapek

 Coder Merlin™ Karel , also known as "that little blue bot," is strongly inspired by Richard Pattis's book, Karel The Robot: A Gentle Introduction to the Art of Programming, written during his studies at Stanford.[1][2] Richard Pattis teaches at the University of California, Irvine. Pattis chose the name Karel in honor of the Czech playwright Karel Čapek, who introduced the word robot in his 1921 play R.U.R.

Eric Roberts, Department of Computer Science, Stanford University, September 2005:

In the 1970s, a Stanford graduate student named Rich Pattis decided that it would be easier to teach the fundamentals of programming if students could somehow learn the basic ideas in a simple environment free from the complexities that characterize most programming languages. Drawing inspiration from the success of Seymour Papert's LOGO project at MIT, Rich designed an introductory programming environment in which students teach a robot to solve simple problems. [3]

Karel is a very simple robot living in a very simple world. Programming Karel is accomplished by specifying a series of simple instructions. Karel initially understands only a very few instructions; but over time, you can expand the vocabulary by defining functions and enhancing Karel's abilities.

All instructions issued to Karel must be very precise and unambiguous, a key requirement of well-written programs. The programs themselves must obey a set of syntactic rules that define which commands (and the ordering of those commands) are acceptable. These rules define a programming language, such as the Swift programming language that we've been using. The details of the subset of instructions that Karel understands are very easy to master, enabling us to focus on problem solving.

These same steps can be used to help us solve any task that can be expressed as an algorithm:

  1. Understand the question
  2. Develop an algorithm to answer the question
  3. Express the algorithm as a flowchart
  4. Translate the algorithm to code


It is problem solving which is the focus and essence of computer programming.

Introduction (Welcome to my World)[edit]

Streets, Avenues, and Corners[edit]

Figure 1

Karel lives in a city with green avenues running vertically north-south and blue streets running horizontally east-west. The intersection of a street with an avenue is called a corner. Karel can be positioned only on a corner and must point in one of the four cardinal directions. Karel always points with his hat, so in Figure 1 Karel is positioned at (avenue: 1, street: 1) and is facing north. Note that worlds may be of various sizes depending on the challenge that needs to be solved.

Beepers[edit]

Figure 2

Corners may have zero or more beepers present, indicated by a yellow/red rotating beacon. The number in the center of the beacon indicates the number of beepers present on the corner. In Rich Pattis's book, beepers are "plastic cones that emit a quiet beeping noise." Karel can detect a beeper only if it is on the same corner. Karel carries with him a hidden beeper bag; the number on the front of Karel indicates how many beepers are in the bag (Figure 3).

Figure 3


Walls[edit]

Figure 4

Walls may be present between streets and avenues and serve as a barrier to Karel; unable to pass through them, Karel must go around them. Note that the presence of walls is implied around the boundary of the city.

Challenges[edit]

 Coder Merlin™ Karel  is integrated into  Merlin Mission Manager  but because it is built on top of IGIS[4], a few additional steps are necessary to complete Karel challenges.

Getting Started[edit]

Karel missions take a similar form to other missions and the usage of the  Merlin Mission Manager  is similar. You'll need to follow the same paradigm for accepting and preparing missions and challenges as that of previous missions and challenges. However, the following difference apply:

File Structure[edit]

The challenges require using framework (a series of libraries). While most of this is transparent, you'll notice several more files in the challenge directory, including:

  • ActionPlan.swift - SHOULD be MODIFIED to develop an effective solution to the challenge.
  • 🚫 dylib.manifest - Generally SHOULD NOT be altered. It's responsible for providing a list of required dynamic libraries and their versions.
  • instructions.txt - SHOULD be READ and closely followed before beginning the challenge.
  • 🚫 main.swift - Generally SHOULD NOT be altered. It's responsible for using the Karel framework to create the world.
  • 🚫 make.sh - Generally SHOULD NOT be altered. It contains the instructions necessary to build the project.
  • 🚫 Package.swift - Generally SHOULD NOT be altered. It contains a description of the package to be built.
  • 🚫 run.sh - Generally SHOULD NOT be altered. It contains the instructions necessary to run the project.
  • 🚫 WorldPlanner.swift - Generally SHOULD NOT be altered. It contains a description of the world that Karel must navigate along with the goal of an effective solution.

Syntax Highlighting[edit]

Syntax highlighting and other Language Services will perform normally in emacs but require additional setup after preparing the challenge. These steps are required only once per challenge.

  1. Enter the challenge directory
  2. Generate a new emacs configuration file

john-williams@codermerlin:~/Merlin...$ dylibEmacs

  1. Open ActionPlan.swift in emacs
  2. A message appears at the bottom of emacs. When warned about "The local variables list in /home/john-williams/Merlin/...contains values that might not be safe (*)" press ! to apply the local variable list and permanently mark the values as safe.
  3. A message appears at the bottom of emacs:

ActionPlan.swift is not part of any project. Select action:



i==>Import project root ~/Merlin/.../.

I==>Import project by selecting root directory interactively.

d==>Do not ask again for the current project by adding ~/Merlin/.../ to lsp-session-folders-blacklist.

D==>Do not ask again for the current project by selecting ignore path interactively.

n=>Do nothing: ask again when opening other files from the current project.

Press I (capital 'I') and select the directory for this challenge in which Package.swift is located.

Building[edit]

Like most challenges, the project can be built by issuing a build command on the console:

john-williams@codermerlin:~/Merlin...$ build

Alternatively, you can use F5 b from within emacs.

Running[edit]

Like most challenges, the project can be run by issuing a run command on the console:

john-williams@codermerlin:~/Merlin...$ run

Alternatively, you can use F5 r from within emacs.

Hint.pngHelpful Hint

To terminate a running program within emacs:

  1. Switch to the window in which the program is running using CONTROL-x o, repeating as many times as is necessary. (The window is titled "*Async Shell Command*".)
  2. Terminate the running program with CONTROL-c CONTROL-c

Viewing[edit]

Unlike most challenges, very little information is displayed to the console. Rather, a browser must be opened to view the output.

Hint.pngHelpful Hint

Each user has his or her own, dedicated URL for viewing Igis programs. For example, John Williams' URL is: https://www.codermerlin.com/igis/john-williams/

Be sure to change your URL in accordance with your user name. Of course, you'll be able to view only your program while it is running.

Simulation Control[edit]

Controlling Karel occurs by programming the Action Plan (described below). However, the following keys might be helpful while running the simulation:

Key Sequence Purpose
Space Toggles between the current and goal views
f Causes the animation to run faster
s Causes the animation to run slower
Hint.pngHelpful Hint
The simulation can be restarted by refreshing the browser.

The Goal[edit]

Each challenge has a target goal state that can be viewed by toggling to the goal view. The goal view appears with a gold background. The first step of solving any Karel challenge begins by running an empty Action Plan, which shows the initial state and then toggling to the goal state. The objective is to formulate an action plan to alter the world from the initial state to the goal state.

Initial (current) view
Goal view


In the above case, we can see that the initial view has Karel at (avenue: 1, street: 1) with one beeper (indicated as a "1" on his body). After achieving the goal, Karel is at (avenue: 3, street: 3) after having dropped his beeper at (avenue: 2, street: 3) along the way.

Action Plan[edit]

The Action Plan is in the file ActionPlan.swift. Initially, the file is nearly empty:

import MerlinKarel

class ActionPlan: KarelExecutor {

    // Declare functions here:

    override func run() {
        // Insert your code here:
    }

}
  • Line 1 informs the Swift compiler that we'll be relying on functionality imported from the MerlinKarel library. This line should not be changed.
  • Line 3 begins the definition of a new class descending from a KarelExecutor. We'll learn more about classes later. This line should not be changed.
  • Line 7 begins the definition of a required function called run. You'll insert your code within the body of this function. Any other functions can be inserted below line 5.

Action Instructions[edit]

When shipped from the factory,  Coder Merlin™ Karel  understands the following action instructions:

Instruction Purpose
move() moves Karel forward one corner in the direction he is facing.

⚠️ If Karel is unable to move forward (because he is blocked by a wall or at the world's edge) the program terminates with an error.

turnLeft() turns Karel counterclockwise by 90°
pickUpBeeper() Karel picks up one beeper from the corner on which he is located.

⚠️ If Karel is unable to pick up a beeper because none are present on the corner, the program terminates with an error.

putDownBeeper() Karel puts down one beeper from his beeper bag on the corner on which he is located.

⚠️ If Karel is unable to put down a beeper because none are present in his beeper bag, the program terminates with an error.

Sensor Instructions[edit]

When shipped from the factory, Karel understands the following sensor instructions:

Instruction Purpose
isBeeperHere() Returns true iff a beeper is present on the corner on which Karel is located, otherwise returns false.
anyBeepersInBag() Returns true iff at least one beeper is present in Karel's bag, otherwise returns false.
isFacingNorth() Returns true iff Karel is facing north, otherwise returns false.
isFacingEast() Returns true iff Karel is facing east, otherwise returns false.
isFacingSouth() Returns true iff Karel is facing south, otherwise returns false.
isFacingWest() Returns true iff Karel is facing west, otherwise returns false.
isFrontClear() Returns true iff Karel is clear (not blocked) to proceed forward, otherwise returns false.
isLeftClear() Returns true iff Karel is clear (not blocked) to proceed to the left, otherwise returns false.
isRightClear() Returns true iff Karel is clear (not blocked) to proceed to the right, otherwise returns false.
isGoalLocation() Returns true iff Karel is at the goal location, otherwise returns false.

Function Block Opportunities[edit]

Function Block

As you develop a plan to achieve the goal, search for Function Block Opportunities.

  • Functions enable us to avoid the repetition of code, i.e., code that would otherwise need to appear more than once should be contained within a function.
  • Functions allow us to divide complicated tasks into sub-tasks that can be thought about separately.[5]
  • Properly parameterizing functions can enable the same function to be invoked from multiple sites with appropriate arguments.
  • Functions should perform a single, specific, coherent task completely.

Function blocks are represented by a rectangle with a vertical line on either side.

Function Block Example[edit]

Invocation of turnAround()
Invocation of turnAround()

An example of a function block useful for Karel would be a function to turn Karel around 180°. The invocation of the function would appear in our flowchart as indicated in the figure on the left.

Implementing such a function is indicated in the figure on the right.

Testing[edit]

After the Action Plan has been completed and tested using the run command (or equivalent), you may test it using the  Merlin Mission Manager  in the same manner as other challenges:

john-williams@codermerlin:~/Merlin...$ merlin test

Note, however, that to complete the test, you must open a browser to your Igis page.

CautionWarnIcon.png

The  Merlin Mission Manager  can alter the parameters of a test in many ways. Before submitting your work, be certain that you have closely followed the instructions in instructions.txt.

Submission[edit]

After you are certain that the Action Plan has been tested successfully, you may submit it using the  Merlin Mission Manager  in the same manner as other challenges:

john-williams@codermerlin:~/Merlin...$ merlin submit


Note, however, that to complete the submission, you must open a browser to your Igis page.

Hint.pngHelpful Hint

The application will terminate automatically during a  Merlin Mission Manager  run when the run() function completes. To terminate the application when it is being executed outside of the  Merlin Mission Manager , press CONTROL-c.

Key Concepts[edit]

Key ConceptsKeyConceptsIcon.png
  • Karel was created by Richard Pattis during his studies at Stanford.
  • Karel was named in honor of the Czech playwright Karel Čapek, who introduced the word robot in his 1921 play R.U.R.
  • Programming Karel is accomplished by specifying a series of simple instructions. All instructions issued to Karel must be very precise and unambiguous.
  • Programs themselves must obey a set of syntactic rules that define which commands (and the ordering of those commands) are acceptable.
  • Problem solving is the focus and essence of computer programming.
  • Karel lives in a city with green avenues running vertically north-south and blue streets running horizontally east-west.
  • The intersection of a street with an avenue is called a corner.
  • Corners may have zero or more beepers present.
  • Karel carries with him a hidden beeper bag.
  • Walls may be present between streets and avenues and serve as a barrier.
  • Karel understands the following action instructions:
    • move()
    • turnLeft()
    • pickUpBeeper()
    • putDownBeeper()
  • Karel understands the following sensor instructions:
    • isBeeperHere()
    • anyBeepersInBag()
    • isFacingNorth()
    • isFacingEast()
    • isFacingSouth()
    • isFacingWest()
    • isFrontClear()
    • isLeftClear()
    • isRightClear()
    • isGoalLocation()

Exercises[edit]

Hint.pngHelpful Hint

Throughout these exercises, your ActionPlan.swift file will be carried forward from one challenge to the next within a mission. It is in your best interest to define useful functions in this file enabling you to leverage them in subsequent challenges. This way, you'll build a library of functions that you're able to reuse; you're essentially providing Karel with additional capabilities.

Note that when you begin a new mission, you'll need to manually copy your ActionPlan.swift file from the prior mission.


CautionWarnIcon.png

Igis projects might require substantial disk space. As a consequence, it's wise to occasionally execute:

john-williams@codermerlin:~/Merlin...$ merlin-clean


This frees temporary space for building and running your Igis projects. It does NOT delete any of your source files.


ExercisesExercisesIcon.png
  1.  M1165-10  Complete  Merlin Mission Manager  Mission M1165-10.
  2.  M1165-11  Complete  Merlin Mission Manager  Mission M1165-11.

References[edit]