SOLUTION TASK 4.01: Counting Stars
class MyPlayer extends Player {
start() {
int count = 0;
while (canMove()) {
move();
if (onStar()) {
count = count + 1;
}
}
say('I have found ${count} stars.');
}
}
SOLUTION TASK 4.02: Cleaning Up
class MyPlayer extends Player {
start() {
bool goingRight = true;
while (!treeFront()) {
removeStar();
if (canMove()) {
move();
} else {
// We are at a border.
if (goingRight) {
// We are at the right border and turn around.
turnAroundRight();
goingRight = false;
} else {
// We are at the left border and turn around.
turnAroundLeft();
goingRight = true;
}
}
}
// Remove the last star.
removeStar();
}
/// Turn around at the right border.
turnAroundRight() {
turnRight();
move();
turnRight();
}
/// Turn around at the left border.
turnAroundLeft() {
turnLeft();
move();
turnLeft();
}
}
SOLUTION TASK 4.03: Inverting
class MyPlayer extends Player {
start() {
bool goingRight = true;
while (!treeFront()) {
invertField();
if (canMove()) {
move();
} else {
// We are at a border.
if (goingRight) {
// We at the right border and turn around.
turnAroundRight();
goingRight = false;
} else {
// We are at the left border and turn around.
turnAroundLeft();
goingRight = true;
}
}
}
// Invert the last field.
invertField();
}
/// Turn around at the right border.
turnAroundRight() {
turnRight();
move();
turnRight();
}
/// Turn around at the left border.
turnAroundLeft() {
turnLeft();
move();
turnLeft();
}
/// Invert a single field.
invertField() {
if (onStar()) {
removeStar();
} else {
putStar();
}
}
}
SOLUTION TASK 4.04: Tree Line
class MyPlayer extends Player {
int longestRow = 0;
/// Your program.
start() {
while (!onStar()) {
if (treeFront()) {
countRow();
} else {
move();
}
}
say('The longest tree line is ${longestRow} trees long.');
}
/// Walks along a tree line and counts the trees.
countRow() {
int currentRow = 0;
turnLeft();
while (treeRight()) {
// Increment the counter for the row by one.
currentRow++;
move();
}
// Go around the tree line.
turnRight();
move();
move();
turnRight();
// Go back down.
while (canMove()) {
move();
}
turnLeft();
// Test if the current tree line is longer than the previous lines.
if (currentRow > longestRow) {
longestRow = currentRow;
}
}
}