1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
|
/*******************************************************************
*
* Copyright 2006-2008 Dmitry Suzdalev <dimsuz@gmail.com>
*
* This file is part of the KDE project "KLines"
*
* KLines is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* KLines is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KLines; see the file COPYING. If not, write to
* the Free Software Foundation, 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
********************************************************************/
#include "scene.h"
#include "ballitem.h"
#include "previewitem.h"
#include "animator.h"
#include "renderer.h"
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <QSet>
#include <KGamePopupItem>
#include <KLocale>
#include <KDebug>
inline uint qHash( const FieldPos& pos )
{
return qHash( QPair<int,int>(pos.x,pos.y) );
}
KLinesScene::KLinesScene( QObject* parent )
: QGraphicsScene(parent),
m_playFieldBorderSize(0), m_numFreeCells(FIELD_SIZE*FIELD_SIZE),
m_score(0), m_bonusScore(0), m_cellSize(32), m_previewZoneVisible(true)
{
m_animator = new KLinesAnimator(this);
connect( m_animator, SIGNAL(moveFinished()), SLOT(moveAnimFinished()) );
connect( m_animator, SIGNAL(removeFinished()), SLOT(removeAnimFinished()) );
connect( m_animator, SIGNAL(bornFinished()), SLOT(bornAnimFinished()) );
m_focusItem = new QGraphicsRectItem( QRectF(0, 0, m_cellSize, m_cellSize), 0, this );
m_focusItem->setZValue(1.0);
m_focusItem->setPen( Qt::DashLine );
m_previewItem = new PreviewItem(this);
m_previewItem->setPos( 0, 0 );
m_popupItem = new KGamePopupItem;
addItem(m_popupItem);
startNewGame();
}
void KLinesScene::startNewGame()
{
if(m_animator->isAnimating())
return;
// reset all vars
m_selPos = FieldPos();
m_numFreeCells = FIELD_SIZE*FIELD_SIZE;
m_score = 0;
m_bonusScore = 0;
m_placeBalls = true;
m_gameOver = false;
m_itemsToDelete.clear();
m_nextColors.clear();
m_focusItem->setPos(0, 0);
m_focusItem->hide();
m_popupItem->forceHide();
// remove all ball items from the scene leaving other items untouched
QList<QGraphicsItem*> itemlist = items();
foreach( QGraphicsItem* item, itemlist )
{
BallItem* ball = qgraphicsitem_cast<BallItem*>(item);
if( ball )
{
removeItem(item);
delete item;
}
}
for(int x=0; x<FIELD_SIZE; ++x)
for(int y=0; y<FIELD_SIZE; ++y)
m_field[x][y] = 0;
// init m_nextColors
for(int i=0; i<3; i++)
{
// random color
BallColor c = static_cast<BallColor>(m_randomSeq.getLong(static_cast<int>(NumColors)));
m_nextColors.append(c);
}
emit stateChanged(QLatin1String( "not_undoable" ));
nextThreeBalls();
}
KLinesScene::~KLinesScene()
{
delete m_animator;
}
void KLinesScene::resizeScene(int width,int height)
{
// store focus item field pos (calculated using old cellSize)
FieldPos focusRectFieldPos = pixToField( m_focusItem->pos() );
bool hasBorder = KLinesRenderer::hasBorderElement();
int minDim = qMin( width, height );
// border width is hardcoded to be half of cell size.
// take it into account if it exists
m_cellSize = hasBorder ? minDim/(FIELD_SIZE+1) : minDim/FIELD_SIZE;
// set it only if current theme supports it
m_playFieldBorderSize = hasBorder ? m_cellSize/2 : 0;
int boardSize = m_cellSize * FIELD_SIZE;
if ( m_previewZoneVisible && boardSize +m_playFieldBorderSize*2 + m_cellSize > width) // No space enough for balls preview
{
minDim = width;
m_cellSize = hasBorder ? (minDim - m_cellSize - m_playFieldBorderSize*2)/FIELD_SIZE : (minDim - m_cellSize)/FIELD_SIZE;
boardSize = m_cellSize * FIELD_SIZE;
}
m_playFieldRect.setX( (width - (m_previewZoneVisible ? m_cellSize : 0))/2 - boardSize/2 - m_playFieldBorderSize );
m_playFieldRect.setY( height/2 - boardSize/2 - m_playFieldBorderSize );
m_playFieldRect.setWidth( boardSize + m_playFieldBorderSize*2 );
m_playFieldRect.setHeight( boardSize + m_playFieldBorderSize*2 );
setSceneRect( 0, 0, width, height );
// sets render sizes for cells
KLinesRenderer::setCellSize( m_cellSize );
QSize cellSize(m_cellSize, m_cellSize);
// re-render && recalc positions for all balls
for( int x=0; x<FIELD_SIZE; ++x)
for(int y=0; y< FIELD_SIZE; ++y)
{
if( m_field[x][y] )
{
// this will update pixmap
m_field[x][y]->setRenderSize(cellSize);
m_field[x][y]->setPos( fieldToPix( FieldPos(x,y) ) );
m_field[x][y]->setColor( m_field[x][y]->color() );
}
}
m_focusItem->setRect( QRect(0,0, m_cellSize, m_cellSize) );
m_focusItem->setPos( fieldToPix( focusRectFieldPos ) );
int previewOriginY = height / 2 - (3 * m_cellSize) / 2;
int previewOriginX = m_playFieldRect.x() + m_playFieldRect.width();
m_previewItem->setPos( previewOriginX, previewOriginY );
m_previewItem->setPreviewColors( m_nextColors );
//kDebug() << "resize:" << width << "," << height << "; cellSize:" << m_cellSize;
}
void KLinesScene::endTurn()
{
if( m_gameOver )
return;
saveUndoInfo();
nextThreeBalls();
}
void KLinesScene::nextThreeBalls()
{
if( m_animator->isAnimating() )
return;
QList<BallItem*> newItems;
BallItem* newBall;
for(int i=0; i<3; i++)
{
newBall = randomlyPlaceBall( m_nextColors.at(i) );
if( newBall )
newItems.append(newBall);
else
break; // the field is filled :).
}
for(int i=0; i<3; i++)
{
// random color
BallColor c = static_cast<BallColor>(m_randomSeq.getLong(static_cast<int>(NumColors)));
m_nextColors[i] = c;
}
m_previewItem->setPreviewColors( m_nextColors );
m_animator->animateBorn( newItems );
}
void KLinesScene::setPreviewZoneVisible( bool visible )
{
if (visible == m_previewZoneVisible)
return;
m_previewZoneVisible = visible;
m_previewItem->setVisible( visible );
resizeScene((int) width(), (int) height());
invalidate( sceneRect() );
}
BallItem* KLinesScene::randomlyPlaceBall(BallColor c)
{
m_numFreeCells--;
if(m_numFreeCells < 0)
{
// restore m_numFreeCells value, it will trigger
// saveAndErase() after bornAnimFinished to check if
// we have 5-in-a-row to erase
m_numFreeCells = 0;
return 0; // game over, we won't create more balls
}
int posx = -1, posy = -1;
// let's find random free cell
do
{
posx = m_randomSeq.getLong(FIELD_SIZE);
posy = m_randomSeq.getLong(FIELD_SIZE);
} while( m_field[posx][posy] != 0 );
BallItem* newBall = new BallItem( this);
newBall->setColor(c, false); // pixmap will be set by born animation
newBall->setPos( fieldToPix( FieldPos(posx,posy) ) );
m_field[posx][posy] = newBall;
return newBall;
}
void KLinesScene::mousePressEvent( QGraphicsSceneMouseEvent* ev )
{
QGraphicsScene::mousePressEvent(ev);
QRect boardRect = m_playFieldRect.adjusted( m_playFieldBorderSize,
m_playFieldBorderSize,
-m_playFieldBorderSize,
-m_playFieldBorderSize );
if ( !boardRect.contains( ev->scenePos().toPoint() ) )
return;
selectOrMove( pixToField(ev->scenePos()) );
}
void KLinesScene::selectOrMove( const FieldPos& fpos )
{
if( m_animator->isAnimating() )
return;
if( m_field[fpos.x][fpos.y] ) // ball was selected
{
if( m_selPos.isValid() )
{
m_field[m_selPos.x][m_selPos.y]->stopAnimation();
if ( m_selPos == fpos )
{
m_selPos.x = m_selPos.y = -1; // invalidate position
return;
}
}
m_field[fpos.x][fpos.y]->startSelectedAnimation();
m_selPos = fpos;
}
else // move selected ball to new location
{
if( m_selPos.isValid() && m_field[fpos.x][fpos.y] == 0 )
{
saveUndoInfo();
// start move animation
// slot moveAnimFinished() will be called when it finishes
bool pathExists = m_animator->animateMove(m_selPos, fpos);
if(!pathExists)
{
m_popupItem->setMessageTimeout(2500);
m_popupItem->showMessage(i18n("There is no path from the selected piece to this cell"), KGamePopupItem::BottomLeft);
}
}
}
}
void KLinesScene::moveAnimFinished()
{
// m_field[m_selPos.x][m_selPos.y] still holds the ball pointer
// but animation placed it to new location.
// But it updated only pixel position, not the field one
// So let's do it here
BallItem *movedBall = m_field[m_selPos.x][m_selPos.y];
// movedBall has new pixel position - let's find out corresponding field pos
FieldPos newpos = pixToField(movedBall->pos());
m_field[m_selPos.x][m_selPos.y] = 0; // no more ball here
m_field[newpos.x][newpos.y] = movedBall;
m_selPos.x = m_selPos.y = -1; // invalidate position
m_placeBalls = true;
// after anim finished, slot removeAnimFinished()
// will be called
searchAndErase();
}
void KLinesScene::removeAnimFinished()
{
if( m_itemsToDelete.isEmpty() && m_numFreeCells == 0 )
{
// game over
gameOverHandler();
return;
}
if( m_itemsToDelete.isEmpty() && m_placeBalls)
{
// slot bornAnimFinished() will be called
// when born animation finishes
// NOTE: removeAnimFinished() will be called again
// after new balls will born (because searchAndErase() will be called)
// but other if branch will be taken
nextThreeBalls();
}
else
{
// this is kind of 'things to do after one turn is finished'
// place in code :)
int numBallsErased = m_itemsToDelete.count();
if(numBallsErased)
{
// expression taked from previous code in klines.cpp
m_score += 2*numBallsErased*numBallsErased - 20*numBallsErased + 60 ;
m_score += m_bonusScore;
}
foreach( BallItem* item, m_itemsToDelete )
{
removeItem(item);
delete item;
}
m_itemsToDelete.clear();
if(numBallsErased)
emit scoreChanged(m_score);
}
}
void KLinesScene::bornAnimFinished()
{
// note that if m_numFreeCells == 0, we still need to
// check for possible 5-in-a-row balls, i.e. call searchAndErase()
// So there's another gameOver-check in removeAnimFinished()
if( m_numFreeCells < 0 )
{
gameOverHandler();
return;
}
// There's a little trick here:
// searchAndErase() will cause m_animator to emit removeFinished()
// If there wasn't m_placeBalls var
// it would cause an infinite loop like this:
// SaE()->removeAnimFinished()->next3Balls()->bornAnimFinished()->
// SaE()->removeAnimFinished()->next3Balls()->...
// etc etc
m_placeBalls = false;
// after placing new balls new 5-in-a-row chunks can occur
// so we need to check for them
//
// And because of that we check for gameOver in removeAnimFinished()
// rather than here - there's a chance that searchAndErase() will remove
// balls making some free cells to play in
searchAndErase();
}
void KLinesScene::searchAndErase()
{
// FIXME dimsuz: put more comments about bounds in for loops
// QSet - to exclude adding duplicates
QSet<FieldPos> positionsToDelete;
// horizontal chunks searching
for(int x=0; x<FIELD_SIZE-4; ++x)
for(int y=0;y<FIELD_SIZE; ++y)
{
if(m_field[x][y] == 0)
continue;
BallColor col = m_field[x][y]->color();
int tmpx = x+1;
while(tmpx < FIELD_SIZE && m_field[tmpx][y] && m_field[tmpx][y]->color() == col)
tmpx++;
// tmpx-x will be: how much balls of the same color we found
if(tmpx-x >= 5)
{
for(int i=x; i<tmpx;++i)
{
positionsToDelete.insert( FieldPos(i,y) );
}
}
else
continue;
}
// vertical chunks searching
for(int y=0; y<FIELD_SIZE-4; ++y)
for(int x=0;x<FIELD_SIZE; ++x)
{
if(m_field[x][y] == 0)
continue;
BallColor col = m_field[x][y]->color();
int tmpy = y+1;
while(tmpy < FIELD_SIZE && m_field[x][tmpy] && m_field[x][tmpy]->color() == col)
tmpy++;
// tmpy-y will be: how much balls of the same color we found
if(tmpy-y >= 5)
{
for(int j=y; j<tmpy;++j)
{
positionsToDelete.insert( FieldPos(x,j) );
}
}
else
continue;
}
// down-right diagonal
for(int x=0; x<FIELD_SIZE-4; ++x)
for(int y=0;y<FIELD_SIZE-4; ++y)
{
if(m_field[x][y] == 0)
continue;
BallColor col = m_field[x][y]->color();
int tmpx = x+1;
int tmpy = y+1;
while(tmpx < FIELD_SIZE && tmpy < FIELD_SIZE &&
m_field[tmpx][tmpy] && m_field[tmpx][tmpy]->color() == col)
{
tmpx++;
tmpy++;
}
// tmpx-x (and tmpy-y too) will be: how much balls of the same color we found
if(tmpx-x >= 5)
{
for(int i=x,j=y; i<tmpx;++i,++j)
{
positionsToDelete.insert( FieldPos(i,j) );
}
}
else
continue;
}
// up-right diagonal
for(int x=0; x<FIELD_SIZE-4; ++x)
for(int y=4; y<FIELD_SIZE; ++y)
{
if(m_field[x][y] == 0)
continue;
BallColor col = m_field[x][y]->color();
int tmpx = x+1;
int tmpy = y-1;
while(tmpx < FIELD_SIZE && tmpy >=0 &&
m_field[tmpx][tmpy] && m_field[tmpx][tmpy]->color() == col)
{
tmpx++;
tmpy--;
}
// tmpx-x (and tmpy-y too) will be: how much balls of the same color we found
if(tmpx-x >= 5)
{
for(int i=x,j=y; i<tmpx;++i,--j)
{
positionsToDelete.insert( FieldPos(i,j) );
}
}
else
continue;
}
foreach( const FieldPos& pos, positionsToDelete )
{
m_itemsToDelete.append(m_field[pos.x][pos.y]);
m_field[pos.x][pos.y] = 0;
m_numFreeCells++;
}
// after it finishes slot removeAnimFinished() will be called
// if m_itemsToDelete is empty removeAnimFinished() will be called immediately
m_animator->animateRemove( m_itemsToDelete );
}
void KLinesScene::moveFocusLeft()
{
if( !m_focusItem->isVisible() )
{
m_focusItem->show();
// no action for the first time
return;
}
FieldPos focusPos = pixToField( m_focusItem->pos() );
focusPos.x--;
if (focusPos.x < 0) // rotate on the torus
focusPos.x = FIELD_SIZE - 1;
m_focusItem->setPos ( fieldToPix( focusPos ) );
}
void KLinesScene::moveFocusRight()
{
if( !m_focusItem->isVisible() )
{
m_focusItem->show();
// no action for the first time
return;
}
FieldPos focusPos = pixToField( m_focusItem->pos() );
focusPos.x++;
if (focusPos.x >= FIELD_SIZE) // rotate on the torus
focusPos.x = 0;
m_focusItem->setPos ( fieldToPix( focusPos ) );
}
void KLinesScene::moveFocusUp()
{
if( !m_focusItem->isVisible() )
{
m_focusItem->show();
// no action for the first time
return;
}
FieldPos focusPos = pixToField( m_focusItem->pos() );
focusPos.y--;
if (focusPos.y < 0) // rotate on the torus
focusPos.y = FIELD_SIZE - 1;
m_focusItem->setPos ( fieldToPix( focusPos ) );
}
void KLinesScene::moveFocusDown()
{
if( !m_focusItem->isVisible() )
{
m_focusItem->show();
// no action for the first time
return;
}
FieldPos focusPos = pixToField( m_focusItem->pos() );
focusPos.y++;
if (focusPos.y >= FIELD_SIZE) // rotate on the torus
focusPos.y = 0;
m_focusItem->setPos ( fieldToPix( focusPos ) );
}
void KLinesScene::cellSelected()
{
if( !m_focusItem->isVisible() )
m_focusItem->show();
// we're taking the center of the cell
selectOrMove( pixToField( m_focusItem->pos() + QPointF(m_cellSize/2,m_cellSize/2) ) );
}
void KLinesScene::saveUndoInfo()
{
// save field state to undoInfo
for(int x=0;x<FIELD_SIZE;++x)
for(int y=0; y<FIELD_SIZE;++y)
// NumColors represents no color
m_undoInfo.fcolors[x][y] = ( m_field[x][y] ? m_field[x][y]->color() : NumColors );
m_undoInfo.numFreeCells = m_numFreeCells;
m_undoInfo.score = m_score;
m_undoInfo.nextColors = m_nextColors;
emit stateChanged(QLatin1String( "undoable" ));
}
// Brings m_field and some other vars to the state it was before last turn
void KLinesScene::undo()
{
// do not allow undo during animation
if(m_animator->isAnimating())
return;
if( m_selPos.isValid() )
m_field[m_selPos.x][m_selPos.y]->stopAnimation();
BallColor col;
for(int x=0;x<FIELD_SIZE;++x)
for(int y=0; y<FIELD_SIZE;++y)
{
col = m_undoInfo.fcolors[x][y];
if(col == NumColors) // no ball
{
if( m_field[x][y] )
{
removeItem( m_field[x][y] );
delete m_field[x][y];
m_field[x][y] = 0;
}
continue;
}
if( m_field[x][y] )
{
if( m_field[x][y]->color() != col )
m_field[x][y]->setColor(col);
//else live it as it is
}
else
{
BallItem *item = new BallItem(this);
item->setColor(col);
item->setPos( fieldToPix( FieldPos(x,y) ) );
item->show();
item->setRenderSize(KLinesRenderer::cellExtent());
m_field[x][y] = item;
}
}
m_numFreeCells = m_undoInfo.numFreeCells;
m_score = m_undoInfo.score;
m_nextColors = m_undoInfo.nextColors;
m_selPos = FieldPos();
m_previewItem->setPreviewColors( m_nextColors );
emit scoreChanged(m_score);
emit stateChanged(QLatin1String( "not_undoable" ));
}
void KLinesScene::drawBackground(QPainter *p, const QRectF&)
{
QPixmap tile = KLinesRenderer::backgroundTilePixmap();
p->drawPixmap( 0, 0, KLinesRenderer::backgroundPixmap(sceneRect().size().toSize()) );
p->drawPixmap( m_playFieldRect.x(), m_playFieldRect.y(),
KLinesRenderer::backgroundBorderPixmap( m_playFieldRect.size() ) );
int startX = m_playFieldRect.x()+m_playFieldBorderSize;
int maxX = m_playFieldRect.x()+m_cellSize*FIELD_SIZE;
int startY = m_playFieldRect.y()+m_playFieldBorderSize;
int maxY = m_playFieldRect.y()+m_cellSize*FIELD_SIZE;
for(int x=startX; x<maxX; x+=m_cellSize)
for(int y=startY; y<maxY; y+=m_cellSize)
p->drawPixmap( x, y, tile );
}
void KLinesScene::gameOverHandler()
{
if( m_gameOver )
return; // don't emit twice
m_gameOver = true;
kDebug() << "GAME OVER";
emit stateChanged(QLatin1String( "not_undoable" ));
//emit enableUndo(false);
emit gameOver(m_score);
// disable auto-hide
m_popupItem->setMessageTimeout(0);
m_popupItem->showMessage(i18n("<h1>Game over</h1>"), KGamePopupItem::Center);
}
#include "scene.moc"
|