logic with karel - iste · ic with karel introduction to coding and logical reasoning karel is a...

10
LO GIC WITH KAREL INTRODUCTION TO CODING AND LOGICAL REASONING Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound simple, but Karel teaches all kinds of sophisticated logical structures. The 24 problems in this workshop start with basic movements, then dive into scripted commands, repeat loops, conditions, functions, and so much more. As you go through the exercises, think about how these logical structures could be used to solve real world problems. Don’t be surprised if you start to see the world as repeated patterns, recursive calls, and logical operators! GETTING STARTED You will need a device connected to the Internet to do these problems. Most devices will work, including PC’s, Macs, Chromebooks, and tablets. Your phone will not, as the screen is too small to accommodate the Karel viewer. The viewer works in Chrome, Edge, Firefox, and Safari. The web address for the workshop is https://nclab.com/karel-workshop/ You will see the 24 levels laid out as tiles. Click on a tile and the viewer will open. You may see a screen or two before the working screen, explaining a concept or adding to the storyline. The viewer has two sections. Type your code on the left side, and view the results on the right. BASIC INSTRUCTIONS Karel syntax is simple. However, there are a few rules. o Words are lower case and must be spelled correctly. Keywords will change color when typed correctly. o All commands are written on separate lines. o Indent two spaces for the body of a loop. Press the gold arrow to run the program. To speed up Karel’s movement, go to Settings and change the speed to Fast. You can step through the code line by line by pressing the black arrow. Press the black circle with the rotating arrow to reset the maze. Press the red and white target to use the code template. This will show the code structure. Don’t worry about making mistakes. The program will suggest errors and fixes, and nothing will explode. Have fun! If you get stuck, the answers are included in this handout.

Upload: others

Post on 17-Mar-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: LOGIC WITH KAREL - ISTE · IC WITH KAREL INTRODUCTION TO CODING AND LOGICAL REASONING Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound

LOGIC WITH KAREL

INTRODUCTION TO CODING AND LOGICAL REASONING

Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound simple, but Karel teaches all kinds

of sophisticated logical structures. The 24 problems in this workshop start with basic movements, then dive into scripted commands,

repeat loops, conditions, functions, and so much more. As you go through the exercises, think about how these logical structures

could be used to solve real world problems. Don’t be surprised if you start to see the world as repeated patterns, recursive calls, and

logical operators!

GETTING STARTED

You will need a device connected to the Internet to do these problems. Most devices will work, including PC’s, Macs, Chromebooks,

and tablets. Your phone will not, as the screen is too small to accommodate the Karel viewer.

The viewer works in Chrome, Edge, Firefox, and Safari. The web address for the workshop is https://nclab.com/karel-workshop/

You will see the 24 levels laid out as tiles. Click on a tile and the viewer will open.

You may see a screen or two before the working screen, explaining a concept or adding to the storyline.

The viewer has two sections. Type your code on the left side, and view the results on the right.

BASIC INSTRUCTIONS

• Karel syntax is simple. However, there are a few rules.

o Words are lower case and must be spelled correctly. Keywords will change color when typed correctly.

o All commands are written on separate lines.

o Indent two spaces for the body of a loop.

• Press the gold arrow to run the program. To speed up Karel’s movement, go to Settings and change the speed to Fast.

• You can step through the code line by line by pressing the black arrow.

• Press the black circle with the rotating arrow to reset the maze.

• Press the red and white target to use the code template. This will show the code structure.

• Don’t worry about making mistakes. The program will suggest errors and fixes, and nothing will explode.

• Have fun! If you get stuck, the answers are included in this handout.

Page 2: LOGIC WITH KAREL - ISTE · IC WITH KAREL INTRODUCTION TO CODING AND LOGICAL REASONING Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound

THE 24 PROBLEMS

1 - MANUAL MODE

Before we start scripting, practice navigating the maze in Manual Mode, either by

pressing the icons, or by using the arrow keys for movement, SHIFT for get, and CTRL

for put

go Karel moves one square forward.

left Karel turns 90 ° to his left.

right Karel turns 90 ° to his right.

get Karel picks up an object.

put Karel places an object.

2 – SIMPLE COMMANDS

Practice the same basic commands by typing them, one command per line.

go

right

go

get

left

left

go

go

put

right

right

go

left

go

3 – REPEAT LOOP I

Any set of commands which needs to be repeated can be written as a loop, starting

with the number of times the commands are to be repeated. The body of the loop is

indented 2 spaces.

repeat 3 go get go go put go

Page 3: LOGIC WITH KAREL - ISTE · IC WITH KAREL INTRODUCTION TO CODING AND LOGICAL REASONING Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound

4 – REPEAT LOOP II

In this problem, repeat loops are embedded in a longer program. There are several solutions. This one has only 15 lines of code and

includes a nested loop (see Problem 5).

repeat 3

go

right

left

repeat 10

left

get

repeat 2

go

right

go

left

repeat 3

go

right

5 – NESTED LOOPS

Nested loops are used for patterns within patterns. Notice how indentation shows

the relationships.

repeat 3

repeat 4

go

get

left

go

right

6 – CONDITIONS

Conditions create flexibility in a program. Karel is no longer restricted to fixed

patterns, but can respond to his environment. Karel has a large library of defined

objects: in this case, a spider.

repeat 10

go

if spider

get

left

go

right

Page 4: LOGIC WITH KAREL - ISTE · IC WITH KAREL INTRODUCTION TO CODING AND LOGICAL REASONING Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound

7 - KEYWORD ELSE

Karel now has choices to make: if the condition is present (if), he does one set of actions. If it is not present (else), he does

another. go

repeat 11

if mark

put

else

left

go

put

right

right

go

left

go

8 – KEYWORD OR

Karel can decide based on the presence of one or another object. The keywords are

connected by the Boolean operator or. repeat 18

go

if coin or nugget

get

if wall

if snake

left

else

right

9 – WHILE LOOP

Karel will continue to repeat a set of actions as long as the while condition is met. while acid

right

go

left

go

go

Page 5: LOGIC WITH KAREL - ISTE · IC WITH KAREL INTRODUCTION TO CODING AND LOGICAL REASONING Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound

10 – FIRST MAZE ALGORITHM

An algorithm is a process used to solve a problem, using certain rules. We want the

algorithm to work consistently and make best use of resources. We may want it to be

flexible enough to solve different conditions.

while not home

go

if wall

left

if wall

right

right

if key

get

11 – CUSTOM COMMANDS I

If we want to use a set of actions several times in a program, we can define a command using def, then call it in the main program.

Comment lines begin with a # symbol, which tells the program to ignore that line. Comments are used to explain what is going on in

the program.

# Command 'waterbox' from level 11.5:

def waterbox

go

repeat 4

repeat 2

go

get

right

repeat 3

go

# Main program:

waterbox

left

repeat 3

go

right

waterbox

go

go

right

go

go

left

waterbox

12 – SECOND MAZE ALGORITHM

This program includes a classic algorithm that can be used to follow along barriers of any shape.

# Move along the wall and collect

# a banana if there is one:

def move

if banana

get

left

while wall

right

go

# Main program:

while not home

move

Page 6: LOGIC WITH KAREL - ISTE · IC WITH KAREL INTRODUCTION TO CODING AND LOGICAL REASONING Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound

13 – CUSTOM COMMANDS II

More practice with custom commands. This program is systematic, using the same set of algorithms for each row.

# Custom command from previous level:

def floor

repeat 14

go

if apple or orange

get

right

while wall

right

go

left

go

# Main program:

while not home

floor

right

while not wall

go

right

right

14 – VARIABLES I

Karel can collect information as he goes. In this case a variable missing starts with

a value of 0, and is increased every time Karel finds a gap in the fence. At the end,

Karel reports the total number of missing fence sections using the print command.

missing = 0

while not home

if not wall

inc(missing)

right

go

left

print("Missing pieces:", missing)

15 – VARIABLES II

More practice with variables. Karel practices a positioning algorithm which places him to the left of the row before counting each

crate. def row

# Locate left-most crate:

while crate

left

go

right

right

go

left

# Count crates:

r = 0

while crate

right

go

left

inc(r)

go

return r

# Main program:

result = row

print("There are", result, "crates!")

Page 7: LOGIC WITH KAREL - ISTE · IC WITH KAREL INTRODUCTION TO CODING AND LOGICAL REASONING Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound

16 – GPS

We can identify the exact location of Karel on our grid, by numbering each horizontal

square from left to right starting from 0 (gpsx), and each vertical square from bottom

to top (gpsy). Note the operator != stands for “not equal to”. while not home

repeat 3

if gpsy != 2

put

go

right

go

left

17 – BOOLEANS

True and False are used to make logical deductions, and are at the heart of computer programming. In this case, Karel assumes

there is a bottle in every corner until he finds one that is not. It only takes one missing bottle to switch from True to False. # Return True if there was a bottle in

# every corner, otherwise return False:

def corners

b = True

repeat 4

while not wall

go

left

b = (b and bottle)

if bottle

get

return b

# Main program:

success = corners

if success

print("There was a bottle in each corner!")

else

print("One or more bottles were missing!")

18 – MAXIMUM

Karel can test for a maximum (or a minimum) by using an algorithm that compares each new value to the previous one. If it is less, then the previous value is retained. If it is more, then the previous value is replaced.

# Collect one column and return its height:

def column

h = 0

left

while bulb

get

go

inc(h)

right

right

while not wall

go

left

go

return h

# Collect all columns and return the maximum height:

def maximum

m = 0

print("Maximum started at", m)

repeat 9

c = column

if m < c

Continued next page

Page 8: LOGIC WITH KAREL - ISTE · IC WITH KAREL INTRODUCTION TO CODING AND LOGICAL REASONING Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound

m = c

print("Maximum updated to", m)

go

go

return m

# Main program:

height = maximum

print("Height is", height)

19 – LISTS I

Karel can generate Python lists to store and return data. Here, Karel is recording the location of orchids in a jungle.

L = []

while not home

right

while not wall

go

if orchid

print("Orchid found at", [gpsx, gpsy])

get

L.append([gpsx, gpsy])

left

left

while not wall

go

right

go

print("Orchids found at positions", L)

20 – LISTS II

In this case, Karel is using a list to map out a path and store each movement and turn in a list.

P = []

while not home

counter = 0

while (not wall) and (not home)

go

inc(counter)

P.append(counter)

left

if wall

right

right

P.append(False)

else

P.append(True)

# Print the list:

print("P =", P)

Page 9: LOGIC WITH KAREL - ISTE · IC WITH KAREL INTRODUCTION TO CODING AND LOGICAL REASONING Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound

21 – RANDOMNESS

Karel can use random numbers to make choices. In this case, Karel randomly goes forward, then left or right until he finds a rug.

Karel only needs to collect one to end the program.

# THERE ARE MANY SOLUTIONS. ALL OF THEM SHOULD BE OK AS LONG # AS THEY SOMEHOW COMBINE RANDOMLY GOING FORWARD AND TURNING.

while empty

if rand

if not wall

go

else

if rand

left

else

right

if rug

get

22 – RECURSION I

Karel uses recursion to call a command until a stopping condition is achieved, in this case: home. Karel will continue to collect

shields and place them in boxes until he is stopped by the home square. Rather than use a while loop, this command calls itself.

# Custom command walk:

def walk

# Stopping condition:

if not home

if shield

get

if box

put

go

# Recursive call:

walk

return

# Main program:

walk

23 – RECURSION II

Karel uses recursion within a more complex function that counts objects and returns a statement which varies according to what he

finds.

# Recursive function: def bounty left go right go # Stopping condition: if not home if candy or lollipop get return bounty + 1 else return bounty else return 0

Page 10: LOGIC WITH KAREL - ISTE · IC WITH KAREL INTRODUCTION TO CODING AND LOGICAL REASONING Karel is a robot who runs around a 12 x 15 maze, collecting and placing objects. That may sound

# Main program: print("I collected", bounty, "candies.")

24 – FINAL CHALLENGE

How will we solve this challenge? Will it be with repeat loops, conditions, lists, random numbers, recursions, counting variables? In

this case the patterns are clearly well defined and repeatable.

go

repeat 4

repeat 2

repeat 3

go

right

get

right

left

go

FINAL THOUGHTS

Karel was designed to teach logical reasoning. Karel was designed as a teaching language by Richard Pettit at Stanford University in

1983, based on Pascal. This version is based on Python, a language commonly used today in science, math, and design. Python has

extensive open source libraries of commands, some powerful features, and the syntax is simple compared to other advanced

languages.

Students can learn and practice many logical structures using Karel, with or without the maze. These 24 problems are just a few

examples. It isn’t difficult to see how programming can be used to solve problems, collect and store data, navigate, and even

generate new ideas in the real world.

NCLab offers a complete Karel course, which can be followed by other Python-based courses. Please visit nclab.com for more

information on courses, trainings, or to apply for a free individual trial to explore these courses. Free trials are available to teachers,

librarians, and administrators.

We hope you have enjoyed your exploration of logic with Karel the Robot!

© Copyright NCLab, Inc 2017 all rights reserved.