CollectNewspaperKarel Solution

This lecture explains how to get started with Karel the Robot:

After watching the lecture, there are a few assignments to get you started. The first one is pretty simple and gets you to feel comfortable with the basics:

Here is my solution:

<pre>/*
 * File: CollectNewspaperKarel.java
 * --------------------------------
 * At present, the CollectNewspaperKarel subclass does nothing.
 * Your job in the assignment is to add the necessary code to
 * instruct Karel to walk to the door of its house, pick up the
 * newspaper (represented by a beeper, of course), and then return
 * to its initial position in the upper left corner of the house.
 */

import stanford.karel.*;

public class CollectNewspaperKarel extends SuperKarel {

	public void run () {
		MoveToNewspaper ();
		PickUp ();
		Return ();
	} 
	private void MoveToNewspaper () {
		move ();
		move ();
		turnRight ();
		move ();
		turnLeft ();
		move ();			
	}
	private void PickUp () {
		pickBeeper ();
		turnAround ();
	}
	private void Return () {
		for (int i = 0; i < 3; i++) {
			move();
		}
		turnRight ();
		move ();
		turnRight ();
	}
}</pre>

I’m sure there are a few solutions to this, but, most importantly, this solves the problem when it runs! I was extremely proud of accomplishing my first little program 🙂

But I’m open to tips. Let me know if you see something that I can improve and apply to the next assignments.

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.