gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:09:44 25 4
gpt4 key购买 nike

我想用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com