Phys/CSci 135: Assignments
Home Syllabus Assignments Samples

Lab 9. Advanced Searching With Sensors

Reversible (page 73)

import lejos.nxt.Motor;

public interface Reversible extends Action {
    public Reversible reversed();
    public Motor countedMotor();
}

ForwardMove (page 73)

import lejos.nxt.*;

public class ForwardMove implements Reversible {
    public void act() {
        Motor.B.forward();
        Motor.C.forward();
    }

    public Motor countedMotor() {
        return Motor.B;
    }

    public Reversible reversed() {
        return new BackwardMove();
    }
}

Reverser (page 74)

import lejos.nxt.*;

public class Reverser implements Action {
    private Reversible action;
    
    public Reverser(Reversible action) {
        this.action = action;
    }

    public void flip() {
        action = action.reversed();
        action.countedMotor().stop();
        action.countedMotor().resetTachoCount();
        action.act();
    }

    public void act() {
        action.act();
    }

    public int getCount() {
        return Math.abs(action.countedMotor().getTachoCount());
    }

    public static void test(Reversible tested) {
        Reverser r = new Reverser(tested);
        r.act();
        while (Button.LEFT.isPressed() == false) {}
        r.flip();
        while (Button.RIGHT.isPressed() == false) {}
    }
}

Switcher (page 76)

import lejos.nxt.*;

public class Switcher implements Action {
    private Condition detected;
    private Reverser action;

    public Switcher(Reverser action, Condition detected) {
        this.action = action;
        this.detected = detected;
    }

    public void act() {
        int distance = 10;
        action.act();
        while (Button.ESCAPE.isPressed() == false) {
            if (action.getCount() < distance) {
                action.flip();
                distance = distance + 1;
            }
        }
    }

    public static void main(String[] args) {
        Reversible searchMove = new TurnLeftMove();
        Reverser r = new Reverser(searchMove);
        LightSensor light = new LightSensor(SensorPort.S3);
        Condition finder = new LineFinder(light);
        Switcher s = new Switcher(r, finder);
        s.act();
    }
}