summaryrefslogtreecommitdiffstats
path: root/konquest/gameboard.cc
blob: 75e440d70480ef466a4a901d61715748cdfe275f (plain)
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
#include <qlayout.h>
#include <qcolor.h>
#include <qlabel.h>
#include <qslider.h>
#include <qevent.h>
#include <qkeycode.h>
#include <qlistbox.h>
#include <qpushbutton.h>
#include <qlineedit.h>
#include <qvalidator.h>
#include <qtextedit.h>

#include <kapplication.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kglobal.h>
#include <kiconloader.h>

#include <ctype.h>
#include <math.h>

#include "gamecore.h"

#include "int_validator.h"
#include "newgamedlg.h"
#include "gameenddlg.h"
#include "scoredlg.h"
#include "fleetdlg.h"
#include "gameboard.h"
#include "gameboard.moc"


/*********************************************************************
 Game Board
*********************************************************************/
GameBoard::GameBoard( QWidget *parent )
    : QWidget( parent ), gameInProgress( false ), gameState( NONE )
{
    QColorGroup cg( white, black, green.light(), green.dark(), green, green.dark(75), green.dark() );
    QPalette palette( cg, cg, cg );

    neutralPlayer = Player::createNeutralPlayer();
    map = new Map;
    
    planets.setAutoDelete(true);
    players.setAutoDelete(true);

    //********************************************************************
    // Create the widgets in the main window
    //********************************************************************
    mapWidget = new ConquestMap( map, this );
    msgWidget = new QTextEdit( this );
    msgWidget->setTextFormat(LogText);
    msgWidget->setMinimumHeight(100);
    msgWidget->setHScrollBarMode(QScrollView::AlwaysOff);
    msgWidget->setPaper(QBrush(Qt::black));
    planetInfo = new PlanetInfo( this, palette );
    gameMessage = new QLabel( this );
    gameMessage->setPalette( palette );
    turnCounter = new QLabel( this );
    turnCounter->setPalette( palette );
    turnCounter->setText( "Turn" );
    turnCounter->setMaximumHeight( turnCounter->sizeHint().height() );

    endTurn = new QPushButton( i18n("End Turn"), this );
    endTurn->setFixedSize( endTurn->sizeHint() );
    endTurn->setPalette( palette );

    shipCountEdit = new QLineEdit( this );
    IntValidator *v = new IntValidator( 1, 32767, this );
    shipCountEdit->setValidator( v );
    shipCountEdit->setMinimumSize( 40, 0 );
    shipCountEdit->setMaximumSize( 32767, 40 );
    shipCountEdit->setEnabled(false);
    shipCountEdit->setPalette( palette );
    shipCountEdit->setEchoMode( QLineEdit::Password );

    splashScreen = new QLabel( this );
    splashScreen->setPixmap(QPixmap(IMAGE_SPLASH));
    splashScreen->setGeometry( 0, 0, 600, 550 );

    setMinimumSize( 600, 600 );

    setMouseTracking( true );
    setFocusPolicy( StrongFocus );
    setFocus();

    //********************************************************************
    // Layout the main window
    //********************************************************************
    QHBoxLayout *layout1 = new QHBoxLayout( this );
    QVBoxLayout *layout2 = new QVBoxLayout;
    QHBoxLayout *layout3 = new QHBoxLayout;
    QVBoxLayout *layout4 = new QVBoxLayout;

    layout1->addLayout( layout2 );
    layout2->addLayout( layout3 );

    layout3->addSpacing( 5 );
    layout3->addWidget( gameMessage, 10 );
    layout3->addWidget( shipCountEdit, 1 );
    layout3->addWidget( endTurn, 1 );

    layout2->addSpacing( 5 );
    layout2->addWidget( mapWidget, 0, AlignTop );
    layout2->addWidget( msgWidget );
    layout2->addStretch( 1 );

    layout1->addSpacing( 5 );
    layout1->addLayout( layout4, 10 );

    layout4->addWidget( planetInfo, 1 );
    layout4->addSpacing( 10 );
    layout4->addWidget( turnCounter,  1 );
    layout4->addStretch( 1 );

    layout1->addStretch( 1 );

    //**********************************************************************
    // Set up signal/slot connections
    //**********************************************************************
    connect( mapWidget, SIGNAL( planetSelected(Planet *) ), this, SLOT(planetSelected(Planet *)) );
    connect( shipCountEdit, SIGNAL(returnPressed()), this, SLOT(newShipCount()) );
    connect( endTurn, SIGNAL( clicked() ), this, SLOT( nextPlayer() ) );
    connect( mapWidget, SIGNAL( planetHighlighted(Planet *)), planetInfo, SLOT(showPlanet(Planet *)) );

    changeGameBoard( false );
}


//**********************************************************************
// Destructor
//**********************************************************************
GameBoard::~GameBoard()
{
    // Nothing much to do yet
}

#if 0
QSize GameBoard::sizeHint() const
{
    return QSize( 600, 550 );
}
#endif

//************************************************************************
// Keyboard Event handlers
//************************************************************************
void
GameBoard::keyPressEvent( QKeyEvent *e )
{
    // Check for the escape key
    if( e->key() == Key_Escape ) {
        switch( gameState ) {
        case DEST_PLANET:
        case SHIP_COUNT:
        case RULER_SOURCE:
        case RULER_DEST:
            gameState = SOURCE_PLANET;
            haveSourcePlanet = false;
            haveDestPlanet = false;
            turn();
            break;
        default:
            break;
        }
        return;
    }

    if( !isgraph( e->ascii() ) ) {
        e->ignore();
        return;
    }

    PlanetListIterator planetSearch( planets );
    QString planetName;

    planetName += toupper( e->ascii() );

    for(Planet *p = planetSearch.toFirst();
        p != NULL;
        p = ++planetSearch ) {

        if( p->getName() == planetName )
            planetSelected( p );
    }

}

QString
GameBoard::playerString(Player *player)
{
    if (!player)
        player = currentPlayer->current();
    return player->getColoredName();
}

//************************************************************************
// Game engine/state machine
//************************************************************************
void
GameBoard::turn()
{
    PlanetListIterator planetAi( planets );
    PlanetListIterator planetAttack( planets );
    Planet *target = 0;
   
    switch( gameState ) {
    case NONE :
        // stuff for none
        gameState = SOURCE_PLANET;
        haveSourcePlanet = false;
        haveDestPlanet = false;
        haveShipCount = false;
        shipCount = 0;
        mapWidget->unselectPlanet();


        turn();
        setFocus();
        break;

    case SOURCE_PLANET :

        if( haveSourcePlanet ) {
            gameState = DEST_PLANET;

            sourcePlanet->select();
            turn();

        } else {
            shipCountEdit->hide();
            endTurn->setEnabled( true );
            mapWidget->unselectPlanet();

            gameMessage->setText( "<qt>" + playerString() + ": " +
                                    i18n("Select source planet...") + "</qt>" );
            setFocus();
        }

        break;

    case DEST_PLANET :

        if( haveDestPlanet ) {
            mapWidget->unselectPlanet();
            gameState = SHIP_COUNT;
            turn();

        } else {
            shipCountEdit->hide();
            endTurn->setEnabled( false );
            sourcePlanet->select();
            gameMessage->setText( "<qt>" + playerString() + ": " +
                                    i18n("Select destination planet...") + "</qt>" );
            setFocus();
        }

        break;

    case SHIP_COUNT:

        if( haveShipCount ) {
            // We now have a complete fleet to send, so send it
            sendAttackFleet( sourcePlanet, destPlanet, shipCount);

            shipCountEdit->hide();
            endTurn->setEnabled( true );

            gameState = NONE;
            turn();

            endTurn->setFocus();

        } else {
            gameMessage->setText( currentPlayer->current()->getName() +
                                    i18n(": How many ships?") );

            shipCountEdit->setText( "" );
            shipCountEdit->show();
            shipCountEdit->setEnabled(true);
            shipCountEdit->setFocus();

            endTurn->setEnabled( false );

            mapWidget->unselectPlanet();
        }

        break;

    case RULER_SOURCE:
        if( haveSourcePlanet ) {
            gameState = RULER_DEST;
            sourcePlanet->select();
            turn();
        } else {
            shipCountEdit->hide();
            endTurn->setEnabled( true );
            mapWidget->unselectPlanet();

            gameMessage->setText( i18n("Ruler: Select starting planet.") );
            setFocus();
        }

        break;

    case RULER_DEST:
        if( haveDestPlanet ) {
            mapWidget->unselectPlanet();

            // Display the distance between the two planets
            CoreLogic cl;
            double dist = cl.distance( sourcePlanet, destPlanet );

            QString msg;
            msg = i18n("The distance from Planet %1 to Planet %2 is %3 light years.\n"
                       "A ship leaving this turn will arrive on turn %4")
                  .arg(sourcePlanet->getName())
		  .arg(destPlanet->getName())
                  .arg(KGlobal::locale()->formatNumber( dist, 2 ))
		  .arg(KGlobal::locale()->formatNumber( turnNumber + (int)dist, 0 ));
	    KMessageBox::information( this, msg, i18n("Distance"));

            gameState = NONE;
            turn();
        } else {
            gameMessage->setText( i18n("Ruler: Select ending planet.") );
            shipCountEdit->hide();
            endTurn->setEnabled( false );
            sourcePlanet->select();

            setFocus();
        }

        break;

     case AI_PLAYER:
         endTurn->setEnabled( false );
         gameMessage->setText( i18n("Computer Player thinking...") );

         Planet *home;

         int ships;
         planetAi.toFirst();
         
         while ((home = planetAi())) {
            if (home->getPlayer() == currentPlayer->current()) {

                           bool hasAttack = false;
                           ships = (int)floor(home->getFleet().getShipCount() * 0.7 );
                           
                           if (ships >= 20) {

				Planet *attack;
				double minDistance = 100;
			        planetAttack.toFirst();
				while ((attack = planetAttack())) {
                                        bool skip = false;
                                        
					CoreLogic cl;
					double dist = cl.distance( home, attack );

					 if ((dist < minDistance) &&  (attack->getPlayer() != currentPlayer->current()) &&
                                                        (attack->getFleet().getShipCount() < ships )) {
                                                AttackFleetListIterator FleetsinFlight( currentPlayer->current()->getAttackList() );
                                                AttackFleet *curFleet;

                                                while ( (curFleet = FleetsinFlight())) {
                                                 	if (curFleet->destination == attack) {
                                                        	skip = true;
							}
						}
                                                if (skip) continue;

					  	target = attack;
					   	hasAttack = true;
					 	minDistance = dist;
					}
				}
                           
                                if (hasAttack) {
			    		sendAttackFleet( home, target, ships );
                                }
                                else {
                                    planetAttack.toFirst();
                                    minDistance = 100;
                                    int shipsToSend = 0;
                                    bool hasDestination = false;
                                    
                                    while ((attack = planetAttack())) {
                                        bool skip = false;
                                        CoreLogic cl;
                                        double dist = cl.distance( home, attack );
                                        int homeships = (int)floor(home->getFleet().getShipCount() * 0.5 );
                                        
                                        if ((dist < minDistance) &&  (attack->getPlayer() == currentPlayer->current()) &&
                                                        (attack->getFleet().getShipCount() < homeships )) {
                                                AttackFleetListIterator FleetsinFlight( currentPlayer->current()->getAttackList() );
                                                AttackFleet *curFleet;

                                                while ( (curFleet = FleetsinFlight())) {
                                                 	if (curFleet->destination == attack) {
                                                        	skip = true;
							}
						}
                                                if (skip) continue;

                                                shipsToSend = (int)floor((home->getFleet().getShipCount() - attack->getFleet().getShipCount()) / 2) ;
                                                
					  	target = attack;
					   	hasDestination = true;
                                                minDistance = dist;
                                        }
                                    }

                                    if (hasDestination) {
                                            sendAttackFleet( home, target, shipsToSend );
                                      }
                                }
    			  }
		}
        }
         
         endTurn->setEnabled( true );
         nextPlayer();
         
    	break;
     
    default:
        break;
    }

    QString turnStr;
    turnStr = i18n("Turn #: %1 of %2").arg(turnNumber).arg(lastTurn);

    turnCounter->setText( turnStr );

    emit newGameState( gameState );
}
//************************************************************************
// To the end turn processing (resolve combat, etc.)
//************************************************************************
void
GameBoard::nextTurn()
{
    resolveShipsInFlight();

    scanForSurvivors();

    // advance to first living player
    while( currentPlayer->current() && !currentPlayer->current()->isInPlay() ) {
    	++(*currentPlayer);
    };

    // advance turn counter
    turnNumber++;

    // update the planets
    PlanetListIterator nextPlanet( planets );
    Planet *planet;

    while( (planet = nextPlanet()) )
    {
        planet->turn();
    }

    // Tell the status widget to update itself
    planetInfo->rescanPlanets();

    Player *winner = findWinner();
    if (winner)
    {
        mapWidget->repaint(true);
        KMessageBox::information(this, 
              i18n("The mighty %1 has conquered the galaxy!").arg(winner->getName()),
              i18n("Game Over"));
    }

    if( (turnNumber == lastTurn) && !winner )
    {
        mapWidget->repaint(true);
        GameEndDlg *dlg = new GameEndDlg( this );

        if( dlg->exec() == KDialogBase::Yes ) {
            lastTurn += dlg->extraTurns();
        }

        delete dlg;
    }

    if( winner || (turnNumber >= lastTurn) )
    {
        // Game over, man! Game over.

        mapWidget->repaint(true);

        gameOver();
    };
}

//************************************************************************
// determine the fate of the ships in transit
//************************************************************************
void
GameBoard::resolveShipsInFlight()
{
    AttackFleetList arrivingShips;
    PlayerListIterator nextPlayer( players );
    Player *plr;

    while( (plr = nextPlayer()) ) {
        AttackFleetListIterator nextFleet( plr->getAttackList() );

        AttackFleet *fleet;

        while( (fleet = nextFleet()) ) {
            double fleetArrivalTurn = floor(fleet->arrivalTurn);

            if( turnNumber == int (fleetArrivalTurn) ) {
                doFleetArrival( fleet );
                plr->getAttackList().removeRef( fleet );
                delete fleet;
            }
        }
    }

}

Player *
GameBoard::findWinner()
{
    Player *winner = 0;
    int activePlayers = 0;

    PlayerListIterator nextPlayer( players );
    Player *plr;
    
    while( (plr = nextPlayer()) ) {
        if (plr->isInPlay())
        {
            winner = plr;
            activePlayers++;
        }
        else if (plr->getAttackList().count() != 0)
        {
            activePlayers++;
        }
    }
    if (activePlayers == 1)
        return winner;

    return 0;
}

void
GameBoard::gameMsg(const QString &msg, Player *player, Planet *planet, Player *planetPlayer)
{
    bool isHumanInvolved = false;
       
    QString color = "white";
    QString colorMsg = msg;
    QString plainMsg = msg;

    if (player)
    {
       if (!player->isAiPlayer())
          isHumanInvolved = true;
       colorMsg = colorMsg.arg(playerString(player));
       plainMsg = plainMsg.arg(player->getName());
    }

    if (planet)
    {
       if (!planetPlayer)
          planetPlayer = planet->getPlayer();
       if (!planetPlayer->isAiPlayer() && !planetPlayer->isNeutral())
          isHumanInvolved = true;

       QString color = planetPlayer->getColor().name();
       colorMsg = colorMsg.arg(QString("<font color=\"%1\">%2</font>").arg(color, planet->getName()));
       plainMsg = plainMsg.arg(planet->getName());
    }
    msgWidget->append(("<qt><font color=\"white\">Turn %1:</font> <font color=\""+color+"\">").arg(turnNumber)+colorMsg+"</font></qt>");
    msgWidget->scrollToBottom();
    
    if (isHumanInvolved)
    {
       mapWidget->repaint(true);
       KMessageBox::information(this, plainMsg);
    }
}

//************************************************************************
// check to see any players have been eliminated
//************************************************************************
void
GameBoard::scanForSurvivors()
{
    PlayerListIterator nextPlayer( players );
    PlayerList activePlayers;
    PlayerList inactivePlayers;

    // insert all of the active players into a special
    // list, the deactivate them
    Player *plr;
    while( (plr = nextPlayer()) ) {
        if( plr->isInPlay() ) {
            activePlayers.append( plr );
            plr->setInPlay( false );
        } else {
            inactivePlayers.append( plr );
        }
    }


    // iterate through the list of planets and
    // mark their owners in play
    PlanetListIterator nextPlanet( planets );

    Planet *planet;
    while( (planet = nextPlanet()) ) {
        planet->getPlayer()->setInPlay( true );
    }


    PlayerListIterator nextActivePlayer( activePlayers );
    while( (plr = nextActivePlayer()) ) {
        if( !plr->isInPlay() ) {
            // Player has bitten the dust
            QString msg;
            msg = i18n("The once mighty empire of %1 has fallen in ruins.");
            gameMsg(msg, plr);
        }
    }

    PlayerListIterator nextInactivePlayer( inactivePlayers );
    while( (plr = nextInactivePlayer()) ) {
        if( plr->isInPlay() ) {
            // Player has bitten the dust
            QString msg;
            msg = i18n("The fallen empire of %1 has staggered back to life.");
            gameMsg(msg, plr);
        }
    }
}

//************************************************************************
// handle the arrival of a fleet at a planet
//************************************************************************
void
GameBoard::doFleetArrival( AttackFleet *arrivingFleet )
{
    // Check to see of (fleet owner) == (planet owner)
    // if the planet and fleet owner are the same, then merge the fleets
    // otherwise attack.

    if( (*arrivingFleet->owner) == (*arrivingFleet->destination->getPlayer())) {
        if (!arrivingFleet->owner->isAiPlayer()) {
        	arrivingFleet->destination->getFleet().absorb(arrivingFleet);

        	QString msg;
        	msg = i18n("Reinforcements (%1 ships) have arrived for planet %2.")
        	      .arg(arrivingFleet->getShipCount());
                gameMsg(msg, 0, arrivingFleet->destination);
        }
    } else {

        // let's get ready to rumble...

        CoreLogic cl;
        AttackFleet &attacker = *arrivingFleet;
        DefenseFleet &defender = arrivingFleet->destination->getFleet();
        Planet &prizePlanet = *(arrivingFleet->destination);

        bool haveVictor = false;
        bool planetHolds = true;

        while( !haveVictor ) {
            double attackerRoll = cl.roll();
            double defenderRoll = cl.roll();

            if( defenderRoll < prizePlanet.getKillPercentage() ) {
                attacker.removeShips( 1 );
            }

            if( attacker.getShipCount() <= 0 ) {
                haveVictor = true;
                planetHolds = true;
                continue;
            }

            if( attackerRoll < attacker.killPercentage ) {
                defender.removeShips( 1 );
                attacker.owner->statEnemyShipsDestroyed( 1 );
            }

            if( defender.getShipCount() <= 0 ) {
                haveVictor = true;
                planetHolds = false;
            }
        }

        if( planetHolds ) {
            prizePlanet.getPlayer()->statEnemyFleetsDestroyed(1);
            QString msg;
            msg = i18n("Planet %2 has held against an attack from %1.");
            gameMsg(msg, attacker.owner, &prizePlanet);
        } else {
            Player *defender = prizePlanet.getPlayer();
            attacker.owner->statEnemyFleetsDestroyed( 1 );

            arrivingFleet->destination->conquer( arrivingFleet );

            QString msg;
            msg = i18n("Planet %2 has fallen to %1.");
            gameMsg(msg, attacker.owner, &prizePlanet, defender);
        }
    }

    mapWidget->repaint(true);
}

//************************************************************************
// Set up the game board for a new game
//************************************************************************
void
GameBoard::startNewGame()
{
    shutdownGame();

    if( gameInProgress )
        return;

    NewGameDlg *newGame = new NewGameDlg( this, map, &players, neutralPlayer, &planets );

    if( !newGame->exec() )
    {
        delete newGame;
        return;
    }
    newGame->save(); // Save settings for next time
    
    msgWidget->clear();

    changeGameBoard( true );

    planetInfo->setPlanetList(planets);

    shipCountEdit->hide();
    endTurn->setEnabled( true );

    currentPlayer = new PlayerListIterator( players );
    currentPlayer->toFirst();

    endTurn->show();
    gameMessage->show();

    lastTurn = newGame->turns();

    turnNumber = 1;
    turn();

    delete newGame;
}

//************************************************************************
// Shut down the current game
//************************************************************************
void
GameBoard::shutdownGame()
{
    if( !gameInProgress )
        return;

    int choice = KMessageBox::warningContinueCancel
      ( this,
	i18n("Do you wish to retire this game?"),
	i18n("End Game"),
        KStdGuiItem::ok() );

    if( choice == KMessageBox::Cancel )
        return;

    gameOver();
}

void
GameBoard::gameOver()
{
    ScoreDlg *scoreDlg = new ScoreDlg( this, i18n("Final Standings"), &players );
    scoreDlg->exec();

    cleanupGame();
}

void
GameBoard::cleanupGame()
{
    map->clearMap();

    planets.clear();
    players.clear();

    delete currentPlayer;
    currentPlayer = NULL;

    shipCountEdit->hide();
    endTurn->setEnabled( false );

    gameMessage->hide();
    endTurn->hide();

    changeGameBoard( false );
    gameState = NONE;
    emit newGameState(gameState);
}


//************************************************************************
// Player selected a planet
//************************************************************************
void
GameBoard::planetSelected( Planet *planet )
{
    switch( gameState ) {
    case SOURCE_PLANET:
        if( (*planet->getPlayer()) == (*currentPlayer->current()) ) {
            // got a match
            haveSourcePlanet = true;
            sourcePlanet = planet;

            turn();
        }

        break;

    case RULER_SOURCE:
        haveSourcePlanet = true;
        sourcePlanet = planet;
        turn();
        break;

    case DEST_PLANET:
    case RULER_DEST:
        if( planet != sourcePlanet ) {
            // got a match
            haveDestPlanet = true;
            destPlanet = planet;

            turn();
        }

        break;

    default:
    case NONE :
        break;
    }

}

//************************************************************************
// Player hit return in the ship count edit box
//************************************************************************
void
GameBoard::newShipCount()
{
    QString temp( shipCountEdit->text() );
    bool ok;

    switch( gameState ) {
    case SHIP_COUNT:
        shipCount = temp.toInt(&ok);

        if( ok )
            haveShipCount = true;

        shipCountEdit->setText( "" );

        turn();
        break;

    default:
        break;
    };

}

//**********************************************************************
// transition board from play to non-play
//**********************************************************************
void
GameBoard::changeGameBoard( bool inPlay  )
{
    gameInProgress = inPlay;

    if( gameInProgress ) {
        mapWidget->show();
        planetInfo->show();
        gameMessage->show();
        endTurn->show();
        shipCountEdit->show();
        splashScreen->hide();
        setBackgroundColor( black );
    } else {
        mapWidget->hide();
        planetInfo->hide();
        gameMessage->hide();
        endTurn->hide();
        shipCountEdit->hide();
        splashScreen->show();
        setBackgroundColor( black );
    }

}

//************************************************************************
// Player clicked the 'End Turn' button
//************************************************************************
void
GameBoard::nextPlayer()
{
    // end turn and advance to next player
    Player *plr;

    while( (plr = ++(*currentPlayer)) && !(plr->isInPlay()) ) {}

    if( !plr ) {
        // end of player list, new turn
        currentPlayer->toFirst();
        nextTurn();
    }

    if( gameInProgress ) {
       if (currentPlayer->current()->isAiPlayer()) {
             gameState = AI_PLAYER;
         }
         else {
             gameState = SOURCE_PLANET;
        
        }
       turn();   
    }
}

//************************************************************************
// A complete set of source, destination planets and ship count has been
// entered, so do something about it
//************************************************************************
void
GameBoard::sendAttackFleet( Planet *source, Planet *dest, int ship )
{
    bool ok;

    ok = currentPlayer->current()->NewAttack( source, dest,
                                                ship, turnNumber );

    if( !ok ) {
      KMessageBox::error( this,
			  i18n("Not enough ships to send.") );
    }
}

//************************************************************************
// Toolbar items
//************************************************************************
void
GameBoard::measureDistance()
{
    switch( gameState ) {
    case SOURCE_PLANET:
        gameState = RULER_SOURCE;
        turn();
    default:
        break;
    }
}

void
GameBoard::showScores()
{
    ScoreDlg *scoreDlg = new ScoreDlg( this, i18n("Current Standings"), &players );
    scoreDlg->show();
}

void
GameBoard::showFleets()
{
  FleetDlg *fleetDlg = new FleetDlg( this, &(currentPlayer->current()->getAttackList()) );
  fleetDlg->show();
}