aboutsummaryrefslogtreecommitdiff
path: root/Week14 Route 66/src/OO14route66/Controller.java
blob: 83e609897441f9b65ed550d0563872228302225e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package OO14route66;

import com.camilstaps.route66.Driver;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Route66 Controller
 * @author Pieter Koopman, Camil Staps
 *
 * The initial controller runs as a single thread
 */
public class Controller {
    private int delay = 120;                // average sleep time
    private final Model model;              // the model
    private final Random random;            // a random generator

    /**
     * The constructor of the controller
     * @param model holds the cars
     */
    public Controller(Model model) {
        this.model  = model;
        random      = new Random();
    }

    /**
     * Tell the drivers of all cars in the model to start driving
     */
    public void run() {
        ExecutorService service = Executors.newCachedThreadPool();
        for (Car car : model.getCars()) {
            Driver d = car.getDriver();
            d.setDelay(delay);
            service.execute(d);
        }
    }
    
    /**
     * stop all cars by setting boolean run to false
     */
    public void stopCars() {
        for (Car car : model.getCars()) {
            car.getDriver().setRunning(false);
        }
    }

    /**
     * start all cars by setting boolean run to true
     */
    public void resumeCars() {
        for (Car car : model.getCars()) {
            car.getDriver().setRunning(true);
        }
    }
    
    public int getDelay() {
        return delay;
    }
    
    /**
     * set delay between maximum and minimum bounds
     * @param d 
     */
    public void setDelay(int d) {
        delay = Math.max(20, Math.min (2000, d));
        for (Car car : model.getCars()) {
            car.getDriver().setDelay(delay);
        }
    }
}