EDIT: To initialize the position array m_pos[3] I set all it's values to 0 in the constructor and then I call from the main function another function called SetPos() which only sets the position of the planet in the 3D map:
void SetPos(float x, float z);
void Planet::SetPos(float x, float z)
{
m_pos[0]=x;
m_pos[1]=0;
m_pos[2]=y;
}
Thus, the constructor takes the form:
Planet::Planet()
{
m_pos[0]=0;
m_pos[1]=0;
m_pos[2]=0;
}
Is that a bad way to do it? (by need, i can't set the position directly through the constructor).
ORIGINAL:
I've created a class called Planet which controles a series of planets (Planet object) in a map. Each object has an array pos[3] which stores the coordinates where the planet must be drawn.
The planets also own a function called DrawConnections() which is in charge of drawing lines representing the connections between the actual planet and the other planets. The planets that one planet is connected to are stored in a vector, std::vector<Planet> connections.
Since attributes are encapsulated, there's a function in the Planet class which returns the position of the planet, called GetPos(float* pos), where *pos is a pointer to an array capable of storing the position of the planet.
First things first, those are the prototypes and variable declarations from Planet.h file:
public:
void DrawConnections(float radius);
void GetPos(float* position);
private:
float m_pos[3];
std::vector<Planet> m_connection;
The function DrawConnections() from Planet.cpp looks like this:
void Planet::DrawConnections(float radius) //parameter radius controls width of lines
{
float position[3]={0.0f,0.0f,0.0f}; //array storing the position of the planets
//which we are connecting to
//various OpenGl calls go here
glBegin(GL_LINES); //begins drawing the lines
for(int i=0;i<m_connection.size();i++) //for each planet we are connected to, draw a
//line
{
glVertex3f(m_pos[0],m_pos[1],m_pos[2]); //draws the first point of the line in the
//actual planet
m_connection[i].GetPos(position); //Gets the position of the planet we connect to
glVertex3f(position[0],position[1],position[2]); //draws the second point of the
//in the planet we connect to
}
glEnd(); //ends drawing
//some other OpenGl calls
}
The function GetPos() from Planet.cpp looks like this:
void Planet::GetPos(float* position)
{
position[0]=m_pos[0]; //copies the data from the position array to
position[1]=m_pos[1]; //the given pointer
position[2]=m_pos[2];
}
Any planet has x, neither z, 0 coordinate. Each one of them has a set of (x,y,z) coordinates, with x and z always different to 0.
However, some of the calls to GetPos() return x and z equal to 0, while others work properly.
This results in many lines going from the planets to the bottom left corner of the screen, without representing any connection. From what I've figured out I think the problem is in the GetPos(). However, other similar drawing functions also use GetPos() and work perfectly when they're called before the DrawConnection() function, but seem to be affected when they're called once DrawConnections() has been called It is as if that one was modifying the values of the position array when called and thus disturbing everything else which has to be with the position, including herself.
As an additional information, I'm working with Codeblocks and the MinGW GNU GCC compiler. I appreciate any help that you could give me.
Why not do?
public:
void DrawConnections(float radius);
const std::vector<float>& GetPos() const {return m_pos;};
private:
std::vector<float> m_pos;
std::vector<Planet> m_connection;
Related
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 have a vector class
class Vector {
public:
double x, y, z;
Vector add(Vector v) {
return Vector(x+v.x, y+v.y, z+v.z);
}
};
and I have a class Ray
class Ray {
public:
Vector origin, direction;
Vector getOrigin() { return origin; }
};
In some method, I do:
Vector x = ray.origin().add(normal); // doesn't work
Vector y = ray.getRayOrigin().add(normal); // works
error message: Type vector doesn't provide a call operator
Why can't I just access the vector directly?
Because origin is not a function. Remove the parentheses when you access it.
Xīcò has the correct solution, but not the right symptom.
origin doesn't have to be a function. The Vector class could overload operator() and be called as if it were a function, and that's the message the compiler is trying to get across.
ray.origin allows anyone to do anything to ray's origin member including things that could be harmful to ray. Very uncool. The purpose of setters and getters is to regulate access to member variables. The goal is self defence.
OP's getOrigin method doesn't return origin. It returns a copy of origin. A malicious cretin can do anything they want to the copy without breaking ray. This is most often the right way unless the object returned is intended to be modified or prohibitively expensive to copy. In that modification case, lock down the returned object with private data, and getters and setters of it's own. In the expensive copy case, declare the return value to be const to reduce the possibility of damage.
A good setter will vet all input to the origin member before allowing the change to take place. If the caller tries to feed in values that are inconsistent with origin, ray can slap it down.
Directly accessing origin through . allows ray no defence whatsoever. It also prevents ray from changing the implementation of origin without also chancing origin's users.
Whether these are concerns with a pair of simple classes like Vector and Ray, is a matter of coding style and necessity, but locking down data access to the minimum necessary is generally a good habit to get into and a must when developing complicated software.
class Vector {
public:
double x, y, z;
Vector add(Vector v) {
return Vector(x+v.x, y+v.y, z+v.z);
}
};
class Ray {
public:
Vector origin, direction;
Vector getOrigin() { return origin; }
Vector& getOrigin2() { return origin; }
};
int main() {
Ray ray;
Vector v1 = ray.origin; // returns origin member
Vector v2 = ray.getOrigin(); // returns a copy of origin member
Vector v3 = ray.getOrigin2(); // same as v1, returns origin member
}
I'm designing a robot simulator for a university project and I've hit a big issue for some collision detection. Here is my robot.h header file:
#ifndef robot_h
#define robot_h
#include <vector>
enum direction
{
UP,DOWN,LEFT,RIGHT
};
enum motor
{
STOP,SLOW,FAST
};
class robot
{
public:
robot();
char bot; // The bot onscreen
int getX(); // The X position of robot
int getY(); // The Y position of robot
int dir; // The direction the robot is going
bool touchSensor; // Boolean value if collision
int lightSensor; // light sensor between 10-100
int motorA; // Motor A between 0, 1 and 2
int motorB; // Motor A between 0, 1 and 2
void detection(int x, int y);
void getReturnObject();
bool returnObjectDash;
bool returnObjectLine;
void move(); // Moving the robot
void draw(); // Drawing the robot on screen
void update(); // Updating the robot position
private:
int positionX; // Starting X value
int positionY; // Starting Y value
};
#endif
Basically, I have two boolean values being used:
returnObjectDash;and returnObjectLine. I have this code in my matrix.cpp file:
void matrix::detection(int x, int y)
{
if(vector2D[x][y]=='-')
{
returnObjectDash=true;
system("pause");
}
else
{
returnObjectDash=false;
}
if(vector2D[x][y]=='|')
{
returnObjectLine=true;
}
else
{
returnObjectLine=false;
}
}
Inside my robot.cpp I have this code which gets the two boolean values and then outputs to the console:
void robot::getReturnObject()
{
if(returnObjectDash==true)
{
std::cout<<"Dash\n";
//dir=DOWN;
}
if(returnObjectLine==true)
{
std::cout<<"Line\n";
//dir=DOWN;
}
}
This is my main.cpp
int main()
{
robot r;
while(true)
{
matrix m;
m.robotPosition(r.getX(), r.getY());
m.update(); // vector2D init and draw
m.detection(m.getX(), m.getY());
r.update();
Sleep(250);
}
}
I'm setting the default value of my two boolean variables in my matrix.cpp default constructor to false. When I hit the pause button and debug I seem to be getting two different returns. For my matrix it is returning false, though for my robot it is returning true, it is like my program is making two different variables. If someone could shed some light on this weird behaviour, then please do tell! Thank you
Your program is making two different values because it has two different values. The matrix class apparently has its own Boolean variable, matrix::returnObjectDash, and the robot class has its own variable, robot::returnObjectDash. Setting the variable in one instance of one class has no impact on the variables in any other classes (or any other instances).
You have not provided code to you matrix class, however, judging from void matrix::detection(int x, int y) I assume that you have a method in there, called detection, and that you have declared the same fields returnObjectLine and returnObjectDash.
You are correct in assuming that there are 2 versions of those variables: One of those versions is inside your matrix object, and the other one is inside your robot object.
Not only that, you can (and usually do!) have more than one matrix/robot object. Each of those will have its own separate copy of those variables, and changing one of them will not impact the other ones.
I'm relatively new to C++ and have been trying to troubleshoot this problem for awhile now, but can't figure this out. I have 2 classes, one called Polygon and one called Rectangle. Rectangle is a child class of Polygon. Polygon contains a std::vector<Points> called _points.
I would like my Rectangle constructor to add some Points to _points based on the constructor arguments. That sounded simple enough. However, when I add Points to _points, they seem to get lost outside of the constructor. When I check the size of _points inside the constructor, it gives the right value. However, when I check it back in the main program, right after constructing the Rectangle, it is 0. I think there is something going on under the hood I don't know about. Any ideas on what could be wrong?
Here's some snippets of code I think may help
Polygon.cpp
// This is just for reference, there are a few other classes involved
// but I don't think they should effect this.
Polygon::Polygon()
: Object()
, _lastColor(0,0,0)
, _lastDotColor(.5, .5, .5)
{
_points = vector<Point>();
_colors = vector<RGB>();
_dotColors = vector<RGB>();
_numDotSections = -1;
}
Rectangle.cpp
Rectangle::Rectangle(Point p1, Point p2, RGB lineColor, double dotSeg, RGB dotColor) : Polygon(){
_points.push_back(p1);
// Prints out 1
std::cout << "Point size: " << getPoints() << std::endl;
}
Driver.cpp
Rectangle playerPolygon = Rectangle(Point(1,1,-.75), Point(-1,-1,-.75), RGB(1,1,1));
// Prints 0
cout << "Number of points (Rectangle): " << playerPolygon.getPoints() << endl;
Edit1: Per request, here's the majority of the text for Polygon.cpp
// File imports
#include <GL/glut.h>
#include <iostream>
#include <math.h>
#include "Polygon.h"
using namespace std;
/**
* Default constructor for Polygon. Uses initializer lists
* to setup the different attributes
*/
Polygon::Polygon()
: _lastColor(0,0,0)
, _lastDotColor(.5, .5, .5)
, _numDotSections(-1)
{
}
/**
* Transforms the points of the polygon and draws it on the screen
*
* #param currentWorld a reference to the world the object is in
*/
void Polygon::draw(World* currentWorld){
// Some long and overly complicated method that should not apply here
}
/**
* Adds a point to the polygon
*
* #param point the point to be added
* #param color the color to start at this point
* #param dotColor the dotted line color to start at this point
*/
void Polygon::addPoint(Point point, RGB color, RGB dotColor){
// Add the values to the lists
_points.push_back(point);
_colors.push_back(color);
_dotColors.push_back(dotColor);
// Update the last colors
_lastColor = color;
_lastDotColor = dotColor;
}
/**
* Adds a point to the polygon
*
* #param point the point to be added
* #param color the color to start at this point
*/
void Polygon::addPoint(Point point, RGB color){
// Add the point using the last dotted line color
addPoint(point, color, _lastDotColor);
}
/**
* Adds a point to the polygon
*
* #param point the point to be added
*/
void Polygon::addPoint(Point point){
// Add the point using the last line and dotted line color
addPoint(point, _lastColor, _lastDotColor);
}
/**
* Set the color of the current line
*
* #param color the color of the line to be added
*/
void Polygon::setColor(RGB color){
// Add the color to the list
_colors.back() = color;
// Update the last used color
_lastColor = color;
}
/**
* Set the dotted line color of the current line
*
* #param color the dotted line color to be added
*/
void Polygon::setDotColor(RGB color){
// Add the dotted line color to the list
_dotColors.back() = color;
// Update the last used dotted line color
_lastDotColor = color;
}
/**
* Sets the number of dotted sections for the current shape
*
* #param number the number of dotted sections
*/
void Polygon::setDotSections(int number){
_numDotSections = number;
}
// I just put this in to see if the issue was copying, but this text is never output
// so I don't believe it's being called
Polygon::Polygon(const Polygon& rhs){
std::cout << "Polygon copied" << std::endl;
std::cout << "RHS: " << rhs._points.size() << " LHS: " << getPoints() << std::endl;
}
int Polygon::getPoints(){
return _points.size();
}
I don't see a reason. But I strongly suggest that you delete some lines in the constructors for copying objects. Also, the default constructor is not necessary to be in the constructor initialization list.
// This is just for reference, there are a few other classes involved
// but I don't think they should effect this.
Polygon::Polygon()
: _lastColor(0,0,0)
, _lastDotColor(.5, .5, .5)
, _numDotSections(-1)
{
}
How do you implement getPoints()?
Rectangle playerPolygon = Rectangle(...);
You're invoking the copy constructor here. Did you write a copy constructor? Is it copying _points? If not, that's a bug; and there's really no need to force another copy constructor call in any case. Why not just
Rectangle playerPolygon(...);
? (But do watch out for the vexing parse...)
After sleeping on it, I figured it out! Being used to Java, I had made what I thought were overloaded constructors:
Rectangle::Rectangle(Point p1, Point p2, RGB lineColor, double dotSeg, RGB dotColor) : Polygon(){
// Add some points here
}
Rectangle::Rectangle(Point p1, Point p2){
// Supposed to call the first constructor
Rectangle(p1, p2, RGB(), -1, RGB());
}
Rectangle::Rectangle(Point p1, Point p2, RGB lineColor){
// Supposed to call the first constructor
Rectangle(p1, p2, lineColor, -1, lineColor);
}
But then I tried using the main constructor in my program and it worked! After doing a bit of research, it turns out that constructors cannot be overloaded like this. When a constructor other than the original one is called, it creates a new Rectangle with the points, then destructs it right away because it's not set equal to anything and returns a new rectangle without the points.
I found the easiest way around this is to use default parameters, so I have the same functionality
Rectangle(Point p1, Point p2, RGB lineColor = RGB(), double dotSeg = -1, RGB dotColor = RGB());
I suppose this would have been caught if I put the entire code in there right away, but thanks for all the help and suggestions!
A wild guess: Rectangle inherits from Polygon, and the Rectangle class declares a second member variable named _points that hides the base class version. Rectangle's constructor then adds some elements to Rectangle::_points, and some other function later checks the size of Polygon::_points and finds none.
If this is the case, just take away the declaration of _points in Rectangle. It needs to use the base class version, either directly if Polygon::_points is accessible (public or protected), or via accessor functions.
A few hints that don't answer your question, but nonetheless:
I'm not sure why you derive Rectangle from Polygon. Unless you plan on taking advantage of polymorphism with the two types then it's not necessary and can even lead to incorrect code. The same holds for deriving Polygon from Object.
Don't use names that start with an underscore. The standard reserves this sort of names for implementors.
There's no need to explicitly initialize members with their default values. The compiler does that for you. For example, the statement _points = vector<Point>(); in the default Polygon constructor is redundant. Also, the call to the default constructor of Object() in that same Polygon constructor is redundant.
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.