how last player is handled is wrong and gives me exceptions class NectoRewardFunction : public RewardFunction {
private:
const Vec BLUE_GOAL = (CommonValues::BLUE_GOAL_BACK + CommonValues::BLUE_GOAL_CENTER) / 2;
const Vec ORANGE_GOAL = (CommonValues::ORANGE_GOAL_BACK + CommonValues::ORANGE_GOAL_CENTER) / 2;
The issue you're encountering stems from the assumption in your code that the index of a player in the state.players vector corresponds directly to their carId. This assumption can lead to out-of-bounds access and exceptions, especially when carId values are not sequential or start from zero.
In your GetReward function, you're accessing the rewards using player.carId as an index:
cpp
return rewards[player.carId];
However, rewards is a std::vector<float>, and if player.carId is greater than or equal to state.players.size(), this will cause an out-of-bounds access, leading to an exception.
Solution:
To fix this issue, you should use a std::unordered_map<int, float> instead of a std::vector<float> for storing rewards. This way, you can map each player's carId to their corresponding reward, avoiding any mismatches between vector indices and carIds.
Here's how you can modify your code:
Change the Data Structures:
Update the rewards and playerQualities to be std::unordered_map<int, float>:
Modify GetReward to use the map and handle cases where a player's reward might not have been calculated:
cpp
float GetReward(const PlayerData& player, const GameState& state, const Action& previousAction) override {
if (rewards.empty()) {
calculateRewards(state);
lastState = state;
}
auto it = rewards.find(player.carId);
if (it != rewards.end()) {
return it->second;
} else {
return 0.0f; // Default reward if not found
}
}
Ensure Consistency Across States:
Make sure that lastState is properly updated and that any players who may have joined or left between states are handled correctly.
Explanation:
By using std::unordered_map<int, float>, you avoid relying on the index positions of players in the state.players vector, which can change over time and may not align with carId. The carId is a unique identifier for each player and is safe to use as a key in your maps.
Additionally, you should determine team membership based on the player's team attribute rather than their position in the player list. This change ensures that team-based calculations, such as goal scoring rewards, are accurately applied regardless of player ordering.
Note:
Be cautious when accessing data from previous states, especially if players can join or leave the game. Always check if a player exists in lastState before accessing their data.
Handle default cases where a player's reward may not have been calculated, such as when a player is new to the game.
By making these changes, you should resolve the exceptions caused by incorrect handling of the last player and ensure that rewards are accurately calculated and assigned to each player.