The problem 3 is “In this exercise, your job is to get Karel to create a checkerboard pattern of beepers inside an empty rectangular world, as illustrated in the following before-and-after diagram:”
The way that I viewed the problem is that the robot (Karel) had to move along the either in Up / Down or Left / Right and place a beeper every other step, so in basics if he moves up, he will move up 1 place see if he is able to move any more, if not turn right and if the front is not blocked move forward and right again to go back down the aisle next to the previous one we have just been up and whilst moving up and down the aisle to place a beeper every other step ( so need to keep check of the steps) or you could do the same process but going left and right instead, e.g. move right first to the end of that aisle and then go up if able to and then turn around and move left along the aisle above the previous aisle.
Here is my implementation of both ideas, again the source code for the assignment 1 is attached above in the zip file and also the PDF with the full assignment details.
/* * File: CheckerboardKarel.java * ---------------------------- * When you finish writing it, the CheckerboardKarel class should draw * a checkerboard using beepers, as described in Assignment 1. You * should make sure that your program works for all of the sample * worlds supplied in the starter folder. */ import stanford.karel.*; public class CheckerboardKarel extends SuperKarel { private boolean putBeeper = true; private void placeBeeperAndMove() { while (true) { if (putBeeper) { putBeeper(); putBeeper = false; } else putBeeper = true; if (frontIsBlocked()) break; move(); } } private void goUpAndDown() { boolean turnLeft = true; while (true) { if (turnLeft) turnLeft(); else turnRight(); placeBeeperAndMove(); turnLeft = (turnLeft == true ? false : true); if (turnLeft) turnLeft(); else turnRight(); if (frontIsBlocked()) break; move(); } } public void goLeftAndRight() { boolean turnLeft = true; while (true) { placeBeeperAndMove(); if (turnLeft) turnLeft(); else turnRight(); if (frontIsBlocked()) break; move(); if (turnLeft) turnLeft(); else turnRight(); turnLeft = (turnLeft == true ? false : true); } } // You fill in this part public void run() { // go up and down //goUpAndDown(); // go left and right goLeftAndRight(); } } |
Here is my solution
This is my solution for solving this problem. This works for all worlds (including 1xn, nx1 and 1×1 worlds).