aboutsummaryrefslogtreecommitdiff
path: root/Week14 Route 66/src/OO14route66/Controller.java
blob: 3b684dc1e4902631f61367927a86d99fc5f69660 (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package OO14route66;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * OO1route66 initial class
 * @author Pieter Koopman
 *
 * The initial controller runs as a single thread
 */
public class Controller
{
    private int delay = 200;                // average sleep time
    private final Model model;              // the model
    private final Random random;            // a random generator
    private boolean run = true;             // car can run in simulation

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

    /**
     * the run method from Thread
     * forever:
     *      move all cars
     *      sleep some time
     */
    public void run() {
        ExecutorService service = Executors.newCachedThreadPool();
        for (Car car : model.getCars()) {
            service.execute(car.getDriver());
        }
    }
    
    /**
     * wait some pseudo random time
     */
    private void pause() {
        try { // sleep can throw an exception 
            Thread.sleep(delay / 2 + random.nextInt(delay));
        }
        catch (InterruptedException e) { // catch the exception thrown by sleep
            System.out.println("An exception in Controller: " + e);
        }
    }
    
    /**
     * make one step with all cars and repaint views.
     */
    public void stepAllCars() {
        if (run) {
            for (int c = 0; c < Model.NUMBEROFCARS; c += 1) {
                model.getCar(c).step();
            }
        }
        model.update(); // update only after all cars have stepped
    }
    /**
     * stop all cars by setting boolean run to false
     */
    public void stopCars() {
        run = false;
    }

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