aboutsummaryrefslogtreecommitdiff
path: root/Week14 Route 66/src/com/camilstaps/route66/Overviewer.java
blob: 844f40ce85a0fbe1c5fbc023bac0ffe8d2255596 (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
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.camilstaps.route66;

import OO14route66.Car;
import OO14route66.Model;

/**
 * The Overviewer (always only one instance) tells Drivers when they can drive
 * 
 * @author Camil Staps
 */
public class Overviewer {
 
    /**
     * This is a singleton
     */
    private static Overviewer instance;
    
    Car[] cars = new Car[Model.NUMBEROFCARS];
    
    /**
     * This is a singleton
     * @return the instance
     */
    public static Overviewer getInstance() {
        if (instance == null) {
            instance = new Overviewer();
        }
        return instance;
    }
    
    /**
     * Add a car to the list of cars
     * @param car 
     */
    public synchronized void hello(Car car) {
        cars[car.getNumber()] = car;
    }
    
    /**
     * Check if a location is safe for a car to go to. This should always be 
     * checked by a driver before actually driving.
     * @param car
     * @param requested_location
     * @return 
     */
    public synchronized boolean isSafeLocation(Car car, int requested_location) {
        for (Car that_car : cars) {
            if (that_car != null && that_car != car && 
                    that_car.getDirection() == car.getDirection() &&
                    that_car.getLocation() > requested_location &&
                    that_car.getLocation() < requested_location + Car.CARLENGTH + Car.MINCARSPACE) {
                return false;
            }
        }
        return true;
    }

}