Я пишу змейку, и мне нужно как-то изменять матрицу объекта класса Field в объекте класса Snake. Я передаю объект Field через конструктор и записываю его в поле field класса Snake. Матрица не меняется, как-бы я не старался. В чём проблема?
#include <iostream>
#include <string>
#include <vector>
#include <array>
enum Tiles { empty = 0, snake, food, wall };
enum Direction { right = 0, left, up, down };
class Field {
public:
std::vector<std::vector<int>> matrix;
int w, h;
Field() {
w = 50;
h = 30;
matrix.resize(w, std::vector<int>(h));
};
Field(int w, int h) {
this->w = w;
this->h = h;
matrix.resize(w, std::vector<int>(h));
};
void clear(int x, int y) {
matrix[x][y] = 0;
};
void set(int x, int y, int t) {
if (t == Tiles::empty ||
t == Tiles::snake ||
t == Tiles::food ||
t == Tiles::wall) {
matrix[x][y] = t;
}
};
int at(int x, int y) {
return matrix[x][y];
};
};
class Snake {
public:
std::vector<std::pair<int, int>> tiles;
Field field;
int x, y;
int length = 1;
int direction, score = 0;
bool alive = true;
Snake(Field &f, int x, int y) {
this->x = x;
this->y = y;
field = f;
length = 1;
tiles.push_back(std::make_pair(x, y));
field.set(x, y, Tiles::snake);
};
void rotate(int d) {
if (d == Direction::right ||
d == Direction::left ||
d == Direction::up ||
d == Direction::down) {
direction = d;
}
};
void shift() {
int backX = tiles[0].first;
int backY = tiles[0].second;
int headX = tiles.back().first;
int headY = tiles.back().second;
field.clear(backX, backY);
tiles.pop_back();
if (direction == Direction::right) {
if (!isCollide(headX + 1, headY)) {
field.set(headX + 1, headY, Tiles::snake);
tiles.push_back(std::make_pair(headX + 1, headY));
}
} else if (direction == Direction::left) {
if (!isCollide(headX - 1, headY)) {
field.set(headX - 1, headY, Tiles::snake);
tiles.push_back(std::make_pair(headX - 1, headY));
}
} else if (direction == Direction::up) {
if (!isCollide(headX, headY - 1)) {
field.set(headX, headY - 1, Tiles::snake);
tiles.push_back(std::make_pair(headX, headY - 1));
}
} else if (direction == Direction::down) {
if (!isCollide(headX, headY + 1)) {
field.set(headX, headY + 1, Tiles::snake);
tiles.push_back(std::make_pair(headX, headY + 1));
}
}
};
bool isCollide(int x, int y) {
int tile = field.at(x, y);
if (tile == Tiles::snake || tile == Tiles::wall) {
alive = false;
return true;
}
return false;
};
};
int main() {
Field field = Field(50, 30);
Snake snake = Snake(field, 25, 15);
std::cout << snake.tiles[0].first << ';' << snake.tiles[0].second << '\n';
std::cout << snake.field.at(snake.tiles[0].first, snake.tiles[0].second) << '\n';
std::cout << field.at(snake.tiles[0].first, snake.tiles[0].second) << '\n';
return 0;
};