mainview.cpp 34.5 KB
Newer Older
Simon Huerlimann's avatar
Simon Huerlimann committed
1 2 3
/*
    Copyright (C) 1998-2001 Andreas Zehender <az@azweb.de>
    Copyright (C) 2006-2007 Dirk Rathlev <dirkrathlev@gmx.de>
4

Simon Huerlimann's avatar
Simon Huerlimann committed
5
    This program is free software; you can redistribute it and/or modify
6 7 8 9 10 11 12 13 14 15 16 17 18 19
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

20
#include "mainview.h"
21 22
#include "ai.h"
#include "options.h"
23

24 25 26 27 28
#include <KActionCollection>
#include <KConfigGroup>
#include <KLocalizedString>
#include <KSharedConfig>
#include <KToggleAction>
Dirk Rathlev's avatar
Dirk Rathlev committed
29 30

#include <QAbstractEventDispatcher>
Dirk Rathlev's avatar
Dirk Rathlev committed
31
#include <QBrush>
32
#include <QFontDatabase>
Dirk Rathlev's avatar
Dirk Rathlev committed
33
#include <QGraphicsSimpleTextItem>
Dirk Rathlev's avatar
Dirk Rathlev committed
34
#include <QKeyEvent>
35
#include <QKeySequence>
Dirk Rathlev's avatar
Dirk Rathlev committed
36
#include <QResizeEvent>
37
#include <QSvgRenderer>
38
#include <QStandardPaths>
39 40 41
#include <QTimerEvent>

#include <math.h>
Andreas Zehender's avatar
Andreas Zehender committed
42

43 44
KToggleAction *MyMainView::pauseAction = 0;

Dirk Rathlev's avatar
Dirk Rathlev committed
45 46 47 48 49 50 51
static struct
 {
     int id;
     const char *path;
 }
 kspd_animations [] =
 {
52 53 54 55
     { ID_EXPLOSION, "explos%1"},
     { ID_MINE1, "mine_red%1"},
     { ID_MINE2, "mine_blue%1"},
     { ID_MINEEXPLO, "mineex%1"},
Dirk Rathlev's avatar
Dirk Rathlev committed
56 57 58
     { 0, 0}
 };

59 60
MyMainView::MyMainView(QWidget *parent)
    :QWidget(parent),
Dirk Rathlev's avatar
Dirk Rathlev committed
61
    field(this),//0,0,DEF_WIDTH,DEF_HEIGHT),
62
    view(&field,this)
Andreas Zehender's avatar
Andreas Zehender committed
63 64
{
   int i,p;
65
   setMinimumSize(600,400);
66
   random.setSeed(0);
67
   QPixmap backgr(QStandardPaths::locate(QStandardPaths::DataLocation, QLatin1String(MV_BACKGROUND)));
Laurent Montel's avatar
Laurent Montel committed
68

Dirk Rathlev's avatar
Dirk Rathlev committed
69 70
   field.setBackgroundBrush(QBrush(backgr));
   view.setCacheMode(QGraphicsView::CacheBackground);
Waldo Bastian's avatar
Waldo Bastian committed
71

Dirk Rathlev's avatar
Dirk Rathlev committed
72 73 74 75 76
   setFocusPolicy(Qt::StrongFocus);
   // FIXME: is this needed anymore?
   //view.setResizePolicy(Q3ScrollView::AutoOne);
   view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
   view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
77
   view.setFrameStyle(QFrame::NoFrame);
78

Andreas Zehender's avatar
Andreas Zehender committed
79 80 81 82 83 84 85 86
   for(p=0;p<2;p++)
   {
      for(i=0;i<PlayerKeyNum;i++)
         playerKeyPressed[p][i]=false;
      bulletShot[p]=false;
      minePut[p]=false;
   }

87
   svgrender = new QSvgRenderer(QStandardPaths::locate(QStandardPaths::DataLocation, QLatin1String(MV_SVG_FILE)));
Laurent Montel's avatar
Laurent Montel committed
88 89

   sun=new SunSprite(svgrender,QLatin1String( MV_SUN ));
90
   field.addItem(sun);
91 92
   sun->setPos(QPointF(width()/2-1-(sun->width()/2),
                       height()/2-1-(sun->height()/2)));
Laurent Montel's avatar
Laurent Montel committed
93 94 95 96 97 98 99 100

   powerupelements[0] = QLatin1String( MV_POWERMINE );
   powerupelements[1] = QLatin1String( MV_POWERBULLET );
   powerupelements[2] = QLatin1String( MV_POWERSHIELD );
   powerupelements[3] = QLatin1String( MV_POWERENERGY );

   ship[0]=new ShipSprite(svgrender, QLatin1String( MV_SHIP1 ), 0);
   ship[1]=new ShipSprite(svgrender, QLatin1String( MV_SHIP2 ), 1);
101 102
   field.addItem(ship[0]);
   field.addItem(ship[1]);
Laurent Montel's avatar
Laurent Montel committed
103

Dirk Rathlev's avatar
Dirk Rathlev committed
104
   readSprites();
Laurent Montel's avatar
Laurent Montel committed
105

Andreas Zehender's avatar
Andreas Zehender committed
106 107
   for(i=0;i<2;i++)
   {
108
      // ship[i]->setBoundsAction(QwRealMobileSprite::Wrap);
Andreas Zehender's avatar
Andreas Zehender committed
109
      ship[i]->hide();
110 111
      bullets[i]=new QList<BulletSprite*>;
      mines[i]=new QList<MineSprite*>;
Andreas Zehender's avatar
Andreas Zehender committed
112 113 114 115 116

   }

   waitForStart=false;
   textSprite=0;
117
   readConfig();
Andreas Zehender's avatar
Andreas Zehender committed
118 119 120 121
}

MyMainView::~MyMainView()
{
Dirk Rathlev's avatar
Dirk Rathlev committed
122
   int i;
Laurent Montel's avatar
Laurent Montel committed
123
   QAbstractEventDispatcher::instance()->unregisterTimers(this);
Dirk Rathlev's avatar
Dirk Rathlev committed
124 125 126 127

   for(i=0;i<2;i++)
   {
      delete ai[i];
128 129 130 131
      qDeleteAll(*mines[i]);
      delete mines[i];
      qDeleteAll(*bullets[i]);
      delete bullets[i];
Dirk Rathlev's avatar
Dirk Rathlev committed
132
   }
Laurent Montel's avatar
Laurent Montel committed
133

134 135
   qDeleteAll(powerups);
   powerups.clear();
Laurent Montel's avatar
Laurent Montel committed
136

137 138
   qDeleteAll(explosions);
   explosions.clear();
Laurent Montel's avatar
Laurent Montel committed
139

140
   writeConfig();
Laurent Montel's avatar
Laurent Montel committed
141
   delete svgrender;
Andreas Zehender's avatar
Andreas Zehender committed
142 143
}

144
void MyMainView::setActionCollection(KActionCollection *a)
Andreas Zehender's avatar
Andreas Zehender committed
145
{
146 147 148
   actionCollection = a;
}

149 150 151 152
/* Assumes that there are no gaps between animation frames. ie 1,2,3 will only have frames 1&2
   recognized. It also assumes that there is at least one frame. */
// FIXME: Add Check for existence of first frame
// TODO: Add support for missing frames (ie 1,2,5)
Dirk Rathlev's avatar
Dirk Rathlev committed
153 154 155 156 157
bool MyMainView::readSprites()
{
   int i = 0;
   while ( kspd_animations[i].id )
   {
158 159
      QList<QString> anim;
      short frame = 0;
Laurent Montel's avatar
Laurent Montel committed
160
      QString element =QLatin1String( kspd_animations[i].path );
161 162 163 164 165 166 167
      QString elem = element.arg(frame, 2, 10, QLatin1Char('0'));
      do
      {
	 anim.append(elem);
	 frame++;
	 elem = element.arg(frame, 2, 10, QLatin1Char('0'));
      } while ( svgrender->elementExists(elem) );
Dirk Rathlev's avatar
Dirk Rathlev committed
168 169 170 171
      animation.insert( kspd_animations[i].id, anim );
      i++;
   }

172
   // FIXME: Perform test!
Dirk Rathlev's avatar
Dirk Rathlev committed
173 174
   return true;
}
Dirk Rathlev's avatar
Dirk Rathlev committed
175

176 177
void MyMainView::readConfig()
{
Laurent Montel's avatar
Port++  
Laurent Montel committed
178
   KConfigGroup game(KSharedConfig::openConfig(), "Game");
Andreas Zehender's avatar
Andreas Zehender committed
179
   int i;
180

Laurent Montel's avatar
Laurent Montel committed
181
   customConfig.gamespeed=game.readEntry("gamespeed",
Andreas Zehender's avatar
Andreas Zehender committed
182 183 184
                                                  predefinedConfig[0].gamespeed);

   customConfig.gravity=
Laurent Montel's avatar
Laurent Montel committed
185
      game.readEntry("gravity",predefinedConfig[0].gravity);
Andreas Zehender's avatar
Andreas Zehender committed
186
   customConfig.acc=
Laurent Montel's avatar
Laurent Montel committed
187
      game.readEntry("acceleration",predefinedConfig[0].acc);
Andreas Zehender's avatar
Andreas Zehender committed
188
   customConfig.bulletDamage=
Laurent Montel's avatar
Laurent Montel committed
189
      game.readEntry("bulletDamage",predefinedConfig[0].bulletDamage);
Andreas Zehender's avatar
Andreas Zehender committed
190
   customConfig.bulletLifeTime=
Laurent Montel's avatar
Laurent Montel committed
191
      game.readEntry("bulletLifeTime",predefinedConfig[0].bulletLifeTime);
Andreas Zehender's avatar
Andreas Zehender committed
192
   customConfig.bulletReloadTime=
Laurent Montel's avatar
Laurent Montel committed
193
      game.readEntry("bulletReloadTime",predefinedConfig[0].bulletReloadTime);
Andreas Zehender's avatar
Andreas Zehender committed
194
   customConfig.mineDamage=
Laurent Montel's avatar
Laurent Montel committed
195
      game.readEntry("mineDamage",predefinedConfig[0].mineDamage);
Andreas Zehender's avatar
Andreas Zehender committed
196
   customConfig.shipDamage=
Laurent Montel's avatar
Laurent Montel committed
197
      game.readEntry("shipDamage",predefinedConfig[0].shipDamage);
Andreas Zehender's avatar
Andreas Zehender committed
198
   customConfig.maxBullets=
Laurent Montel's avatar
Laurent Montel committed
199
      game.readEntry("maxBullets",predefinedConfig[0].maxBullets);
Andreas Zehender's avatar
Andreas Zehender committed
200
   customConfig.maxMines=
Laurent Montel's avatar
Laurent Montel committed
201
      game.readEntry("maxMines",predefinedConfig[0].maxMines);
Andreas Zehender's avatar
Andreas Zehender committed
202
   customConfig.mineReloadTime=
Laurent Montel's avatar
Laurent Montel committed
203
      game.readEntry("mineReloadTime",predefinedConfig[0].mineReloadTime);
Andreas Zehender's avatar
Andreas Zehender committed
204
   customConfig.rotationSpeed=
Laurent Montel's avatar
Laurent Montel committed
205
      game.readEntry("rotationSpeed",predefinedConfig[0].rotationSpeed);
Andreas Zehender's avatar
Andreas Zehender committed
206
   customConfig.shotSpeed=
Laurent Montel's avatar
Laurent Montel committed
207
      game.readEntry("shotSpeed",predefinedConfig[0].shotSpeed);
Andreas Zehender's avatar
Andreas Zehender committed
208
   customConfig.energyNeed=
Laurent Montel's avatar
Laurent Montel committed
209
      game.readEntry("accEnergyNeed",predefinedConfig[0].energyNeed);
Andreas Zehender's avatar
Andreas Zehender committed
210
   customConfig.rotationEnergyNeed=
Laurent Montel's avatar
Laurent Montel committed
211
      game.readEntry("rotationEnergyNeed",predefinedConfig[0].rotationEnergyNeed);
Andreas Zehender's avatar
Andreas Zehender committed
212
   customConfig.sunEnergy=
Laurent Montel's avatar
Laurent Montel committed
213
      game.readEntry("sunEnergy",predefinedConfig[0].sunEnergy);
Andreas Zehender's avatar
Andreas Zehender committed
214
   customConfig.mineActivateTime=
Laurent Montel's avatar
Laurent Montel committed
215
      game.readEntry("mineActivateTime",predefinedConfig[0].mineActivateTime);
Andreas Zehender's avatar
Andreas Zehender committed
216
   customConfig.mineFuel=
Laurent Montel's avatar
Laurent Montel committed
217
      game.readEntry("mineFuel",predefinedConfig[0].mineFuel);
Andreas Zehender's avatar
Andreas Zehender committed
218
   customConfig.shotEnergyNeed=
Laurent Montel's avatar
Laurent Montel committed
219
      game.readEntry("shotEnergyNeed",predefinedConfig[0].shotEnergyNeed);
Andreas Zehender's avatar
Andreas Zehender committed
220
   customConfig.mineEnergyNeed=
Laurent Montel's avatar
Laurent Montel committed
221
      game.readEntry("mineEnergyNeed",predefinedConfig[0].mineEnergyNeed);
Andreas Zehender's avatar
Andreas Zehender committed
222
   customConfig.startPosX=
Laurent Montel's avatar
Laurent Montel committed
223
      game.readEntry("startPosX",predefinedConfig[0].startPosX);
Andreas Zehender's avatar
Andreas Zehender committed
224
   customConfig.startPosY=
Laurent Montel's avatar
Laurent Montel committed
225
      game.readEntry("startPosY",predefinedConfig[0].startPosY);
Andreas Zehender's avatar
Andreas Zehender committed
226
   customConfig.startVelX=
Laurent Montel's avatar
Laurent Montel committed
227
      game.readEntry("startVelX",predefinedConfig[0].startVelX);
Andreas Zehender's avatar
Andreas Zehender committed
228
   customConfig.startVelY=
Laurent Montel's avatar
Laurent Montel committed
229
      game.readEntry("startVelY",predefinedConfig[0].startVelY);
Andreas Zehender's avatar
Andreas Zehender committed
230
   customConfig.powerupLifeTime=
Laurent Montel's avatar
Laurent Montel committed
231
      game.readEntry("powerupLifeTime",predefinedConfig[0].powerupLifeTime);
Andreas Zehender's avatar
Andreas Zehender committed
232
   customConfig.powerupRefreshTime=
Laurent Montel's avatar
Laurent Montel committed
233
      game.readEntry("powerupRefreshTime",predefinedConfig[0].powerupRefreshTime);
Andreas Zehender's avatar
Andreas Zehender committed
234
   customConfig.powerupShieldAmount=
Laurent Montel's avatar
Laurent Montel committed
235
      game.readEntry("powerupShieldAmount",
Andreas Zehender's avatar
Andreas Zehender committed
236 237
                              predefinedConfig[0].powerupShieldAmount);
   customConfig.powerupEnergyAmount=
Laurent Montel's avatar
Laurent Montel committed
238
      game.readEntry("powerupEnergyAmount",
Andreas Zehender's avatar
Andreas Zehender committed
239
                              predefinedConfig[0].powerupEnergyAmount);
Andreas Zehender's avatar
Andreas Zehender committed
240

241 242
   if(Options::lastConfig() < predefinedConfigNum)
      config=modifyConfig(predefinedConfig[Options::lastConfig()]);
Andreas Zehender's avatar
Andreas Zehender committed
243 244 245 246
   else
      config=modifyConfig(customConfig);

   for(i=0;i<2;i++)
247
      ai[i]=new Ai(i,ship,bullets,mines,&config);
Andreas Zehender's avatar
Andreas Zehender committed
248 249 250 251
}

void MyMainView::writeConfig()
{
Laurent Montel's avatar
Port++  
Laurent Montel committed
252
   KConfigGroup game(KSharedConfig::openConfig(), "Game");
Laurent Montel's avatar
Laurent Montel committed
253

Stephan Kulow's avatar
Stephan Kulow committed
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
   game.writeEntry("gravity",customConfig.gravity);
   game.writeEntry("acceleration",customConfig.acc);
   game.writeEntry("bulletDamage",customConfig.bulletDamage);
   game.writeEntry("bulletLifeTime",customConfig.bulletLifeTime);
   game.writeEntry("bulletReloadTime",customConfig.bulletReloadTime);
   game.writeEntry("mineDamage",customConfig.mineDamage);
   game.writeEntry("shipDamage",customConfig.shipDamage);
   game.writeEntry("maxBullets",customConfig.maxBullets);
   game.writeEntry("maxMines",customConfig.maxMines);
   game.writeEntry("rotationSpeed",customConfig.rotationSpeed);
   game.writeEntry("shotSpeed",customConfig.shotSpeed);
   game.writeEntry("accEnergyNeed",customConfig.energyNeed);
   game.writeEntry("rotationEnergyNeed",customConfig.rotationEnergyNeed);
   game.writeEntry("sunEnergy",customConfig.sunEnergy);
   game.writeEntry("mineActivateTime",customConfig.mineActivateTime);
   game.writeEntry("mineReloadTime",customConfig.mineReloadTime);
   game.writeEntry("mineFuel",customConfig.mineFuel);
   game.writeEntry("shotEnergyNeed",customConfig.shotEnergyNeed);
   game.writeEntry("mineEnergyNeed",customConfig.mineEnergyNeed);

   game.writeEntry("startPosX",customConfig.startPosX);
   game.writeEntry("startPosY",customConfig.startPosY);
   game.writeEntry("startVelX",customConfig.startVelX);
   game.writeEntry("startVelY",customConfig.startVelY);

   game.writeEntry("powerupLifeTime",customConfig.powerupLifeTime);
   game.writeEntry("powerupRefreshTime",customConfig.powerupRefreshTime);
   game.writeEntry("powerupShieldAmount",customConfig.powerupShieldAmount);
   game.writeEntry("powerupEnergyAmount",customConfig.powerupEnergyAmount);
Andreas Zehender's avatar
Andreas Zehender committed
283 284 285 286 287
}

SConfig MyMainView::modifyConfig(SConfig conf)
{
   SConfig newConfig=conf;
288
   newConfig.gamespeed*=Options::refreshTime()/33.0;
Andreas Zehender's avatar
Andreas Zehender committed
289 290 291 292 293 294 295 296 297 298 299
   newConfig.acc*=newConfig.gamespeed;
   newConfig.rotationSpeed*=newConfig.gamespeed*M_PI/ROTNUM*4;
   newConfig.energyNeed*=newConfig.gamespeed;
   newConfig.rotationEnergyNeed*=newConfig.gamespeed;
   newConfig.mineActivateTime*=newConfig.gamespeed;

   return newConfig;
}

void MyMainView::keyPressEvent(QKeyEvent *ev)
{
300 301 302
    // if-statement kept for historical reasons, maybe not needed anymore
    if ( ((gameEnd>0.0) || (gameEnd<=-2.0)) && (!waitForStart) )
    {
Laurent Montel's avatar
Laurent Montel committed
303
      if(actionCollection->action(QLatin1String( "P1KeyLeft" ))->shortcuts().contains(ev->key()))
304
            playerKeyPressed[0][PlayerKeyLeft]=true;
Laurent Montel's avatar
Laurent Montel committed
305
      else if(actionCollection->action(QLatin1String( "P2KeyLeft" ))->shortcuts().contains(ev->key()))
306
            playerKeyPressed[1][PlayerKeyLeft]=true;
Laurent Montel's avatar
Laurent Montel committed
307 308

      else if(actionCollection->action(QLatin1String( "P1KeyRight" ))->shortcuts().contains(ev->key()))
309
            playerKeyPressed[0][PlayerKeyRight]=true;
Laurent Montel's avatar
Laurent Montel committed
310
      else if(actionCollection->action(QLatin1String( "P2KeyRight" ))->shortcuts().contains(ev->key()))
311
            playerKeyPressed[1][PlayerKeyRight]=true;
Laurent Montel's avatar
Laurent Montel committed
312 313

      else if(actionCollection->action(QLatin1String( "P1KeyAcc" ))->shortcuts().contains(ev->key()))
314
            playerKeyPressed[0][PlayerKeyAcc]=true;
Laurent Montel's avatar
Laurent Montel committed
315
      else if(actionCollection->action(QLatin1String( "P2KeyAcc" ))->shortcuts().contains(ev->key()))
316
            playerKeyPressed[1][PlayerKeyAcc]=true;
Laurent Montel's avatar
Laurent Montel committed
317 318

      else if(actionCollection->action(QLatin1String( "P1Shot" ))->shortcuts().contains(ev->key()))
319
            playerKeyPressed[0][PlayerKeyShot]=true;
Laurent Montel's avatar
Laurent Montel committed
320
      else if(actionCollection->action(QLatin1String( "P2Shot" ))->shortcuts().contains(ev->key()))
321
            playerKeyPressed[1][PlayerKeyShot]=true;
Laurent Montel's avatar
Laurent Montel committed
322 323

      else if(actionCollection->action(QLatin1String( "P1Mine" ))->shortcuts().contains(ev->key()))
324
            playerKeyPressed[0][PlayerKeyMine]=true;
Laurent Montel's avatar
Laurent Montel committed
325
      else if(actionCollection->action(QLatin1String( "P2Mine" ))->shortcuts().contains(ev->key()))
326 327
            playerKeyPressed[1][PlayerKeyMine]=true;
      else
328 329
        ev->ignore();
    }
Andreas Zehender's avatar
Andreas Zehender committed
330 331
}

332
void MyMainView::keyReleaseEvent(QKeyEvent *ev)
Andreas Zehender's avatar
Andreas Zehender committed
333
{
Laurent Montel's avatar
Laurent Montel committed
334
   if(actionCollection->action(QLatin1String( "P1KeyLeft" ))->shortcuts().contains(ev->key()))
335
      playerKeyPressed[0][PlayerKeyLeft]=false;
Laurent Montel's avatar
Laurent Montel committed
336
   else if(actionCollection->action(QLatin1String( "P2KeyLeft" ))->shortcuts().contains(ev->key()))
337
      playerKeyPressed[1][PlayerKeyLeft]=false;
Laurent Montel's avatar
Laurent Montel committed
338 339

   else if(actionCollection->action(QLatin1String( "P1KeyRight" ))->shortcuts().contains(ev->key()))
340
      playerKeyPressed[0][PlayerKeyRight]=false;
Laurent Montel's avatar
Laurent Montel committed
341
   else if(actionCollection->action(QLatin1String( "P2KeyRight" ))->shortcuts().contains(ev->key()))
342
      playerKeyPressed[1][PlayerKeyRight]=false;
Laurent Montel's avatar
Laurent Montel committed
343 344

   else if(actionCollection->action(QLatin1String( "P1KeyAcc" ))->shortcuts().contains(ev->key()))
345
      playerKeyPressed[0][PlayerKeyAcc]=false;
Laurent Montel's avatar
Laurent Montel committed
346
   else if(actionCollection->action(QLatin1String( "P2KeyAcc" ))->shortcuts().contains(ev->key()))
347
      playerKeyPressed[1][PlayerKeyAcc]=false;
Laurent Montel's avatar
Laurent Montel committed
348 349

   else if(actionCollection->action(QLatin1String( "P1Shot" ))->shortcuts().contains(ev->key()))
350
      playerKeyPressed[0][PlayerKeyShot]=false;
Laurent Montel's avatar
Laurent Montel committed
351
   else if(actionCollection->action(QLatin1String( "P2Shot" ))->shortcuts().contains(ev->key()))
352
      playerKeyPressed[1][PlayerKeyShot]=false;
Laurent Montel's avatar
Laurent Montel committed
353 354

   else if(actionCollection->action(QLatin1String( "P1Mine" ))->shortcuts().contains(ev->key()))
355
      playerKeyPressed[0][PlayerKeyMine]=false;
Laurent Montel's avatar
Laurent Montel committed
356
   else if(actionCollection->action(QLatin1String( "P2Mine" ))->shortcuts().contains(ev->key()))
357 358
      playerKeyPressed[1][PlayerKeyMine]=false;
   else
359
      ev->ignore();
Andreas Zehender's avatar
Andreas Zehender committed
360 361 362 363
}

void MyMainView::pause()
{
364 365 366
   if( !waitForStart )
   {
      pauseAction->setChecked( true );
367

368
      waitForStart=true;
Laurent Montel's avatar
Laurent Montel committed
369
      QAbstractEventDispatcher::instance()->unregisterTimers(this);
Hans Petter Bieker's avatar
Hans Petter Bieker committed
370
      emit setStatusText(i18n(" paused "), IDS_PAUSE);
371
   }
Andreas Zehender's avatar
Andreas Zehender committed
372 373 374 375 376
}

void MyMainView::resume()
{
   waitForStart=false;
377
   timerID=startTimer(Options::refreshTime());
Laurent Montel's avatar
Laurent Montel committed
378 379
   emit(setStatusText(QLatin1String( "" ),IDS_PAUSE));
   emit(setStatusText(QLatin1String( "" ),IDS_MAIN));
Andreas Zehender's avatar
Andreas Zehender committed
380 381
}

382 383 384 385 386 387 388 389 390
void MyMainView::start( )
{
   if( ( gameEnd <= 0.0 ) && ( gameEnd > -2.0 ) )
   {
      newRound( );
   }
   else if( waitForStart )
   {
      waitForStart = false;
391
      timerID=startTimer(Options::refreshTime());
Laurent Montel's avatar
Laurent Montel committed
392 393
      emit(setStatusText(QLatin1String( "" ),IDS_PAUSE));
      emit(setStatusText(QLatin1String( "" ),IDS_MAIN));
394 395 396 397 398 399 400 401 402
      pauseAction->setEnabled( true );
      pauseAction->setChecked( false );
   }
}

void MyMainView::stop()
{
   pauseAction->setEnabled( false );
   pauseAction->setChecked( false );
403

Laurent Montel's avatar
Laurent Montel committed
404
   QAbstractEventDispatcher::instance()->unregisterTimers(this);
405 406 407 408 409 410 411 412 413 414 415
   waitForStart = true;
}

void MyMainView::togglePause( )
{
   if( waitForStart )
      resume( );
   else
      pause( );
}

Andreas Zehender's avatar
Andreas Zehender committed
416 417 418 419
void MyMainView::resizeEvent(QResizeEvent *event)
{
   double mx,my;
   int i,current;
420
   int listsize; // used for caching QtList::size()
Andreas Zehender's avatar
Andreas Zehender committed
421 422 423 424 425

   mx=(event->size().width()-event->oldSize().width())/2.0;
   my=(event->size().height()-event->oldSize().height())/2.0;
   QWidget::resizeEvent(event);
   view.resize(width(),height());
Dirk Rathlev's avatar
Dirk Rathlev committed
426
   field.setSceneRect(0, 0, width(),height());
427 428

   // printf("%d %d\n",field.width(),field.height());
Dirk Rathlev's avatar
Dirk Rathlev committed
429

430 431
   sun->setPos(QPointF(width()/2-1-(sun->width()/2),
                       height()/2-1-(sun->height()/2)));
Andreas Zehender's avatar
Andreas Zehender committed
432 433 434

   for(i=0;i<2;i++)
   {
435
      // ship[i]->adoptSpritefieldBounds();
436
      ship[i]->moveBy(mx,my);
Laurent Montel's avatar
Laurent Montel committed
437

438 439
      listsize = mines[i]->size();
      for (current=0; current<listsize; current++)
440 441 442 443
      {
         // mine->adoptSpritefieldBounds();
         mines[i]->value(current)->moveBy(mx,my);
      }
Laurent Montel's avatar
Laurent Montel committed
444

445 446
      listsize = bullets[i]->size();
      for (current=0; current<listsize; current++)
447 448 449 450
      {
         // bullet->adoptSpritefieldBounds();
         bullets[i]->value(current)->moveBy(mx,my);
      }
Andreas Zehender's avatar
Andreas Zehender committed
451
   }
Andreas Zehender's avatar
Andreas Zehender committed
452 453
   if(textSprite)
      textSprite->moveBy((int)mx,(int)my);
Laurent Montel's avatar
Laurent Montel committed
454

455 456
   listsize = powerups.size();
   for (current=0; current<listsize; current++)
457 458 459
   {
      powerups[current]->moveBy(mx,my);
   }
Andreas Zehender's avatar
Andreas Zehender committed
460 461 462 463 464 465
}

void MyMainView::newRound()
{
   double mx,my;
   int i;
Andreas Zehender's avatar
Andreas Zehender committed
466

Waldo Bastian's avatar
Waldo Bastian committed
467
   timeToNextPowerup=random.getDouble() * config.powerupRefreshTime;
468
   qDeleteAll(powerups);
Andreas Zehender's avatar
Andreas Zehender committed
469
   powerups.clear();
Andreas Zehender's avatar
Andreas Zehender committed
470

Laurent Montel's avatar
Laurent Montel committed
471
   QAbstractEventDispatcher::instance()->unregisterTimers(this);
Andreas Zehender's avatar
Andreas Zehender committed
472 473
   mx=width()/2.0;
   my=height()/2.0;
474 475
   ship[0]->setPos(QPointF(mx+config.startPosX-(ship[0]->width()/2),
                           my+config.startPosY-(ship[0]->height()/2)));
Andreas Zehender's avatar
Andreas Zehender committed
476
   ship[0]->setRotation(0.0);
477

478 479
   ship[1]->setPos(QPointF(mx-config.startPosX-(ship[1]->width()/2),
                           my-config.startPosY-(ship[1]->height()/2)));
Andreas Zehender's avatar
Andreas Zehender committed
480 481 482 483 484 485 486
   ship[1]->setRotation(M_PI);

   ship[0]->setVelocity(config.startVelX,config.startVelY);
   ship[1]->setVelocity(-config.startVelX,-config.startVelY);
   for(i=0;i<2;i++)
   {
      ship[i]->show();
487
      ship[i]->setEnergy(MAX_ENERGY);
488
      ship[i]->setHitPoints(Options::startHitPoints(i));
Andreas Zehender's avatar
Andreas Zehender committed
489 490 491 492 493
      ship[i]->stop(false);
      ship[i]->setExplosion(-1);
      emit(energy(i,(int)ship[i]->getEnergy()));
      emit(hitPoints(i,ship[i]->getHitPoints()));
      bulletShot[i]=false;
494
      qDeleteAll(*bullets[i]);
Andreas Zehender's avatar
Andreas Zehender committed
495
      bullets[i]->clear();
Laurent Montel's avatar
Laurent Montel committed
496

497
      qDeleteAll(*mines[i]);
Andreas Zehender's avatar
Andreas Zehender committed
498
      mines[i]->clear();
Laurent Montel's avatar
Laurent Montel committed
499

Andreas Zehender's avatar
Andreas Zehender committed
500 501
      ship[i]->mine(0.0);
      ship[i]->bullet(0.0);
Andreas Zehender's avatar
Andreas Zehender committed
502 503
      ship[i]->setBulletPowerups(0);
      ship[i]->setMinePowerups(0);
Andreas Zehender's avatar
Andreas Zehender committed
504 505 506

      ai[i]->newRound();
   }
507
   qDeleteAll(explosions);
Andreas Zehender's avatar
Andreas Zehender committed
508 509 510 511 512 513 514 515 516 517 518 519 520
   explosions.clear();
   gameEnd=-10.0;
   for(i=0;i<PlayerKeyNum;i++)
   {
      playerKeyPressed[0][i]=false;
      playerKeyPressed[1][i]=false;
   }
   if(textSprite)
   {
      textSprite->hide();
      delete textSprite;
      textSprite=0;
   }
521
   //field.update();
522

523
   QString str = i18n("Press %1 to start",
524
                  actionCollection->action("game_start")->shortcut().toString(QKeySequence::NativeText));
525
   emit(setStatusText(str,IDS_MAIN));
Laurent Montel's avatar
Laurent Montel committed
526
   emit(setStatusText( QLatin1String( "" ), IDS_PAUSE ));
527
   stop( );
Andreas Zehender's avatar
Andreas Zehender committed
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
}

void MyMainView::newGame()
{
   int i;
   for(i=0;i<2;i++)
   {
      ship[i]->setWins(0);
      emit(wins(i,0));
   }
   newRound();
}

void MyMainView::timerEvent(QTimerEvent *event)
{
   unsigned w;
   int i;
Andreas Zehender's avatar
Andreas Zehender committed
545
   bool stopped = false;
Andreas Zehender's avatar
Andreas Zehender committed
546 547 548

   if(event->timerId()==timerID)
   {
Laurent Montel's avatar
Laurent Montel committed
549
      QAbstractEventDispatcher::instance()->unregisterTimers(this);
Andreas Zehender's avatar
Andreas Zehender committed
550 551 552 553 554
      if(gameEnd>0.0)
      {
         gameEnd-=1.0;
         if(gameEnd<=0.0)
         {
Andreas Zehender's avatar
Andreas Zehender committed
555 556 557 558 559 560 561
            stopped = true;
            if(textSprite)
            {
               textSprite->hide();
               delete textSprite;
               textSprite=0;
            }
Laurent Montel's avatar
Laurent Montel committed
562 563
            textSprite=new QGraphicsSimpleTextItem(0);
            field.addItem(textSprite);
Dirk Rathlev's avatar
Dirk Rathlev committed
564 565
	    // FIXME
           // textSprite->setTextFlags(Qt::AlignCenter);
566
	    textSprite->setBrush(QBrush(QColor(255,160,0)));
Laurent Montel's avatar
Port++  
Laurent Montel committed
567
            textSprite->setFont(QFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont).family(),14));
568
            textSprite->show( );
Andreas Zehender's avatar
Andreas Zehender committed
569 570 571
            if(ship[0]->getHitPoints()==0)
            {
               if(ship[1]->getHitPoints()==0)
572
                  textSprite->setText(i18n("draw round"));
Andreas Zehender's avatar
Andreas Zehender committed
573 574
               else
               {
575
                  textSprite->setText(i18n("blue player won the round"));
Andreas Zehender's avatar
Andreas Zehender committed
576 577 578 579 580 581 582
                  w=ship[1]->getWins()+1;
                  ship[1]->setWins(w);
                  emit(wins(1,w));
               }
            }
            else
            {
583
               textSprite->setText(i18n("red player won the round"));
Andreas Zehender's avatar
Andreas Zehender committed
584 585 586 587
               w=ship[0]->getWins()+1;
               ship[0]->setWins(w);
               emit(wins(0,w));
            }
Dirk Rathlev's avatar
Dirk Rathlev committed
588 589
            // must do this after setting text, because length is unknown until now
            textSprite->setPos(QPointF((width()-textSprite->boundingRect().width()) / 2,height()/2-90));
Laurent Montel's avatar
Laurent Montel committed
590

591
            QString str = i18n("Press %1 for new round",
592
                          actionCollection->action("game_start")->shortcut().toString(QKeySequence::NativeText));
Andreas Zehender's avatar
Andreas Zehender committed
593
            emit(setStatusText(str,IDS_MAIN));
594
            stop( );
Andreas Zehender's avatar
Andreas Zehender committed
595 596 597
         }
      }

Andreas Zehender's avatar
Andreas Zehender committed
598 599 600
      if( !stopped )
      {
         for(i=0;i<2;i++)
601
            if(Options::playerIsAi(i)&&(ship[i]->getHitPoints()>0))
Andreas Zehender's avatar
Andreas Zehender committed
602
               ai[i]->think();
603

Andreas Zehender's avatar
Andreas Zehender committed
604 605 606 607 608 609
         moveMines();
         moveBullets();
         moveExplosions();
         moveShips();
         calculatePowerups();
         collisions();
610
         timerID=startTimer(Options::refreshTime());
Andreas Zehender's avatar
Andreas Zehender committed
611
      }
612
     //field.update();
Andreas Zehender's avatar
Andreas Zehender committed
613 614 615 616 617 618 619 620 621 622 623 624 625
   }
}

void MyMainView::moveShips()
{
   int i,nf,olde;
   double nx,ny,en,nr;
   BulletSprite *bullet;
   MineSprite *mine;


   for(i=0;i<2;i++)
   {
626
      bool playerIsAi = Options::playerIsAi(i);
Andreas Zehender's avatar
Andreas Zehender committed
627 628 629 630 631 632 633 634 635 636 637 638
      olde=(int)ship[i]->getEnergy();
      if(ship[i]->getHitPoints()==0)
      {
         ship[i]->forward(config.gamespeed);
         ship[i]->calculateGravityAndEnergy(config.gravity,config.sunEnergy,
                                            config.gamespeed);
      }
      else
      {
         ship[i]->calculateGravityAndEnergy(config.gravity,config.sunEnergy,
                                         config.gamespeed);

639

640 641
         if(!playerIsAi&&playerKeyPressed[i][PlayerKeyRight]
            || playerIsAi&&ai[i]->rotateRight())
Andreas Zehender's avatar
Andreas Zehender committed
642 643 644
            ship[i]->rotateRight(config.rotationEnergyNeed,
                                 config.rotationSpeed);

645 646
         if(!playerIsAi&&playerKeyPressed[i][PlayerKeyLeft]
            || playerIsAi&&ai[i]->rotateLeft())
Andreas Zehender's avatar
Andreas Zehender committed
647 648
            ship[i]->rotateLeft(config.rotationEnergyNeed,
                                config.rotationSpeed);
649

Andreas Zehender's avatar
Andreas Zehender committed
650 651 652
         en=ship[i]->getEnergy();
         nr=ship[i]->getRotation();

Dirk Rathlev's avatar
Dirk Rathlev committed
653
         nf = 0;
Andreas Zehender's avatar
Andreas Zehender committed
654 655
         nx=cos(nr);
         ny=sin(nr);
656
         if ( ((!playerIsAi && playerKeyPressed[i][PlayerKeyAcc])
657
             || playerIsAi&&ai[i]->accelerate())
658
	     && (en>config.energyNeed) )
Andreas Zehender's avatar
Andreas Zehender committed
659 660
         {
            en-=config.energyNeed;
661 662
            ship[i]->setVelocity(ship[i]->xVelocity()+nx*config.acc,
                                 ship[i]->yVelocity()-ny*config.acc);
Laurent Montel's avatar
Laurent Montel committed
663

664 665 666 667 668 669 670 671 672 673
	    // limit speed to avoid "tunneling" through other objects
	    // FIXME: find a more elegant way
	    if (ship[i]->xVelocity()*ship[i]->xVelocity()+
		ship[i]->yVelocity()*ship[i]->yVelocity() > MAX_VELOCITY*MAX_VELOCITY)
	    {
		    double alpha;
		    alpha = fabs(atan(ship[i]->yVelocity()/ship[i]->xVelocity()));
		    ship[i]->setVelocity(MAX_VELOCITY*cos(alpha)*fabs(ship[i]->xVelocity())/ship[i]->xVelocity(),
                                 MAX_VELOCITY*sin(alpha)*fabs(ship[i]->yVelocity())/ship[i]->yVelocity());
	    }
Andreas Zehender's avatar
Andreas Zehender committed
674
         }
675 676
         if(en>MAX_ENERGY)
            en=MAX_ENERGY;
Andreas Zehender's avatar
Andreas Zehender committed
677 678

         ship[i]->forward(config.gamespeed);
Laurent Montel's avatar
Laurent Montel committed
679

Andreas Zehender's avatar
Andreas Zehender committed
680
             //Bullets and Mines
681 682
         if(!playerIsAi&&playerKeyPressed[i][PlayerKeyShot]
            ||playerIsAi&&ai[i]->shootBullet())
Andreas Zehender's avatar
Andreas Zehender committed
683 684 685
         {
            if((en>config.shotEnergyNeed) && (!ship[i]->reloadsBullet()))
            {
Andreas Zehender's avatar
Andreas Zehender committed
686
               if(bullets[i]->count() <
Andreas Zehender's avatar
Andreas Zehender committed
687
                  (config.maxBullets+ship[i]->getBulletPowerups()))
Andreas Zehender's avatar
Andreas Zehender committed
688 689 690
               {
                  ship[i]->bullet(config.bulletReloadTime);
                  en-=config.shotEnergyNeed;
691
		  if(i)
Laurent Montel's avatar
Laurent Montel committed
692
		     bullet=new BulletSprite(svgrender, QLatin1String( MV_BULLET2 ), i,
693 694
					     config.bulletLifeTime);
		  else
Laurent Montel's avatar
Laurent Montel committed
695
		     bullet=new BulletSprite(svgrender, QLatin1String( MV_BULLET1 ), i,
Andreas Zehender's avatar
Andreas Zehender committed
696
                                          config.bulletLifeTime);
697
		  field.addItem(bullet);
Dirk Rathlev's avatar
Dirk Rathlev committed
698
		  QPointF p;
699
		  p = ship[i]->mapToScene(ship[i]->center());
Dirk Rathlev's avatar
Dirk Rathlev committed
700
		  bullet->setPos(QPointF(p.x()+nx*SHOTDIST,p.y()-ny*SHOTDIST));
701 702 703
                  bullet->setVelocity(ship[i]->xVelocity()+nx*config.shotSpeed,
                                      ship[i]->yVelocity()-ny*config.shotSpeed);
                  // bullet->setBoundsAction(QwRealMobileSprite::Wrap);
Andreas Zehender's avatar
Andreas Zehender committed
704 705 706 707 708
                  bullet->show();
                  bullets[i]->append(bullet);
               }
            }
         }
709 710
         if(!Options::playerIsAi(i)&&playerKeyPressed[i][PlayerKeyMine]
            || Options::playerIsAi(i)&&ai[i]->layMine())
Andreas Zehender's avatar
Andreas Zehender committed
711 712 713
         {
            if((en>config.mineEnergyNeed) && (!ship[i]->reloadsMine()))
            {
Andreas Zehender's avatar
Andreas Zehender committed
714
               if(mines[i]->count() <
Andreas Zehender's avatar
Andreas Zehender committed
715
                  (config.maxMines+ship[i]->getMinePowerups()))
Andreas Zehender's avatar
Andreas Zehender committed
716 717 718
               {
                  ship[i]->mine(config.mineReloadTime);
                  en-=config.mineEnergyNeed;
Dirk Rathlev's avatar
Dirk Rathlev committed
719
		  if (i==0)
720
                     mine=new MineSprite(svgrender,animation[ID_MINE1],animation[ID_MINEEXPLO],i,
Dirk Rathlev's avatar
Dirk Rathlev committed
721 722
                                      config.mineActivateTime,config.mineFuel);
		  else
723
		     mine=new MineSprite(svgrender,animation[ID_MINE2],animation[ID_MINEEXPLO],i,
Andreas Zehender's avatar
Andreas Zehender committed
724
                                      config.mineActivateTime,config.mineFuel);
725
		  field.addItem(mine);
Dirk Rathlev's avatar
Dirk Rathlev committed
726
		  QPointF p;
727 728 729
		  mine->setPos(ship[i]->mapToScene(ship[i]->center()));
                  // move mine to center
                  mine->moveBy(-mine->center().x(),-mine->center().y());
Andreas Zehender's avatar
Andreas Zehender committed
730
                  mine->setVelocity(0,0);
731
                  //mine->setBoundsAction(QwRealMobileSprite::Wrap);
Andreas Zehender's avatar
Andreas Zehender committed
732 733 734 735 736 737 738 739 740 741 742 743 744 745
                  mine->show();
                  mines[i]->append(mine);
               }
            }
         }
         ship[i]->setEnergy(en);
         if(olde!=(int)en)
            emit(energy(i,(int)en));
      }
   }
}

void MyMainView::moveMines()
{
746
   int i;
Andreas Zehender's avatar
Andreas Zehender committed
747 748
   MineSprite* mine;
   int p;
749
   int listsize; // used for caching QtList::size()
Andreas Zehender's avatar
Andreas Zehender committed
750 751 752

   for(p=0;p<2;p++)
   {
753
      i=0;
754 755
      listsize = mines[p]->size();
      while (i<listsize)
756 757 758 759 760 761 762 763 764
      {
         mine = mines[p]->value(i);
         mine->calculateGravity(config.gravity,config.gamespeed);
         mine->forward(config.gamespeed);
         if(mine->over())
         {
            mine->hide();
            mines[p]->removeAt(i);
            delete mine;
765
            listsize--;
766 767 768 769
         }
         else
            i++;
      }
Andreas Zehender's avatar
Andreas Zehender committed
770 771 772 773 774
   }
}

void MyMainView::moveBullets()
{
775
   int i,j;
Andreas Zehender's avatar
Andreas Zehender committed
776
   BulletSprite *sp;
777
   int listsize; // used for caching QtList::size()
Andreas Zehender's avatar
Andreas Zehender committed
778 779 780

   for(i=0;i<2;i++)
   {
781
      j=0;
782 783
      listsize = bullets[i]->size();
      while (j<listsize)
784 785 786 787 788 789 790 791
      {
         sp = bullets[i]->value(j);
         sp->calculateGravity(config.gravity,config.gamespeed);
         sp->forward(config.gamespeed);
         if(sp->timeOut())
         {
            sp->hide();
            bullets[i]->removeAll(sp);
792
            listsize--;
793 794 795 796
         }
         else
            j++;
      }
Andreas Zehender's avatar
Andreas Zehender committed
797 798 799 800 801
   }
}

void MyMainView::moveExplosions()
{
802
   int i=0;
Andreas Zehender's avatar
Andreas Zehender committed
803
   ExplosionSprite *ex;
804
   int listsize; // used for caching QtList::size()
805 806
   listsize = explosions.size();
   while (i<listsize)
807 808 809 810 811 812 813
   {
      ex = explosions[i];
      ex->forward(config.gamespeed);
      if(ex->isOver())
      {
         explosions.removeAt(i);
         delete ex;
814
         listsize--;
815 816 817 818
      }
      else
         i++;
   }
Andreas Zehender's avatar
Andreas Zehender committed
819
}
Andreas Zehender's avatar
Andreas Zehender committed
820

Andreas Zehender's avatar
Andreas Zehender committed
821
void MyMainView::calculatePowerups()
Andreas Zehender's avatar
Andreas Zehender committed
822
{
823
   int i=0;
Andreas Zehender's avatar
Andreas Zehender committed
824
   PowerupSprite *sp;
825
   int listsize; // used for caching QtList::size()
826 827
   listsize = powerups.size();
   while (i<listsize)
828 829 830 831 832 833 834
   {
      sp = powerups[i];
      sp->setLifetime(sp->getLifetime()-config.gamespeed);
      if (sp->getLifetime()<0)
      {
         powerups.removeAt(i);
         delete sp;
835
         listsize--;
836 837 838 839
      }
      else
         i++;
   }
Andreas Zehender's avatar
Andreas Zehender committed
840 841
   timeToNextPowerup-=config.gamespeed;
   if(timeToNextPowerup<0)
Andreas Zehender's avatar
Andreas Zehender committed
842
   {
843
      int type,x,y;
Waldo Bastian's avatar
Waldo Bastian committed
844 845
      timeToNextPowerup= random.getDouble() * config.powerupRefreshTime;
      type= random.getLong(PowerupSprite::PowerupNum);
846
      sp=new PowerupSprite(svgrender,powerupelements[type],type,
847
                           config.powerupLifeTime);
848
      field.addItem(sp);
Andreas Zehender's avatar
Andreas Zehender committed
849 850
      do
      {
Waldo Bastian's avatar
Waldo Bastian committed
851 852
         x = random.getLong(width()-40)+20;
         y = random.getLong(height()-40)+20;
Andreas Zehender's avatar
Andreas Zehender committed
853 854
      }
      while(((x-width()/2)*(x-width()/2)+(y-height()/2)*(y-height()/2))<(50*50));