#ifndef SNAKE_H#define SNAKE_H#include <QObject>#include <QQueue>#include <QPoint>class QPolygon;class Snake : public QObject{ Q_OBJECTpublic: enum Direction {Left, Right, Top, Bottom}; Snake(); ~Snake(); QPoint getTail(); QPoint getHead(); void setHead(QPoint&); int getCountBlocks(); int getLength(); const QPolygon* getBlockPositions(); Direction getDirection(); void Reset(); void MoveToLeft(); void MoveToRight(); void MoveToTop(); void MoveToBottom(); bool Move(); void AddBlock(); void ChangeDirection(Direction);signals: void onBlockAddFinish(QPoint);private: QQueue<QPoint>* addedBlocks; QPolygon* blockPositions; Direction direction; void MoveBlocks(); void CreateStandartSnake(); bool isCollisionOfSnake(); void Initialize();};#endif // SNAKE_H
#include "snake.h"#include <QQueue>#include <QPoint>#include <QPolygon>#include <QMessageBox>Snake::Snake(){ Initialize();}void Snake::Initialize(){ addedBlocks = new QQueue<QPoint>(); blockPositions = new QPolygon(); CreateStandartSnake(); direction = Right;}Snake::~Snake(){ delete addedBlocks; delete blockPositions;}void Snake::MoveBlocks(){ bool newBlock = false; //time to add new block to snake if(addedBlocks->count() > 0 && getTail() == addedBlocks->head()) { newBlock = true; } for(int i = getLength() - 1; i != 0; i--) { blockPositions->setPoint(i, blockPositions->point(i-1)); } if (newBlock) { blockPositions->append(addedBlocks->dequeue()); emit this->onBlockAddFinish(getTail()); }}void Snake::Reset(){ blockPositions->clear(); addedBlocks->clear(); Initialize();}void Snake::CreateStandartSnake(){ blockPositions->append(QPoint(2,0)); blockPositions->append(QPoint(1,0)); blockPositions->append(QPoint(0,0));}bool Snake::Move(){ MoveBlocks(); switch (direction) { case Left: MoveToLeft(); break; case Right: MoveToRight(); break; case Bottom: MoveToBottom(); break; case Top: MoveToTop(); break; } return isCollisionOfSnake();}bool Snake::isCollisionOfSnake(){ QPoint head = getHead(); for (int i = 1; i < getLength(); i++) { if (head == blockPositions->point(i)) { return false; } } return true;}void Snake::ChangeDirection(Direction direct){ if ((direction == Left && direct == Right) || (direction == Right && direct == Left)) { return; } if ((direction == Top && direct == Bottom) || (direction == Bottom && direct == Top)) { return; } direction = direct;}void Snake::setHead(QPoint &point){ blockPositions->setPoint(0,point);}void Snake::AddBlock(){ addedBlocks->enqueue(getHead());}void Snake::MoveToLeft(){ QPoint head = getHead(); head.rx()--; blockPositions->setPoint(0,head);}void Snake::MoveToRight(){ QPoint head = getHead(); head.rx()++; blockPositions->setPoint(0,head);}void Snake::MoveToTop(){ QPoint head = getHead(); head.ry()--; blockPositions->setPoint(0,head);}void Snake::MoveToBottom(){ QPoint head = getHead(); head.ry()++; blockPositions->setPoint(0, head);}QPoint Snake::getTail(){ return blockPositions->point(getLength()-1);}QPoint Snake::getHead(){ return blockPositions->point(0);}int Snake::getCountBlocks(){ return blockPositions->count() + addedBlocks->count();}int Snake::getLength(){ return blockPositions->count();}const QPolygon* Snake::getBlockPositions(){ return blockPositions;}Snake::Direction Snake::getDirection(){ return direction;}
#ifndef GAME_H#define GAME_H#include <QObject>#include "snake.h"#include "IBlockDraw.h"#include <QQueue>#include <QKeyEvent>#include <QBrush>#include "statistic.h"class QPoint;class QTimer;class Game : public QObject{ Q_OBJECTpublic: enum Speed {Slow = 200, Medium = 100, Fast = 50}; Game(int width, int height, IBlockDraw* BlockDraw); ~Game(); int getPoints(); void Start(); void End(); void setSnakeColor(const QBrush&); void setBlockColor(const QBrush&); void setBackgroundColor(const QBrush&); Statistic* getStatistic(); void KeyPressHandle(QKeyEvent *); Speed getSpeed(); void setSpeed(Speed); Snake* snake; void SaveResult(QString&);protected: bool isNewBlock(); void AddNewBlock();private: int points; QTimer* moveTimer; QQueue<Snake::Direction>* pressedDirections; QPoint* block; QBrush* backgroundColor; QBrush* snakeColor; QBrush* blockColor; IBlockDraw* blockDraw; Statistic statistic; int eatPoints; int width; int height; Speed speed; bool Move(); void NewBlock(); void ClearBlock(const QPoint&); void DrawSnakeBlock(const QPoint&); void DrawBlock(); void Draw(const QPoint&, const QBrush&); void DrawSnake(); void DrawBackground(); void setPoints(int points); void AddPoints(int); void CheckSnakeOutOfMap();public slots: void MoveByTime(); void AddSnakeBlockFinish(const QPoint&);signals: void onPointsChanged(int points); void onGameOver(); void onSnakeBlockCountChanged(int legth);};#endif // GAME_H
#include "game.h"#include <QPoint>#include <QTimer>#include <QBrush>#include <QQueue>#include "snake.h"#include <QDateTime>Game::Game(int width, int height, IBlockDraw *BlockDraw){ QString path("statistic.db"); statistic = Statistic(path); eatPoints = 100; this->width = width; this->height = height; blockDraw = BlockDraw; moveTimer = new QTimer(this); moveTimer->setInterval(Slow); moveTimer->stop(); snake = new Snake(); backgroundColor = new QBrush(Qt::gray); snakeColor = new QBrush(Qt::blue); blockColor = new QBrush(Qt::red); pressedDirections = new QQueue<Snake::Direction>(); QObject::connect(moveTimer, SIGNAL(timeout()), this, SLOT(MoveByTime())); QObject::connect(snake, SIGNAL(onBlockAddFinish(QPoint)), this, SLOT(AddSnakeBlockFinish(const QPoint&)));}Game::~Game(){ delete snake; delete moveTimer; delete pressedDirections; delete block; delete backgroundColor; delete blockColor; delete snakeColor; delete blockDraw;}void Game::Start(){ snake->Reset(); DrawBackground(); DrawSnake(); points = 0; moveTimer->start(); //emit onSnakeBlockCountChanged(snake->getCountBlocks()); NewBlock();}void Game::End(){ moveTimer->stop(); //clearing old directions for new game pressedDirections->clear(); pressedDirections = new QQueue<Snake::Direction>(); emit onGameOver();}bool Game::isNewBlock(){ QPoint head = snake->getHead(); if(head.x()== block->x() && head.y() == block->y()) { return true; } return false;}void Game::AddNewBlock(){ snake->AddBlock(); AddPoints(eatPoints); NewBlock(); emit onSnakeBlockCountChanged(snake->getCountBlocks());}void Game::MoveByTime(){ Move();}bool Game::Move(){ if (pressedDirections->count() > 0) { snake->ChangeDirection(pressedDirections->dequeue()); } ClearBlock(snake->getTail()); if(!snake->Move()) { End(); return false; } CheckSnakeOutOfMap(); if(isNewBlock()) { AddNewBlock(); } DrawSnakeBlock(snake->getHead()); return true;}void Game::NewBlock(){ bool contains = false; qsrand(QDateTime::currentMSecsSinceEpoch()); //checking that place new block not on snake do { contains = false; block = new QPoint(qrand() % width, qrand() % height); if (snake->getBlockPositions()->contains(*block)) { contains = true; delete block; } } while(contains); DrawBlock();}void Game::Draw(const QPoint& point, const QBrush& color){ int x = point.x() * blockDraw->getSize();//+1; int y = point.y() * blockDraw->getSize();//+1; QPoint p(x,y); blockDraw->DrawBlock(p, color);}void Game::ClearBlock(const QPoint& p){ Draw(p, *backgroundColor);}void Game::DrawSnakeBlock(const QPoint& p){ Draw(p, *snakeColor);}void Game::DrawBlock(){ Draw(*block, *blockColor);}void Game::AddSnakeBlockFinish(const QPoint& block){ DrawSnakeBlock(snake->getTail());}void Game::DrawSnake(){ const QPolygon* snakeBlocks = snake->getBlockPositions(); for(int i=0; i<snake->getCountBlocks(); i++) { DrawSnakeBlock(snakeBlocks->point(i)); }}void Game::DrawBackground(){ QPoint point; for (int i = 0; i < width+1; i++) { for (int j = 0; j < height+1; j++) { point.rx()=i; point.ry()=j; Draw(point, *backgroundColor); } }}void Game::setPoints(int points){ this->points = points; emit onPointsChanged(points);}void Game::AddPoints(int points){ this->points+=points; emit onPointsChanged(this->points);}void Game::setSpeed(Game::Speed sp){ speed = sp; moveTimer->setInterval(speed);}Game::Speed Game::getSpeed(){ return speed;}void Game::KeyPressHandle(QKeyEvent* e){ switch (e->key()) { case Qt::Key_Up: case Qt::Key_W: pressedDirections->enqueue(Snake::Top); break; case Qt::Key_Left: case Qt::Key_A: pressedDirections->enqueue(Snake::Left); break; case Qt::Key_Down: case Qt::Key_S: pressedDirections->enqueue(Snake::Bottom); break; case Qt::Key_Right: case Qt::Key_D: pressedDirections->enqueue(Snake::Right); break; }}void Game::CheckSnakeOutOfMap(){ QPoint head = snake->getHead(); if(head.x() > width) { QPoint* point = new QPoint(0,head.y()); snake->setHead(*point); } if(head.x() < 0) { QPoint* point = new QPoint(width,head.y()); snake->setHead(*point); } if(head.y() > height) { QPoint* point = new QPoint(head.x(),0); snake->setHead(*point); } if(head.y() < 0) { QPoint* point = new QPoint(head.x(),height); snake->setHead(*point); }}Statistic * Game::getStatistic(){ return &statistic;}void Game::setSnakeColor(const QBrush& color){ *snakeColor = color;}void Game::setBlockColor(const QBrush& color){ *blockColor = color;}void Game::setBackgroundColor(const QBrush& color){ *backgroundColor = color;}void Game::SaveResult(QString &name){ statistic.AddRecord(name, points, QDate::currentDate());}
class A{B b(args)}
void foo(QString&);void main(){ foo(QString(""));}
C++ (Qt)class MyClass {public: MyClass( const QString & txt = "" ) : mName(txt) {} QString mName;}; class MyClass2 {public: MyClass( const QString & txt = "" ) : mStruct(str) {} MyStruct mStruct;};
C++ (Qt)void foo(const QString & str = "");}
class MyClass {public: MyClass( const QString & txt = "" ) : mName(txt) {} QString mName;}; class MyClass2 {public: MyClass( const QString & txt = "" ) : mStruct(str) {} MyStruct mStruct;};
class MyClass2{public: MyClass(const QString& text = ""):mClass(str){}MyClass mClass;}
class MyClass{ public: MyClass(int score): score(score){} MyClass():score(0){} int score;}class MyClass2{ public MyClass2(QString& s = ""):myStr(s){}QString myStr;MyClass mClass;}
class Foo{public: Foo(const QString&s):str(s){} QString str;};class Foo2{public: Foo2(){ foo = Foo(QString("foo")); } Foo foo;};
Foo2():foo(QString("foo")){...}
C++ (Qt)class Foo2{public: Foo2() : foo(QString("foo"))// Foo2() : foo("foo") // можно и так { } Foo foo;};
void f(Type* t){};void main(){f(new Type());}
#include <QtCore/QCoreApplication>#include <QDebug>#include "windows.h"class Record{public: int x;//т.к. тест, то всеравно где Record() { x=3; qDebug("record created"); } ~Record() { qDebug("record destructed"); } Record(const Record& r) { qDebug() << "copy constructor"; }};static Record* r;//будем хранить ссылку передаваемую в функциюvoid Test(const Record& rec){ qDebug("Test start"); //qDebug()<<"&rec="<<&rec; if(&(*r) != &rec)//если новая ссылка не равна старой, выводим и присваиваем { qDebug()<<"&rec="<<&rec; r = const_cast<Record*>(&rec); } QString s("ldgjfdklgjdfg"), ss("fsfsdfdsfsdf"); for (int i = 0; i < 10000000; i++) { s+=ss;//что бы было какое то время для удаления временного обьекта если должен удаляться } Sleep(1000);//с той же целью qDebug("Test end");}int main(int argc, char *argv[]){ QCoreApplication a(argc, argv); for(int i=0; i<10; i++) { Test(Record()); Sleep(1000);//время что бы могла освободиться память временных обьектов и т.п. } return a.exec();}
C++ (Qt)foo(new Record()); // foo( const Record * );
C++ (Qt)fooRef(Record()); // fooRef( const Record & );
На стеке отвели место для безымянного Record и вызвали его конструктор. Возможно конструктор там какие-то члены создал в куче - то его дело. Толкнули опять-таки адрес Record на стек и вызвали ф-цию. Ф-ция отработала и вернула упрвление. Вызываем деструктор Record (если есть). Выравниваем стек. Готовченко.