CSE 111 Karel the Robot

advertisement
CSE 111
Karel the Robot
Decision Making
The ability to make decisions significantly
increases the capability of Karel to perform
tasks
How is this accomplished?
Conditional Statements
If-Then
If-Then-Else
If Then Instruction
Format
If condition THEN instruction
How does it work?
If condition is met, then perform instruction(s) in
THEN clause
Reserved Words
IF
THEN
If Then Instruction
Test Conditions
Is Karel next to a wall?
front-is-clear
 front-is-blocked
left-is-clear
 left-is-blocked
right-is-clear
 right-is-blocked
What direction is Karel facing?
facing-north
 not-facing-north
facing-south
 not-facing-south
facing-east
 not-facing-east
facing-west
 not-facing-west
If Then Instruction
Test Conditions
Are there any beepers in Karel’s beeper bag?
any-beepers-in-beeper-bag
 no-beepers-in-beeper-bag
Is Karel next to a beeper?
next-to-a-beeper
 not-next-to-a-beeper
If Then Instruction
Example
IF next-to-a-beeper THEN
BEGIN
pickbeeper;
END;
If Then Instruction
What if multiple instructions are to be executed?
Block Structuring
Instructions are placed between the delimiters BEGIN &
END
Format
If condition THEN
BEGIN
instructions
END;
Sample Program
Task
9
8
7
6
5
4
3
2
1
N
W
E
S
1
1 1
Karel’s
Initial
Position
1
Streets
Streets
Clear a room of all beepers
Room Size: 3 x 3
Karel starts in lower left, facing north
Room is square
There will be no more than one beeper on an
intersection
Sample Initial World
Sample Final World
9
8
7
6
5
4
3
2
1
Karel’s
Final
Position
N
W
E
S
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
Avenues
Avenues
Sample Program
BEGINNING-OF-PROGRAM
DEFINE-NEW-INSTRUCTION turnright AS
BEGIN
turnleft;
turnleft;
turnleft;
END;
DEFINE-NEW-INSTRUCTION clear-row AS
BEGIN
IF next-to-a-beeper THEN pickbeeper;
move;
IF next-to-a-beeper THEN pickbeeper;
move;
IF next-to-a-beeper THEN pickbeeper;
END;
Sample Program
BEGINNING-OF-EXECUTION
clear-row;
turnright;
move;
turnright;
clear-row;
turnleft;
move;
turnleft;
clear-row;
turnoff
END-OF-EXECUTION
END-OF-PROGRAM
References
Richard E. Pattis (revised by Jim Roberts &
mark Stehlik), Karel the Robot, John Wiley &
Sons, Inc., 2nd edition, 1995, pp 65-86
Download