- Какова одиночная ответственность класса
World
?
Это просто блоб, содержащий практически все виды функций. Это не хороший дизайн. Одна очевидная ответственность - «представлять сетку, на которой размещены блоки». Но это не имеет ничего общего с созданием тетроидов, манипулированием списками блоков или рисованием. Фактически, большая часть этого, вероятно, вообще не должна быть в классе. Я ожидал бы, что объект World
будет содержать BlockList
, который вы вызываете StaticBlocks, чтобы он мог определять сетку, на которой вы играете.
- Почему вы определяете свой
Blocklist
? Вы сказали, что хотите, чтобы ваш код был универсальным, так почему бы не разрешить использовать любой контейнер? Почему я не могу использовать std::vector<Block>
, если хочу? Или std::set<Block>
, или какой-нибудь самодельный контейнер?
- Используйте простые имена, которые не дублируют информацию и не противоречат друг другу.
TranslateTetroid
не переводит тетроид. Он переводит все блоки в черный список. Так должно быть TranslateBlocks
или что-то в этом роде. Но даже это излишне. Мы можем видеть из подписи (она занимает BlockList&
), что она работает на блоках. Так что просто назовите это Translate
.
- Старайтесь избегать комментариев в стиле C (
/*...*/
). Стиль C ++ (//..
) ведет себя немного лучше, так как если вы используете комментарий в стиле C для всего блока кода, он сломается, если этот блок также будет содержать комментарии в стиле C. (В качестве простого примера, /*/**/*/
не будет работать, так как компилятор увидит первый */
как конец комментария, и поэтому последний */
не будет считаться комментарием.
- Что со всеми (неназванными)
int
параметрами? Это делает ваш код невозможным для чтения.
- Уважайте языковые особенности и соглашения. Способ копирования объекта - использование его конструктора копирования. Поэтому вместо функции
CopyTetroid
дайте BlockList
конструктор копирования. Тогда, если мне нужно скопировать один, я могу просто сделать BlockList b1 = b0
.
- Вместо методов
void SetX(Y)
и Y GetX()
удалите избыточный префикс Get / Set и просто укажите void X(Y)
и Y X()
. Мы знаем, что это геттер, потому что он не принимает параметров и возвращает значение. И мы знаем, что другой является установщиком, потому что он принимает параметр и возвращает void.
BlockList
не очень хорошая абстракция. У вас очень разные потребности в «текущем тетроиде» и «списке статических блоков, находящихся в данный момент в сетке». Статические блоки могут быть представлены простой последовательностью блоков, как у вас (хотя последовательность строк или двумерный массив может быть более удобной), но активный в настоящее время тетроид требует дополнительной информации, такой как центр вращения (который не принадлежит в World
).
- Простой способ представления тетроида и облегчения поворотов может состоять в том, чтобы блоки-члены сохраняли простое смещение от центра вращения. Это облегчает вычисление вращений и означает, что блоки-члены вообще не нужно обновлять во время перевода. Просто центр вращения должен быть перемещен.
- В статическом списке даже неэффективно, чтобы блоки знали свое местоположение. Вместо этого сетка должна сопоставлять местоположения с блоками (если я спрашиваю сетку «какой блок существует в ячейке
(5,8)
», она должна иметь возможность вернуть блок. Но самому блоку не нужно сохранять координаты. Если это так , это может стать головной болью обслуживания. Что делать, если из-за некоторой тонкой ошибки два блока заканчивают с одной и той же координатой? Это может произойти, если блоки сохраняют свою собственную координату, но не если сетка содержит список того, какой блок находится где. )
- это говорит нам о том, что нам нужно одно представление для «статического блока», а другое для «динамического блока» (в нем необходимо хранить смещение от центра тетроида). Фактически, «статический» блок может быть сведен к основам: либо ячейка в сетке содержит блок, и этот блок имеет цвет, либо он не содержит блок. Больше нет поведения, связанного с этими блоками, поэтому, возможно, вместо этого следует смоделировать ячейку, в которую он помещен.
- и нам нужен класс, представляющий подвижный / динамический тетроид.
- Так как большая часть вашего обнаружения столкновений является «прогнозирующей» в том смысле, что она имеет дело с «что, если я переместил объект сюда», может быть проще реализовать немутирующие функции перемещения / поворота. Они должны оставить исходный объект неизмененным, а возвращенную повернутую / переведенную копию.
Итак, вот первый шаг к вашему коду, просто переименование, комментирование и удаление кода без чрезмерного изменения структуры.
class World
{
public:
// Constructor/Destructor
// the constructor should bring the object into a useful state.
// For that, it needs to know the dimensions of the grid it is creating, does it not?
World(int width, int height);
~World();
// none of thes have anything to do with the world
///* Blocks Operations */
//void AppendBlock(int, int, BlockList&);
//void RemoveBlock(Block*, BlockList&);;
// Tetroid Operations
// What's wrong with using BlockList's constructor for, well, constructing BlockLists? Why do you need NewTetroid?
//void NewTetroid(int, int, int, BlockList&);
// none of these belong in the World class. They deal with BlockLists, not the entire world.
//void TranslateTetroid(int, int, BlockList&);
//void RotateTetroid(int, BlockList&);
//void CopyTetroid(BlockList&, BlockList&);
// Drawing isn't the responsibility of the world
///* Draw */
//void DrawBlockList(BlockList&);
//void DrawWalls();
// these are generic functions used to test for collisions between any two blocklists. So don't place them in the grid/world class.
///* Collisions */
//bool TranslateCollide(int, int, BlockList&, BlockList&);
//bool RotateCollide(int, BlockList&, BlockList&);
//bool OverlapCollide(BlockList&, BlockList&); // For end of game
// given that these functions take the blocklist on which they're operating as an argument, why do they need to be members of this, or any, class?
// Game Mechanics
bool AnyCompleteLines(BlockList&); // Renamed. I assume that it returns true if *any* line is complete?
bool IsLineComplete(int line, BlockList&); // Renamed. Avoid ambiguous names like "CompleteLine". is that a command? (complete this line) or a question (is this line complete)?
void ColourLine(int line, BlockList&); // how is the line supposed to be coloured? Which colour?
void DestroyLine(int line, BlockList&);
void DropLine(int, BlockList&); // Drops all blocks above line
// bad terminology. The objects are rotated about the Z axis. The x/y coordinates around which it is rotated are not axes, just a point.
int rotationAxisX;
int rotationAxisY;
// what's this for? How many rotation states exist? what are they?
int rotationState; // Which rotation it is currently in
// same as above. What is this, what is it for?
int rotationModes; // How many diff rotations possible
private:
int wallX1;
int wallX2;
int wallY1;
int wallY2;
};
// The language already has perfectly well defined containers. No need to reinvent the wheel
//class BlockList
//{
//public:
// BlockList();
// ~BlockList();
//
// Block* GetFirst();
// Block* GetLast();
//
// /* List Operations */
// void Append(int, int);
// int Remove(Block*);
// int SearchY(int);
//
//private:
// Block *first;
// Block *last;
//};
struct Colour {
int r, g, b;
};
class Block
{
public:
Block(int x, int y);
~Block();
int X();
int Y();
void Colour(const Colour& col);
void Translate(int down, int left); // add parameter names so we know the direction in which it is being translated
// what were the three original parameters for? Surely we just need to know how many 90-degree rotations in a fixed direction (clockwise, for example) are desired?
void Rotate(int cwSteps);
// If rotate/translate is non-mutating and instead create new objects, we don't need these predictive collision functions.x ½
//// Return values simulating the operation (for collision purposes)
//int IfTranslateX(int);
//int IfTranslateY(int);
//int IfRotateX(int, int, int);
//int IfRotateY(int, int, int);
// the object shouldn't know how to draw itself. That's building an awful lot of complexity into the class
//void Draw();
//Block *next; // is there a next? How come? What does it mean? In which context?
private:
int x; // position x
int y; // position y
Colour col;
//int colourR;
//int colourG;
//int colourB;
};
// Because the argument block is passed by value it is implicitly copied, so we can modify that and return it
Block Translate(Block bl, int down, int left) {
return bl.Translate(down, left);
}
Block Rotate(Block bl, cwSteps) {
return bl.Rotate(cwSteps);
}
Теперь давайте добавим некоторые недостающие фрагменты:
Во-первых, нам нужно представить «динамические» блоки, тетроид, владеющий ими, и статические блоки или ячейки в сетке.
(Мы также добавим простой метод "Collides" в класс world / grid)
class Grid
{
public:
// Constructor/Destructor
Grid(int width, int height);
~Grid();
// perhaps these should be moved out into a separate "game mechanics" object
bool AnyCompleteLines();
bool IsLineComplete(int line);
void ColourLine(int line, Colour col);Which colour?
void DestroyLine(int line);
void DropLine(int);
int findFirstInColumn(int x, int y); // Starting from cell (x,y), find the first non-empty cell directly below it. This corresponds to the SearchY function in the old BlockList class
// To find the contents of cell (x,y) we can do cells[x + width*y]. Write a wrapper for this:
Cell& operator()(int x, int y) { return cells[x + width*y]; }
bool Collides(Tetroid& tet); // test if a tetroid collides with the blocks currently in the grid
private:
// we can compute the wall positions on demand from the grid dimensions
int leftWallX() { return 0; }
int rightWallX() { return width; }
int topWallY() { return 0; }
int bottomWallY { return height; }
int width;
int height;
// let this contain all the cells in the grid.
std::vector<Cell> cells;
};
// represents a cell in the game board grid
class Cell {
public:
bool hasBlock();
Colour Colour();
};
struct Colour {
int r, g, b;
};
class Block
{
public:
Block(int x, int y, Colour col);
~Block();
int X();
int Y();
void X(int);
void Y(int);
void Colour(const Colour& col);
private:
int x; // x-offset from center
int y; // y-offset from center
Colour col; // this could be moved to the Tetroid class, if you assume that tetroids are always single-coloured
};
class Tetroid { // since you want this generalized for more than just Tetris, perhaps this is a bad name
public:
template <typename BlockIter>
Tetroid(BlockIter first, BlockIter last); // given a range of blocks, as represented by an iterator pair, store the blocks in the tetroid
void Translate(int down, int left) {
centerX += left;
centerY += down;
}
void Rotate(int cwSteps) {
typedef std::vector<Block>::iterator iter;
for (iter cur = blocks.begin(); cur != blocks.end(); ++cur){
// rotate the block (*cur) cwSteps times 90 degrees clockwise.
// a naive (but inefficient, especially for large rotations) solution could be this:
// while there is clockwise rotation left to perform
for (; cwSteps > 0; --cwSteps){
int x = -cur->Y(); // assuming the Y axis points downwards, the new X offset is simply the old Y offset negated
int y = cur->X(); // and the new Y offset is the old X offset unmodified
cur->X(x);
cur->Y(y);
}
// if there is any counter-clockwise rotation to perform (if cwSteps was negative)
for (; cwSteps < 0; --cwSteps){
int x = cur->Y();
int y = -cur->X();
cur->X(x);
cur->Y(y);
}
}
}
private:
int centerX, centerY;
std::vector<Block> blocks;
};
Tetroid Translate(Tetroid tet, int down, int left) {
return tet.Translate(down, left);
}
Tetroid Rotate(Tetroid tet, cwSteps) {
return tet.Rotate(cwSteps);
}
и нам нужно повторно реализовать спекулятивные проверки столкновений. Учитывая неизменяемые методы Translate / Rotate, это просто: мы просто создаем повернутые / переведенные копии и проверяем их на столкновение:
// test if a tetroid t would collide with the grid g if it was translated (x,y) units
if (g.Collides(Translate(t, x, y))) { ... }
// test if a tetroid t would collide with the grid g if it was rotated x times clockwise
if (g.Collides(Rotate(t, x))) { ... }