This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
What can cause segmentation faults in C++? [closed]
(9 answers)
Closed 2 years ago.
So I am writing a c++ OpenGl application that should test if two figures layed out with matches are identical. I have written an own class: the "figure" class. This class makes use of the two classes "Line" and "Point". Here you can see my implementation in the figure.h header:
#define SHINT short int
class Point
{
public:
std::pair<SHINT, SHINT> coord;
Point()
{
coord = std::pair<SHINT, SHINT>{ 0, 0 };
}
Point(int x, int y)
{
coord = std::pair<SHINT, SHINT>{ (short)x, (short)y };
};
};
class Line
{
public:
std::pair<Point, Point> pts;
Line()
{
pts = std::pair<Point, Point>{ Point(), Point() };
}
Line(Point p1, Point p2)
{
pts = std::pair<Point, Point>{ (Point)p1, (Point)p2 };
};
};
class Figure
{
public:
Figure() {};
private:
std::vector<Line> lines;
Point p1;
Point p2;
char* renderPath = FILEPATH;
public:
void DrawComponents();
void Clear();
void RemoveLine(int index);
void AddLine();
void SetWorking(int x, int y, bool segment); //true seg1, false seg2
void Render();
};
The implementation of the problematic functions are as follows:
void Figure::AddLine()
{
Line l1 = Line(p1, p2);
lines.push_back(l1);
}
void Figure::SetWorking(int x, int y, bool segment)
{
if (segment)
{
p1 = Point(x, y);
}
p2 = Point(x, y);
}
I have a fig*, that can be either set to the first figure or to the second Figure. You can do that with the help of an ImGui overlay. If you press your mouse button, a set of function is triggered:
selected->SetWorking(posX, posY, m_Select); //
if (m_Select)
selected->AddLine();
posX and posY are calculated relative to the mouse position and that is working properly.
We than call the SetWorking() function on the figure pointer, which again calls a constructor in the Point and Sets the working Point to what posX and Y are. I have to Points that are used in turns. So if I click the first time, the first Point is set, if I press a second time, the second Point is set, and with two Points set, we push a new line into the vector. This alteration is achieved by the "segment" bool int the SetWorking() function. Points are saved as std::pairs<> that hold short ints, and Lines are saved as std::pairs<> that hold two points. But if we land there, an error occurs: "Exception thrown: write access violation.
this was 0x14"
The error is thrown in the utility file of the c++ STL: (line 292)
pair& operator=(_Identity_t<_Myself&&> _Right) noexcept(
conjunction_v<is_nothrow_move_assignable<_Ty1>, is_nothrow_move_assignable<_Ty2>>) /* strengthened */ {
first = _STD forward<_Ty1>(_Right.first); // <---- here
second = _STD forward<_Ty2>(_Right.second);
return *this;
}
And honestly, at this point I don't have the slightest clue as of what is going on there. My educated guess is, that something with the std::pair is going wrong, but I am to unskilled with c++ yet, so I don't really now how to solve these kinds of error
"this was 0x14": The error occured in a member function (operator=()) of pair. The pair object that executes operator=() has a value of 0x14 for its this pointer, which is highly unlikely to be correct.
Usually this means that the pair is member of an object with this pointer == nullptr, and the pair object is located at offset 0x14 relative to the class.
I suspect that selected is a nullpointer and the assignment of p1 results in the access violation.
I created a class for a type of enemy using allegro4 and C++; in this class I have a function that makes move a sprite, like this:
sprite_one(x, y);
sprite_two(x2, y2);
class enemy{
public:
void mov(){
x++;
----
y--;
}
}
};
enemy test_one;
test_one.mov(); // this works because its coordinates are x and y
enemy test_two;
test_two.mov(); // this doesn't work, its coordinates are x2 and y2
The problem is that when I create the object, the first one can move according to the function (updating variable x and y), the others no because they have different way to call the variables of the positions. How can I fix this?
Your enemy class needs to have the x and y coordinates as member variables. This is how you get each actual enemy to have its own coordinates separate from all the others. The following code should get you up and running, at least. You will presumably want to add a public function to print the coordinates, or to draw the enemy onscreen.
class enemy
{
int mx, my; // coordinates of this enemy
public:
enemy(int x, int y)
: mx(x), my(y) // initialize the coordinates
{
// possibly add future initialization here
}
void mov()
{
++mx;
--my;
}
}
Then you can create and move two enemies as before:
enemy test_one(x,y);
test_one.mov();
enemy test_two(x2,y2);
test_two.mov();
Note that x,y,x2,y2 are no longer variables storing the current positions of the enemies, but constants defining their start positions.
I really need help on this one cause I am extremely stuck and have no idea what to do.
Edit:
A lot of you guys are saying that I need to use the debugger but let me be clear I have not used C++ for an extremely long time and I've used visual studio for a grand total of 2 weeks so I do not know all the cool stuff it can do with the debugger.
I am a student at university at the beginning of my second year who is trying to work out how to do something mostly by failing.
I AM NOT a professional coder and I don't have all the knowledge that you people have when it comes to these issues and that is why I am asking this question. I am trying my best to show my issue so yes my code contains a lot of errors as I only have a very basic understanding of a lot of C++ principles so can you please keep that in mind when commenting
I'm only posting this here because I can don't know who else to ask right now.
I have a function called world that is suppose to call my render class to draw all the objects inside of its vector to the screen.
#include "C_World.h"
C_World::C_World()
{
// creates an instance of the renderer class to render any drawable objects
C_Renderer *render = new C_Renderer;
}
C_World::~C_World()
{
delete[] render;
}
// adds an object to the world vector
void C_World::addToWorld(C_renderable* a)
{
world_list.push_back(a);
}
void C_World::World_Update()
{
render->ClearScreen();
World_Render();
}
void C_World::World_Render() {
for (int i = 0; i < 1; i++)
{
//render->DrawSprite(world_list[i]->getTexture(), world_list[i]->get_X, world_list[i]->get_Y());
render->DrawSprite(1, 1, 1);
}
}
While testing I commented out the Sprites get functions in order to check if they were causing the issue.
the renderer sprites are added to the vector list in the constructor through the create sprite function
C_Renderer::C_Renderer()
{
// test sprite: Id = 1
CreateSprite("WhiteBlock.png", 250, 250, 1);
}
I thought this might of been the issue so I had it in other functions but this didn't solve anything
Here are the Draw and create Sprite functions
// Creates a sprite that is stored in the SpriteList
// Sprites in the spriteList can be used in the drawSprite function
void C_Renderer::CreateSprite(std::string texture_name,
unsigned int Texture_Width, unsigned int Texture_height, int spriteId)
{
C_Sprite *a = new C_Sprite(texture_name,Texture_Width,
Texture_height,spriteId);
SpriteList.push_back(a);
size_t b = SpriteList.size();
HAPI.DebugText(std::to_string(b));
}
// Draws a sprite to the X and Y co-ordinates
void C_Renderer::DrawSprite(int id,int x,int y)
{
Blit(screen, _screenWidth, SpriteList[id]->get_Texture(),
SpriteList[id]->getTexture_W(), SpriteList[id]->getTexture_H(), x, y);
}
I even added some test code into the create sprite function to check to see if the sprite was being added too the vector list. It returns 1 so I assume it is.
Exception thrown: read access violation.
std::_Vector_alloc<std::_Vec_base_types<C_Sprite *,
std::allocator<C_Sprite *> > >::_Mylast(...) returned 0x8.
that is the full error that I get from the compiler
I'm really really stuck if there is anymore information you need just say and ill post it straight away
Edit 2:
#pragma once
#include <HAPI_lib.h>
#include <vector>
#include <iostream>
#include "C_renderable.h"
#include "C_Renderer.h"
class C_World
{
public:
C_World();
~C_World();
C_Renderer *render = nullptr;
void World_Update();
void addToWorld(C_renderable* a);
private:
std::vector<C_renderable*> world_list;
void C_World::World_Render();
};
#pragma once
#include <HAPI_lib.h>
#include "C_renderable.h"
#include "C_Sprite.h"
#include <vector>
class C_Renderer
{
public:
C_Renderer();
~C_Renderer();
// gets a pointer to the top left of screen
BYTE *screen = HAPI.GetScreenPointer();
void Blit(BYTE *destination, unsigned int destWidth,
BYTE *source, unsigned int sourceWidth, unsigned int sourceHeight,
int posX, int posY);
void C_Renderer::BlitBackground(BYTE *destination,
unsigned int destWidth, unsigned int destHeight, BYTE *source,
unsigned int sourceWidth, unsigned int sourceHeight);
void SetPixel(unsigned int x,
unsigned int y, HAPI_TColour col,BYTE *screen, unsigned int width);
unsigned int _screenWidth = 1750;
void CreateSprite(std::string texture_name,
unsigned int Texture_Width,unsigned int Texture_height, int spriteId);
void DrawSprite(int id, int x, int y);
void ClearScreen();
private:
std::vector<C_Sprite*> SpriteList;
};
I don't say this lightly, but the code you've shown is absolutely terrible. You need to stop and go back several levels in your understanding of C++.
In all likeliness, your crash is the result of a simple "shadowing" issue in one or more of your functions:
C_World::C_World()
{
// creates an instance of the renderer class to render any drawable objects
C_Renderer *render = new C_Renderer;
}
C_World::~C_World()
{
delete[] render;
}
There are multiple things wrong here, and you don't show the definition of C_World but if this code compiles we can deduce that it has a member render, and you have fallen into a common trap.
C_Renderer *render = new C_Renderer;
Because this line starts with a type this is a definition of a new, local variable, render. Your compiler should be warning you that this shadows the class-scope variable of the same name.
What these lines of code
C_World::C_World()
{
// creates an instance of the renderer class to render any drawable objects
C_Renderer *render = new C_Renderer;
}
do is:
. assign an undefined value to `this->render`,
. create a *local* variable `render`,
. construct a dynamic `C_Renderer` presumably on the heap,
. assign that to the *local* variable `render`,
. exit the function discarding the value of `render`.
So at this point the memory is no-longer being tracked, it has been leaked, and this->render is pointing to an undefined value.
You repeat this problem in several of your functions, assigning new results to local variables and doing nothing with them. It may not be this specific instance of the issue that's causing the problem.
Your next problem is a mismatch of new/delete vs new[]/delete[]:
C_World::~C_World()
{
delete[] render;
}
this would result in undefined behavior: this->render is undefined, and delete[] on a non-new[] allocation is undefined.
Most programmers use a naming convention that distinguishes a member variable from a local variable. Two common practices are an m_ prefix or an _ suffix for members, e.g.
class C_World
{
public:
C_Foo* m_foo; // option a
C_Renderer* render_; // option b
// ...
}
Perhaps you should consider using modern C++'s concept of smart pointers:
#include <memory>
class C_World {
// ...
std::unique_ptr<C_Renderer> render_;
// ...
};
C_World::C_World()
: render_(new C_Renderer) // initializer list
{}
But it's unclear why you are using a dynamic allocation here in the first place. It seems like an instance member would be better:
class C_World {
C_Renderer render_;
};
C_World::C_World() : render_() {}
Trying to compile my code in Xcode, but I am obviously running into some problems as I get the error in the title. Here is the code for my header file called "myClasses.h":
#ifndef myClasses_h
#define myClasses_h
class Star
{
public:
Star(int x,int y)
{
int xPos = x;
int yPos = y;
}
};
#endif
So I obviously want a constructor for Star so I can declare a Star object like this:
Star sol(10,30);
Then the code in my "main.cpp":
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include "myClasses.h" //includes the Star class
bool checkOverlap(Star check, int a, int b)
{
double diffX = a - check.xPos;
double diffY = b - check.yPos;
double checkDist = sqrt( pow( diffX,2.0 ) + pow( diffY,2.0) );
if( checkDist > 20 )
return true;
else
return false;
};
int main()
{
//some other code here with no errors
};
Here in the main file I get the error, so I am lost as to what is going wrong? Am I using incorrect syntax to access the object's member variables? Shouldn't the code below print 10:
Star sol(10,30);
cout << sol.xPos
If not, how do I rewrite my class so it behaves like that or how do I properly access the member variables in the constructor?
You need to declare the variables in your class, you can't do that in the body of the constructor as those will be temporary variables not associated with the class instance. This will leave the xPos and yPos as their default values (which is 0) which is probably not what you want. Try something like this instead:
class Star
{
public:
int xPos;
int yPos;
Star(int x,int y):
xPos(x), yPos(y) //initializing the variables here
{
}
};
I've used a member initializer list here to initialize the members.
It's worth noting that this is likely not the best design for a class, you probably want to make xPos and yPos private along with some functions to change those values. You probably want to read up about encapsulation. Essentially you want to hide away information so that people don't need to know the internals of how your classes work in order to use them. This big benefit is that this lets people use your code without needing to worry about the internals of how your code works and lets them keep using your code without having to change their code even if some of those internal details happen to change over time. Imagine the hassle if you had to know exactly how your network card driver was programmed in order to write an application that used the network. It would be a big pain, you might have to change your code whenever you updated the other code, however because this driver code has (hopefully) been encapsulated you don't need to worry about these details in order to use that code. The code and classes you write are no different, think about the people who will use them, try to make it easy for them to use your code.
A possibly better design would be to do something like this:
class Star
{
private:
int xPos;
int yPos;
public:
Star(int x,int y):
xPos(x), yPos(y) //initializing the variables here
{
}
int get_xPos(){
return xPos;
}
int get_yPos(){
return yPos;
}
};
Now in your main code you change:
Star sol(10,30);
cout << sol.xPos;
To:
Star sol(10,30);
cout << sol.get_xPos();
The benefits of doing it this way really start to become more obvious when you get larger software or you have to deal with changes. For example later on the code changes and we decide to store the coordinates in a coordinates struct:
struct coords{
int xPos;
int yPos;
}
class Star
{
private:
coords Pos;
public:
Star(int x,int y):
Pos{x,y} //initializing the variables here
{
}
int get_xPos(){
return Pos.xPos;
}
int get_yPos(){
return Pos.yPos;
}
};
The original code would break:
Star sol(10,30);
cout << sol.xPos; //There's no xPos anymore
but with our new design this:
Star sol(10,30);
cout << sol.get_xPos();
Works just like before! We only needed to change the code in one place in the getter function get_xPos() and everthing will keep working just like it did before we made the changes.
Declare member variables:
class Star
{
public:
int xPos;
int yPos;
Star(int x,int y)
{
xPos = x;
yPos = y;
}
};
I've written a working tetris clone but it has a pretty messy layout. Could I please get feedback on how to restructure my classes to make my coding better. I focuses on making my code as generic as possible, trying to make it more an engine for games only using blocks.
Each block is created seperately in the game.
My game has 2 BlockLists (linked lists): StaticBlocks and Tetroid.
StaticBlocks is obviously the list of all non-moving blocks, and tetroid are the 4 blocks of the current tetroid.
In main a World is created.
First a new tetroid (4 blocks in a list Tetroid) is created by (NewTetroid)
Collision is detected by the (***Collide) functions, by comparing each of Tetroid with all of the StaticBlocks using the (If*****) functions.
When the tetroid stops (hits the bottom/blocks), it is copied (CopyTetroid) to the StaticBlocks and Tetroid is made empty, then tests are made for complete lines, blocks are destroyed/dropped etc by searching StaticBlocks with (SearchY).
A new tetroid is created.
(TranslateTetroid) and (RotateTetroid) perform operations on each block in the Tetroid list one by one ( I think this is bad practise).
(DrawBlockList) just goes through a list, running the Draw() function for each block.
Rotation is controlled by setting rotation axis relative to the first block in Tetroid when (NewTetroid) is called. My rotation function (Rotate) for each block rotates it around the axis, using an input +-1 for left/right rotation. RotationModes and States are for blocks that rotate in 2 or 4 different ways, defining what state they are currently in, and whether they should be rotated left or right. I am not happy with how these are defined in "World", but I don't know where to put them, whilst still keeping my (Rotate) function generic for each block.
My classes are as follows
class World
{
public:
/* Constructor/Destructor */
World();
~World();
/* Blocks Operations */
void AppendBlock(int, int, BlockList&);
void RemoveBlock(Block*, BlockList&);;
/* Tetroid Operations */
void NewTetroid(int, int, int, BlockList&);
void TranslateTetroid(int, int, BlockList&);
void RotateTetroid(int, BlockList&);
void CopyTetroid(BlockList&, BlockList&);
/* Draw */
void DrawBlockList(BlockList&);
void DrawWalls();
/* Collisions */
bool TranslateCollide(int, int, BlockList&, BlockList&);
bool RotateCollide(int, BlockList&, BlockList&);
bool OverlapCollide(BlockList&, BlockList&); // For end of game
/* Game Mechanics */
bool CompleteLine(BlockList&); // Test all line
bool CompleteLine(int, BlockList&); // Test specific line
void ColourLine(int, BlockList&);
void DestroyLine(int, BlockList&);
void DropLine(int, BlockList&); // Drops all blocks above line
int rotationAxisX;
int rotationAxisY;
int rotationState; // Which rotation it is currently in
int rotationModes; // How many diff rotations possible
private:
int wallX1;
int wallX2;
int wallY1;
int wallY2;
};
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;
};
class Block
{
public:
Block(int, int);
~Block();
int GetX();
int GetY();
void SetColour(int, int, int);
void Translate(int, int);
void Rotate(int, int, int);
/* Return values simulating the operation (for collision purposes) */
int IfTranslateX(int);
int IfTranslateY(int);
int IfRotateX(int, int, int);
int IfRotateY(int, int, int);
void Draw();
Block *next;
private:
int pX; // position x
int pY; // position y
int colourR;
int colourG;
int colourB;
};
Sorry if this is a bit unclear or long winded, I'm just looking for some help restructuring.
What is the single responsibility of the World class?
It's just a blob containing practically every kind of functionality. That's not good design. One obvious responsibility is "represent the grid onto which blocks are placed". But that has nothing to do with creating tetroids or manipulating block lists or drawing. In fact, most of that probably doesn't need to be in a class at all. I would expect the World object to contain the BlockList you call StaticBlocks so it can define the grid on which you're playing.
Why do you define your own Blocklist? You said you wanted your code to be generic, so why not allow any container to be used? Why can't I use a std::vector<Block> if I want to? Or a std::set<Block>, or some home-brewed container?
Use simple names that don't duplicate information or contradict themselves. TranslateTetroid doesn't translate a tetroid. It translates all the blocks in a blocklist. So it should be TranslateBlocks or something. But even that is redundant. We can see from the signature (it takes a BlockList&) that it works on blocks. So just call it Translate.
Try to avoid C-style comments (/*...*/). C++-style (//..)behaves a bit nicer in that if you use a C-style comment out an entire block of code, it'll break if that block also contained C-style comments. (As a simple example, /*/**/*/ won't work, as the compiler will see the first */ as the end of the comment, and so the last */ won't be considered a comment.
What's with all the (unnamed) int parameters? It's making your code impossible to read.
Respect language features and conventions. The way to copy an object is using its copy constructor. So rather than a CopyTetroid function, give BlockList a copy constructor. Then if I need to copy one, I can simply do BlockList b1 = b0.
Rather than void SetX(Y) and Y GetX() methods, drop the redundant Get/Set prefix and simply have void X(Y) and Y X(). We know it's a getter because it takes no parameters and returns a value. And we know the other one is a setter because it takes a parameter and returns void.
BlockList isn't a very good abstraction. You have very different needs for "the current tetroid" and "the list of static blocks currently on the grid". The static blocks can be represented by a simple sequence of blocks as you have (although a sequence of rows, or a 2D array, may be more convenient), but the currently active tetroid needs additional information, such as the center of rotation (which doesn't belong in the World).
A simple way to represent a tetroid, and to ease rotations, might be to have the member blocks store a simple offset from the center of rotation. That makes rotations easier to compute, and means that the member blocks don't have to be updated at all during translation. Just the center of rotation has to be moved.
In the static list, it isn't even efficient for blocks to know their location. Instead, the grid should map locations to blocks (if I ask the grid "which block exists in cell (5,8), it should be able to return the block. but the block itself doesn't need to store the coordinate. If it does, it can become a maintenance headache. What if, due to some subtle bug, two blocks end up with the same coordinate? That can happen if blocks store their own coordinate, but not if the grid holds a list of which block is where.)
this tells us that we need one representation for a "static block", and another for a "dynamic block" (it needs to store the offset from the tetroid's center). In fact, the "static" block can be boiled down to the essentials: Either a cell in the grid contains a block, and that block has a colour, or it does not contain a block. There is no further behavior associated with these blocks, so perhaps it is the cell into which it is placed that should be modelled instead.
and we need a class representing a movable/dynamic tetroid.
Since a lot of your collision detection is "predictive" in that it deals with "what if I moved the object over here", it may be simpler to implement non-mutating translation/rotation functions. These should leave the original object unmodified, and a rotated/translated copy returned.
So here's a first pass on your code, simply renaming, commenting and removing code without changing the structure too much.
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);
}
Now, let's add some of the missing pieces:
First, we'll need to represent the "dynamic" blocks, the tetroid owning them, and the static blocks or cells in a grid.
(We'll also add a simple "Collides" method to the world/grid class)
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);
}
and we'll need to re-implement the speculative collision checks. Given the non-mutating Translate/Rotate methods, that is simple: We just create rotated/translated copies, and test those for collision:
// 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))) { ... }
I would personally ditch the static blocks and deal with them as rows. Having a static block you are keeping a lot more information than you need.
A world is made of rows, which is an array of single squares. The squares can be either empty, or a color (or extend it if you have special blocks).
The world also owns a single active block, as you have now. The class should have a rotate and translate method. The block will obviously need to maintain a reference to the world to determine if it will collide with existing bricks or the edge of the board.
When the active block goes out of play, it will call something like world.update() which will add the pieces of the active block to the appropriate rows, clear all full rows, decide if you have lost, etc, and finally create a new active block if needed.