1

I want to design a data structure with OOP for emulating traffic situation in a racing game. The requirements are as below:

  1. Each vehicle can know on which position of a lane, which lane, and which section of road it is driving.
  2. For each road, it can know how many vehicles are on it, and how many vehicles on each lane on the road.
  3. (plus) Each vehicle has it's driving strategy. For example, some vehicles like to drive fast while others like slow.

I use java to implement this topic. Currently my objects are as below. I just know that this could need a bi-direction relationship between Vehicle and Road/RoadSection, but I don't know how to implement it.

class Lane {
    List<Vehicle> vehicleDrivingOnMe = new ArrayList<Vehicle>()

}

class RoadSection {

    int roadSectionLengthByKM
    /**
     * Integer: LaneID, example: 0 for overspeed
     */
    Map<Integer, Lane> lanes = new HashMap<Integer, Lane>()
}

class Road {
    List<RoadSection> roadSectionList = new ArrayList<RoadSection>()
}

class Vehicle {
    int drivingSpeedByKM

}

Then, my problem is, what elements should I add into what object for fulfilling the requirements 1 and 2? Any suggestion is appreciated.

Christophe
  • 68,716
  • 7
  • 72
  • 138
wureka
  • 731
  • 1
  • 11
  • 26

1 Answers1

0

To fulfill requirement 1 you can maintain parent pointers.

class Lane {
    RoadSection roadSection;
    List<Vehicle> vehicleDrivingOnMe = new ArrayList<Vehicle>();

    public void addVehicle(Vehicle vehicle) {
        //Update parent
        vehicle.lane = this;
        //Update the position
        vehicle.position = vehicleDrivingOnMe.size();
        vehicleDrivingOnMe.add(vehicle);
    }
}

class Vehicle {
    Lane lane;
    int drivingSpeedByKM;
    int position;
}

You can now get the lane of a vehicle by vehicle.lane.roadSection. Just update the parent pointers accordingly.

To fulfill requirement 2 you can either implement just in time calculation or cache the results in a field for objects up in the hierarchy. Like noOfVechiles. For just in time calculation you can look for something like this.

class Road {
    List<RoadSection> roadSectionList = new ArrayList<RoadSection>();

    public long getVehicles() {
        long count = 0;
        for (RoadSection section : roadSectionList) {
            for (Integer laneId : section.lanes.keySet()) {
                count += section.lanes.get(laneId).vehicleDrivingOnMe.size();
            }
        }
        return count;
    }

    public long getVehicles(int laneId) {
        long count = 0;
        for (RoadSection section : roadSectionList) {
            Lane lane = section.lanes.get(laneId);
            count += lane == null ? 0 : lane.vehicleDrivingOnMe.size();
        }
        return count;
    }
}
Prashant
  • 153
  • 9