1 /* Evil Plumber is a small puzzle game.
2 Copyright (C) 2010 Marja Hassinen
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include <QTableWidget>
21 #include <QListWidget>
23 #include <QPushButton>
24 #include <QApplication>
29 const Piece* findPiece(PieceType type, int rotation)
31 static QHash<QPair<PieceType, int>, const Piece*> pieceCache;
33 // Fill the cache on the first run
34 if (pieceCache.size() == 0) {
35 for (int i = 0; ppieces[i].type != PiecesEnd; ++i)
36 pieceCache.insert(QPair<PieceType, int>(ppieces[i].type, ppieces[i].rotation), &ppieces[i]);
38 QPair<PieceType, int> key(type, rotation);
39 if (pieceCache.contains(key))
40 return pieceCache[key];
45 QString pieceToIconId(const Piece* piece, bool flow1 = false, bool flow2 = false)
47 QString fileName = QString(IMGDIR) + "/" + QString::number(piece->type) + "_" + QString::number(piece->rotation);
49 fileName += (QString("_flow_") + (flow1? "1" : "0") + (flow2? "1" : "0"));
52 //qDebug() << "need: " << fileName;
53 return fileName + ".png";
56 int flowCount(const Piece* piece)
58 // How many times the liquid can flow through this pre-placed
61 for (int i = 0; i < 4; ++i) {
62 if (piece->flows[i] != DirNone) {
69 Direction flowsTo(const Piece* piece, Direction flowFrom)
71 //qDebug() << piece->flows[0];
72 //qDebug() << piece->flows[1];
73 //qDebug() << piece->flows[2];
74 //qDebug() << piece->flows[3];
75 //qDebug() << "check" << flowFrom;
76 if (piece->flows[0] == flowFrom)
77 return piece->flows[1];
78 if (piece->flows[1] == flowFrom)
79 return piece->flows[0];
80 if (piece->flows[2] == flowFrom)
81 return piece->flows[3];
82 if (piece->flows[3] == flowFrom)
83 return piece->flows[2];
87 GameField::GameField(QTableWidget* ui)
88 : fieldUi(ui), field(0), rows(0), cols(0)
90 connect(fieldUi, SIGNAL(cellClicked(int, int)), this, SIGNAL(cellClicked(int, int)));
91 fieldUi->setContentsMargins(0, 0, 0, 0);
94 void GameField::initGame(int rows_, int cols_, int count, PrePlacedPiece* prePlaced)
102 field = new PlacedPiece[rows*cols];
104 for (int i = 0; i < rows*cols; ++i) {
105 field[i].piece = ppieces;
106 field[i].fixed = false;
107 field[i].flow[0] = false;
108 field[i].flow[1] = false;
112 fieldUi->setRowCount(rows);
113 fieldUi->setColumnCount(cols);
115 for (int i = 0; i < rows; ++i)
116 fieldUi->setRowHeight(i, 72);
118 for (int c = 0; c < cols; ++c) {
119 fieldUi->setColumnWidth(c, 72);
120 for (int r = 0; r < rows; ++r) {
121 QModelIndex index = fieldUi->model()->index(r, c);
122 fieldUi->setIndexWidget(index, new QLabel(""));
126 // Set pre-placed pieces
127 for (int i = 0; i < count; ++i) {
128 setPiece(prePlaced[i].row, prePlaced[i].col, prePlaced[i].piece, true);
132 int GameField::toIndex(int row, int col)
134 return row * cols + col;
137 bool GameField::setPiece(int row, int col, const Piece* piece, bool fixed)
139 qDebug() << "set piece" << row << col;
141 if (row < 0 || row >= rows || col < 0 || col >= cols) {
142 qWarning() << "Invalid piece index";
146 int index = toIndex(row, col);
147 if (field[index].piece->type == PieceNone) {
148 qDebug() << "really setting";
149 field[index].piece = piece;
150 field[index].fixed = fixed;
152 QString iconId = pieceToIconId(piece);
153 QModelIndex index = fieldUi->model()->index(row, col);
154 QLabel* label = (QLabel*)fieldUi->indexWidget(index);
155 label->setPixmap(QPixmap(iconId));
162 const Piece* GameField::pieceAt(int row, int col)
164 if (row < 0 || row >= rows || col < 0 || col >= cols) {
165 qWarning() << "Invalid piece index";
169 int index = toIndex(row, col);
170 return field[index].piece;
173 bool GameField::isPrePlaced(int row, int col)
175 if (row < 0 || row >= rows || col < 0 || col >= cols) {
176 qWarning() << "Invalid piece index";
180 int index = toIndex(row, col);
181 return field[index].fixed;
184 void GameField::indicateFlow(int row, int col, Direction dir)
186 // Indicate the flow: fill the piece in question with the
187 // liquid. (The piece can also be an empty one, or an illegal
189 qDebug() << "ind flow" << row << col << dir;
190 if (row < 0 || col < 0 || row >= rows || col >= cols) {
193 if (dir == DirDone || dir == DirFailed || dir == DirPassed) {
194 // No need to indicate these pseudo-directions
198 int index = toIndex(row, col);
199 if (dir != DirNone && (field[index].piece->flows[0] == dir || field[index].piece->flows[1] == dir)) {
200 field[index].flow[0] = true;
202 else if (dir != DirNone && (field[index].piece->flows[2] == dir || field[index].piece->flows[3] == dir)) {
203 field[index].flow[1] = true;
205 else if (dir == DirNone) {
206 // Flowing to a pipe from a wrong direction -> A hack to get
207 // the correct icon (same as an empty square flooded)
208 field[index].piece = ppieces;
209 field[index].flow[0] = true;
210 field[index].flow[1] = false;
213 qWarning() << "Indicate flow: illegal direction" << row << col << dir;
217 QString iconId = pieceToIconId(field[index].piece, field[index].flow[0], field[index].flow[1]);
218 qDebug() << "icon id" << iconId;
219 QModelIndex mIndex = fieldUi->model()->index(row, col);
220 QLabel* label = (QLabel*)fieldUi->indexWidget(mIndex);
222 label->setPixmap(QPixmap(iconId));
225 AvailablePieces::AvailablePieces(QTableWidget* ui)
228 connect(pieceUi, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(onItemClicked(QTableWidgetItem*)));
232 qDebug() << pieceUi->rowCount() << pieceUi->columnCount();
234 for (int i = 0; i < 2; ++i)
235 pieceUi->setColumnWidth(i, 120);
237 for (int i = 0; i < 4; ++i)
238 pieceUi->setRowHeight(i, 70);
240 for (int i = 0; ppieces[i].type != PiecesEnd; ++i) {
241 if (ppieces[i].userCanAdd == false) continue;
243 //qDebug() << ppieces[i].type << ppieces[i].rotation;
244 QString fileName = pieceToIconId(&(ppieces[i]));
246 QTableWidgetItem* item = new QTableWidgetItem(QIcon(fileName), "0", QTableWidgetItem::UserType + pieceToId(&(ppieces[i])));
248 pieceUi->setItem(ppieces[i].uiRow, ppieces[i].uiColumn, item);
252 int AvailablePieces::pieceToId(const Piece* piece)
254 return piece->type * 4 + piece->rotation/90;
257 const Piece* AvailablePieces::idToPiece(int id)
259 int rotation = (id % 4)*90;
260 PieceType type = (PieceType)(id / 4);
261 return findPiece(type, rotation);
264 void AvailablePieces::initGame(int count, AvailablePiece* pieces)
266 for (int i = 0; ppieces[i].type != PiecesEnd; ++i) {
267 if (ppieces[i].userCanAdd == false) continue;
268 pieceCounts.insert(&ppieces[i], 0);
269 pieceUi->item(ppieces[i].uiRow, ppieces[i].uiColumn)->setText(QString::number(0));
272 for (int i = 0; i < count; ++i) {
273 pieceCounts.insert(pieces[i].piece, pieces[i].count);
274 pieceUi->item(pieces[i].piece->uiRow, pieces[i].piece->uiColumn)->setText(QString::number(pieces[i].count));
276 pieceUi->clearSelection();
279 void AvailablePieces::onItemClicked(QTableWidgetItem* item)
281 qDebug() << "piece clicked";
282 int id = item->type() - QTableWidgetItem::UserType;
284 const Piece* piece = idToPiece(id);
285 if (piece->type != PieceNone && pieceCounts[piece] > 0) {
286 emit validPieceSelected(piece);
289 emit invalidPieceSelected();
292 void AvailablePieces::onPieceUsed(const Piece* piece)
294 pieceCounts[piece]--;
295 pieceUi->item(piece->uiRow, piece->uiColumn)->setText(QString::number(pieceCounts[piece]));
297 // TODO: perhaps clear the selection
298 if (pieceCounts[piece] == 0)
299 emit invalidPieceSelected();
302 GameController::GameController(AvailablePieces* pieceUi, GameField* fieldUi,
303 QLabel* timeLabel, QPushButton* doneButton)
304 : pieceUi(pieceUi), fieldUi(fieldUi),
305 timeLabel(timeLabel), doneButton(doneButton),
306 currentPiece(ppieces), rows(0), cols(0), timeLeft(0), levelRunning(false), neededFlow(0),
307 startRow(0), startCol(0), startDir(DirNone), flowRow(0), flowCol(0), flowDir(DirNone), flowPreplaced(0), flowScore(0)
309 connect(fieldUi, SIGNAL(cellClicked(int, int)), this, SLOT(onCellClicked(int, int)));
310 connect(pieceUi, SIGNAL(invalidPieceSelected()),
311 this, SLOT(onInvalidPieceSelected()));
312 connect(pieceUi, SIGNAL(validPieceSelected(const Piece*)),
313 this, SLOT(onValidPieceSelected(const Piece*)));
315 connect(this, SIGNAL(pieceUsed(const Piece*)), pieceUi, SLOT(onPieceUsed(const Piece*)));
317 connect(doneButton, SIGNAL(clicked()), this, SLOT(levelEnds()));
319 // Setup the timer, but don't start it yet
320 timer.setInterval(1000);
321 timer.setSingleShot(false);
322 connect(&timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
323 timeLabel->setText("");
325 flowTimer.setInterval(500);
326 flowTimer.setSingleShot(false);
327 connect(&flowTimer, SIGNAL(timeout()), this, SLOT(computeFlow()));
330 void GameController::startLevel(QString fileName)
332 // TODO: read the data while the user is reading the
335 // Read data about pre-placed pieces and available pieces from a
337 QFile file(fileName);
339 qFatal("Error reading game file: doesn't exist");
341 file.open(QIODevice::ReadOnly);
342 QTextStream gameData(&file);
346 qDebug() << rows << cols;
347 if (rows < 2 || rows > 10 || cols < 2 || cols > 10)
348 qFatal("Error reading game file: rows and cols");
351 int prePlacedCount = 0;
352 gameData >> prePlacedCount;
353 if (prePlacedCount < 2 || prePlacedCount > 100)
354 qFatal("Error reading game file: piece count");
356 PrePlacedPiece* prePlaced = new PrePlacedPiece[prePlacedCount];
357 for (int i = 0; i < prePlacedCount; ++i) {
360 if (type < 0 || type >= PiecesEnd)
361 qFatal("Error reading game file: type of pre-placed piece");
364 gameData >> rotation;
365 if (rotation != 0 && rotation != 90 && rotation != 180 && rotation != 270)
366 qFatal("Error reading game file: rotation of pre-placed piece");
368 prePlaced[i].piece = findPiece((PieceType)type, rotation);
369 if (!prePlaced[i].piece)
370 qFatal("Error reading game file: invalid pre-placed piece");
372 // Record that the liquid must flow through this pre-placed
374 neededFlow += flowCount(prePlaced[i].piece);
376 gameData >> prePlaced[i].row;
377 gameData >> prePlaced[i].col;
378 if (prePlaced[i].row < 0 || prePlaced[i].row >= rows ||
379 prePlaced[i].col < 0 || prePlaced[i].col >= cols)
380 qFatal("Error reading game file: piece position");
382 if (prePlaced[i].piece->type == PieceStart) {
383 startRow = prePlaced[i].row;
384 startCol = prePlaced[i].col;
385 startDir = prePlaced[i].piece->flows[0];
388 fieldUi->initGame(rows, cols, prePlacedCount, prePlaced);
391 int availableCount = 0;
392 gameData >> availableCount;
393 if (availableCount < 2 || availableCount >= noPieces)
394 qFatal("Error reading game file: no of pieeces");
396 AvailablePiece* availablePieces = new AvailablePiece[availableCount];
397 for (int i = 0; i < availableCount; ++i) {
400 if (ix < 0 || ix >= noPieces)
401 qFatal("Error reading game file: piece index");
402 availablePieces[i].piece = &ppieces[ix];
403 gameData >> availablePieces[i].count;
404 if (availablePieces[i].count < 0 || availablePieces[i].count > 100)
405 qFatal("Error reading game file: piece count");
407 pieceUi->initGame(availableCount, availablePieces);
408 delete[] availablePieces;
410 gameData >> timeLeft;
412 qFatal("Error reading game file: time left");
413 timeLabel->setText(QString::number(timeLeft));
415 // Clear piece selection
416 onInvalidPieceSelected();
418 doneButton->setEnabled(true);
424 void GameController::onTimeout()
427 timeLabel->setText(QString::number(timeLeft));
434 void GameController::onCellClicked(int row, int column)
436 qDebug() << "clicked: " << row << column;
437 if (!levelRunning) return;
438 if (currentPiece->type == PieceNone) return;
439 if (fieldUi->setPiece(row, column, currentPiece))
440 emit pieceUsed(currentPiece);
443 void GameController::onValidPieceSelected(const Piece* piece)
445 qDebug() << "selected: " << piece->type << piece->rotation;
446 currentPiece = piece;
449 void GameController::onInvalidPieceSelected()
451 currentPiece = ppieces;
454 void GameController::levelEnds()
456 if (!levelRunning) return;
458 doneButton->setEnabled(false);
459 levelRunning = false;
462 // Initiate computing the flow
468 flowTimer.setInterval(500);
472 void GameController::computeFlow()
475 // Where the flow currently is
476 // and which direction the flow goes after that piece
477 fieldUi->indicateFlow(flowRow, flowCol, flowDir);
479 if (flowDir == DirFailed) {
485 if (flowDir == DirPassed) {
487 emit levelPassed(flowScore);
490 if (flowDir == DirNone) {
491 // This square contained no pipe or an incompatible pipe. Get
492 // some more time, so that the user sees the failure before we
495 flowTimer.setInterval(1000);
500 if (flowDir == DirDone) {
501 // Again, give the user some time...
502 if (flowPreplaced < neededFlow) {
504 // TODO: indicate which pipes were missing
509 flowTimer.setInterval(1000);
513 // Compute where it flows next
514 if (flowDir == DirRight) {
518 else if (flowDir == DirLeft) {
522 else if (flowDir == DirUp) {
526 else if (flowDir == DirDown) {
531 if (flowRow < 0 || flowCol < 0 || flowRow >= rows || flowCol >= cols) {
534 flowTimer.setInterval(1000);
538 // Now we know the next piece and where the flow comes *from*
539 qDebug() << "flow to" << flowRow << flowCol;
541 // Check which piece is there
542 const Piece* piece = fieldUi->pieceAt(flowRow, flowCol);
543 qDebug() << "there is" << piece->type << piece->rotation;
544 flowDir = flowsTo(piece, flowDir);
545 // If the piece was pre-placed, record that the liquid has
546 // flown through it once
547 if (fieldUi->isPrePlaced(flowRow, flowCol))
551 LevelSwitcher::LevelSwitcher(GameController* gameController,
552 QWidget* levelWidget, QListWidget* levelList,
553 QPushButton* levelStartButton,
554 QWidget* startWidget, QLabel* startTitle,
555 QLabel* startLabel, QPushButton* startButton,
556 QLabel* levelLabel, QLabel* scoreLabel,
557 QStringList collections)
558 : gameController(gameController),
559 levelWidget(levelWidget), levelList(levelList), levelStartButton(levelStartButton),
560 startWidget(startWidget), startTitle(startTitle), startLabel(startLabel), startButton(startButton),
561 levelLabel(levelLabel), scoreLabel(scoreLabel),
562 curColl(""), level(0), totalScore(0)
564 connect(levelStartButton, SIGNAL(clicked()), this, SLOT(onLevelCollectionChosen()));
566 connect(startButton, SIGNAL(clicked()), this, SLOT(onStartClicked()));
567 connect(gameController, SIGNAL(levelPassed(int)), this, SLOT(onLevelPassed(int)));
568 connect(gameController, SIGNAL(levelFailed()), this, SLOT(onLevelFailed()));
570 readLevelCollections(collections);
571 chooseLevelCollection();
574 void LevelSwitcher::chooseLevelCollection()
578 foreach (const QString& collection, levelCollections.keys()) {
579 QListWidgetItem *newItem = new QListWidgetItem();
581 // Check how many levels the user has already passed
583 if (savedGames.contains(collection)) {
584 passed = savedGames[collection];
587 if (levelCollections.contains(collection)) {
588 total = levelCollections[collection].size();
591 newItem->setText(collection + " \tPassed: " +
592 QString::number(passed) + " / " + QString::number(total));
593 levelList->addItem(newItem); // transfers ownership
594 if (first && passed < total) {
595 levelList->setCurrentItem(newItem);
602 void LevelSwitcher::onLevelCollectionChosen()
605 curColl = levelList->currentItem()->text().split(" ").first();
607 if (levelCollections.contains(curColl)) {
608 levels = levelCollections[curColl];
611 qFatal("Error choosing a level collection: unrecognized");
614 // Go to the level the user has not yet passed
615 if (savedGames.contains(curColl)) {
616 qDebug() << "going to saved level" << savedGames[curColl];
617 level = savedGames[curColl];
618 if (level >= levels.size()) {
624 startTitle->setText("Starting a new game.");
625 scoreLabel->setText("0");
629 void LevelSwitcher::onStartClicked()
632 levelLabel->setText(QString::number(level+1));
633 gameController->startLevel(QString(LEVDIR) + "/" + levels[level] + ".dat");
636 void LevelSwitcher::initiateLevel()
638 if (level >= levels.size()) {
639 qWarning() << "Level index too large";
643 QFile file(QString(LEVDIR) + "/" + levels[level] + ".leg");
645 qFatal("Error reading game file: doesn't exist");
646 file.open(QIODevice::ReadOnly);
647 QTextStream gameData(&file);
649 QString introText = gameData.readLine();
650 introText.replace("IMGDIR", IMGDIR);
652 // The start button might be connected to "chooseLevelCollection"
653 startButton->disconnect();
654 connect(startButton, SIGNAL(clicked()), this, SLOT(onStartClicked()));
655 startLabel->setText(introText);
659 void LevelSwitcher::onLevelPassed(int score)
662 scoreLabel->setText(QString::number(score));
664 if (level < levels.size() - 1) {
666 startTitle->setText(QString("Level ") + QString::number(level) + QString(" passed, proceeding to level ") + QString::number(level+1));
667 // Record that the level has been passed, so that the user can
669 savedGames.insert(curColl, level);
675 startTitle->setText(QString("All levels passed. Score: ") + QString::number(score));
676 startLabel->setText("Start a new game?");
677 startButton->disconnect();
678 connect(startButton, SIGNAL(clicked()), this, SLOT(chooseLevelCollection()));
679 // Record that all levels have been passed
680 savedGames.insert(curColl, levels.size());
688 void LevelSwitcher::onLevelFailed()
690 startTitle->setText(QString("Level ") + QString::number(level+1) + QString(" failed, try again!"));
694 void LevelSwitcher::readSavedGames()
696 QFile file(QDir::homePath() + "/.evilplumber");
697 if (!file.exists()) {
698 qWarning() << "Save file doesn't exist";
701 file.open(QIODevice::ReadOnly);
702 QTextStream saveData(&file);
703 QString collection = 0;
705 while (!saveData.atEnd()) {
706 saveData >> collection;
708 qDebug() << "Got saved game: " << collection << level;
709 if (collection != "")
710 savedGames.insert(collection, level);
715 void LevelSwitcher::readLevelCollections(QStringList collections)
717 foreach (const QString& coll, collections) {
718 QFile file(QString(LEVDIR) + "/" + coll + ".dat");
719 qDebug() << "Trying to read" << file.fileName();
721 qFatal("Error reading level collection: doesn't exist");
722 file.open(QIODevice::ReadOnly);
723 QTextStream levelData(&file);
724 QStringList readLevels;
725 while (!levelData.atEnd())
726 readLevels << levelData.readLine();
728 levelCollections.insert(coll, readLevels);
733 void LevelSwitcher::writeSavedGames()
735 QFile file(QDir::homePath() + "/.evilplumber");
736 file.open(QIODevice::Truncate | QIODevice::WriteOnly);
737 QTextStream saveData(&file);
738 foreach (const QString& collection, savedGames.keys()) {
739 qDebug() << "writing" << collection << savedGames[collection];
740 saveData << collection << " " << savedGames[collection] << endl;
748 // level collections: introduction + basic
750 // make fixed pipes look different than non-fixed ones
754 // graphical hints on what to do next
755 // graphical help, showing the ui elements: demo