"First, solve the problem.
Then, write the code."
John Johnson
Cpp/Qt

catchTheBottle

cuteHang
zamknięty:
styczeń 2010
zleceniodawca:
projekt autorski
Opis:

Prosta gra polegająca na przejściu po trawie do butelki. Głównym bohaterem jestem ja a głównej nagrody nie ma żadnej ;)

A to praktycznie cały kod tej prościutkiej aplikacji:

#include 
#include 
#include 

#include "gra.h"

Gra::Gra(QWidget *parent) : QWidget(parent) {
    setMinimumSize(640, 480);
    setMaximumSize(640, 480);

    x=100;
    y=100;

    zwyciestwo = false;

    this->installEventFilter(this);

    QMessageBox::information(0, "Sterowanie:", "Użyj strzałek na klawiaturze ;)", QMessageBox::Ok, QMessageBox::Ok);

}

void Gra::paintEvent(QPaintEvent *) {
     QStyleOption styl;
     QPainter painter(this);

     styl.init(this);
     setStyleSheet("background-image: url(:/bg)");
     style()->drawPrimitive(QStyle::PE_Widget, &styl, &painter, this);
     this->rysujGlowe(painter);
     painter.setPen(Qt::NoPen);
     painter.drawPixmap(300, 300, 20, 40, QPixmap(":/beer"));
     if( zwyciestwo )
         painter.drawPixmap(120, 110, 400, 260, QPixmap(":/win"));

 }

void Gra::rysujGlowe(QPainter &painter) {
    painter.drawPixmap(this->glowaRect(), QPixmap(":/ja"));
    QRect glowa = this->glowaRect();
    if (glowa.intersects(this->butelkaRect()))
	zwyciestwo = true;
}

QRect Gra::glowaRect() const {
    QRect glowa(0, 0, 40, 40);
    glowa.moveCenter(QPoint(x, y));
    return glowa;
}

QRect Gra::butelkaRect() const {
    QRect butelka(300, 300, 20, 40);
    return butelka;
}

bool Gra::eventFilter(QObject *obj, QEvent *ev) {
    if ( ev->type() == QEvent::KeyPress && !zwyciestwo) {

	 QRegion region = this->glowaRect();
	 QRect glowaR = this->glowaRect();

         QKeyEvent *keyEvent = static_cast(ev);

	 if( glowaR.x()>20 && glowaR.x()width()-60  && glowaR.y()>20 && glowaR.y()height()-60) {
             if( keyEvent->key() == 16777235 ) { //góra
                 y -= 20;
		 region.unite(glowaR);
             } else if( keyEvent->key() == 16777237 ) { //dół
                 y += 20;
		 region.unite(glowaR);
             }else if( keyEvent->key() == 16777234 ) { //lewo
                 x -= 20;
		 region.unite(glowaR);
             }else if( keyEvent->key() == 16777236 ) { //prawo
                 x += 20;
		 region.unite(glowaR);
             }
	     update(region);
	 }
        return true;
     } else {
         return QObject::eventFilter(obj, ev);
     }
}
do góry