Код: Выделить всё
/**
* @brief updates the grid
* @details First, generates a temporary copy of the current grid with all empty values
* Second, performs all updates on the copy grid while using data from old grid to avoid data dependency.
* Third, replaces the old grid with the new grid.
*/
void update_grid() {
// make a temporary Ocean object, a copied version of current object calling this function.
Ocean temp_ocean(*this);
// Iterate over this temp_ocean:
for (int i = 0; i < temp_ocean.num_rows; ++i) {
for (int j = 0; j < temp_ocean.num_cols; ++j) {
// skip empty cells
if (temp_ocean.get_cell(i, j) == Occupy::Empty) { continue; }
// retrieve cell state from current grid:
Occupy curr_obj = get_cell(i, j);
// perform movement based on the object type
switch(curr_obj) {
// when Turtle
case Occupy::Turtle:
temp_ocean.turtle_move(i, j);
break;
// when Trash
case Occupy::Trash:
temp_ocean.trash_move(i, j);
break;
// when Ship
case Occupy::Ship:
temp_ocean.ship_move(i, j);
break;
// default:
default: break;
}
}
}
// replace the original Ocean object with the temp one:
*this = temp_ocean;
};
Код: Выделить всё
void turtle_move (int i, int j) {
// use random_direction () function with default prob of 1 / 9.
move(i, j, Occupy::Turtle, random_direction());
};
Код: Выделить всё
/**
* @brief setter for a specific cell
* @param i index of row, starting at 0
* @param j index of column, starting at 0
* @param value value to update that cell
*/
void set_cell(int i, int j, Ocean::Occupy value) {
grid.at(i * num_cols + j) = static_cast(value);
}
/**
* @brief getter for a specific cell
* @param i index of row, starting at 0
* @param j index of column, starting at 0
* @return cell state in Occupy enum;
*/
Ocean::Occupy get_cell(int i, int j) {
return static_cast(grid.at(i * num_cols + j));
}
Например, в update_grid() используется черепаха_move(). . Будет ли эта черепаха_move() действовать на temp_grid или на this.grid?
Кстати, все методы относятся к классу Ocean.
Основной( ) будет выглядеть примерно так:
Код: Выделить всё
int main() {
Ocean ocean{// set up constructor};
ocean.update_grid();
return 0;
}
Подождите... почему у меня болит голова? Могу ли я просто обновить эту сетку напрямую при доступе к значениям данных в temp_ocean?
Подробнее здесь: https://stackoverflow.com/questions/792 ... nvocations
Мобильная версия