java - 游戏中表达道路交通状况的数据结构

标签 java oop data-structures racing

我想用OOP设计一个数据结构来模拟赛车游戏中的交通状况。 要求如下:

  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.

我使用java来实现这个主题。目前我的对象如下。我只知道这可能需要 VehicleRoad/RoadSection 之间存在双向关系,但我不知道如何实现它。

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

}

那么,我的问题是,我应该在什么对象中添加什么元素才能满足要求1和2?如有任何建议,我们将不胜感激。

最佳答案

要满足要求 1,您可以维护父指针。

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;
}

您现在可以通过vehicle.lane.roadSection获取车辆的车道。只需相应地更新父指针即可。

要满足要求 2,您可以实现即时计算,也可以将结果缓存在层次结构中向上的对象的字段中。就像noOfVechiles。对于即时计算,您可以寻找类似的东西。

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;
    }
}

关于java - 游戏中表达道路交通状况的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59797492/

相关文章:

java - 找不到类型 Material 的属性 getMaterials!和创建名称为 'materialRepository' : 的 bean 时出错

java - 安卓 SIP : How to make audio call without using SIP address (I want to use real phone number instead)

javascript - prototype.constructor 和 object of itself 有什么区别?

java - 在 Map 中存储和比较树节点

java - 创建键值对象列表

java - 方法重载中也存在多态性吗?

java - 找不到 bundle java.util.PropertyResourceBundle、sc.title 的资源

javascript - 如何扩展正则表达式对象

java - 构建器模式与配置对象

algorithm - 选择排序运行时困惑