Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/towerdefenseFS15/src/modules/towerdefense/TowerDefense.cc @ 10340

Last change on this file since 10340 was 10340, checked in by erbj, 9 years ago

Tower upgrade now implemented and towers are now saved in the towerTurretMatrix and the Models in the towerModelMatrix

  • Property svn:eol-style set to native
File size: 15.0 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *  Author:
23 *
24 *   Co-authors:
25 *      ...
26 *
27 *NACHRICHT:
28 *
29 * Hier empfehle ich euch die gesamte Spielogik unter zu bringen. Viele Funktionen werden automatisch
30 * bei gewissen Ereignissen aufgerufen bzw. lösen Ereignisse aus
31 *
32 *Z.B:
33 * start() //wird aufgerufen, bevor das Spiel losgeht
34 * end() //wenn man diese Funktion aufruft wird
35 * pawnKilled() // wird aufgerufen, wenn ein Pawn stirbt (z.B: wenn )
36 * playerScored() // kann man aufrufen um dem Spieler Punkte zu vergeben.
37 *
38 *
39 *
40 *TIPP: Eclipse hilft euch schnell auf bereits vorhanden Funktionen zuzugreifen:
41 * einfach "this->" eingeben und kurz warten. Dann tauch eine Liste mit Vorschlägen auf. Wenn ihr jetzt weiter
42 * tippt, werden die Vorschläge entsprechend gefiltert.
43 *
44 *
45 *TIPP: schaut euch mal Tetris::createStone() an. Dort wird ein TetrisStone-Objekt (ControllableEntity) erzeugt,
46 * ihm ein Template zugewiesen (welches vorher im Level definiert wurde und dem CenterPoint übergeben wurde)
47 * Ähnlich könnt ihr vorgehen, um einen Turm zu erzeugen. (Zusätzlich braucht ein Turm noch einen Controller)
48 * z.B: WaypointPatrolController. Wenn kein Team zugewiesen wurde bekämpft ein WaypointPatrolController alles,
49 * was in seiner Reichweite liegt.
50 *
51 *
52 *HUD:
53 * Ein Gametype kann ein HUD (Head up Display haben.) Z.B: hat Pong eine Anzeige welcher Spieler wieviele Punkte hat.
54 * Generell kann man a) Grafiken oder b) Zeichen in einer HUD anzeigen.
55 * Fuer den ersten Schritt reicht reiner Text.
56 *
57 * a)
58 * PongScore.cc uebernehmen und eigene Klasse draus machen.
59 * Wenn ihr bloss anzeigen wollt wieviele Punkte der Spieler bereits erspielt hat (Punkte = Kapital fuer neue Tuerme) dann orientiert ihr euch an
60 * TetrisScore.cc (im pCuts branch): http://www.orxonox.net/browser/code/branches/pCuts/src/modules/tetris/TetrisScore.cc
61 * Ich habe TetrisScore lediglich dazu gebraucht, um eine Variable auf dem HUD auszugeben. Ein Objekt fuer statischen Text gibt es bereits.
62 *
63 * b)
64 * Im naesten Schritt erstellt man die Vorlage fuer das HUD-Objekt: siehe /data/overlays/pongHUD
65 * OverlayText ist eine Vorlage fuer statischen text zb: "Points Scored:". Aus mir nicht erklaerlichen Gruenden sollte man die OverlayText
66 * Objekte immer erst nach dem PongScore anlegen.
67 *
68 * c)  Im TowerDefense gamtype muss im Constructor noch das HUD-Template gesetzt werden.
69 *
70 * d) in CMakeLists.txt noch das Module includen das fuer die Overlays zustaendig ist. Siehe das gleiche File im Pong module.
71 *
72 *
73 *
74 */
75#include "TowerDefense.h"
76#include "TowerDefenseTower.h"
77#include "TowerDefenseCenterpoint.h"
78//#include "TDCoordinate.h"
79#include "worldentities/SpawnPoint.h"
80#include "worldentities/pawns/Pawn.h"
81#include "worldentities/pawns/SpaceShip.h"
82#include "controllers/WaypointController.h"
83#include "graphics/Model.h"
84#include "infos/PlayerInfo.h"
85#include "chat/ChatManager.h"
86#include "core/CoreIncludes.h"
87/* Part of a temporary hack to allow the player to add towers */
88#include "core/command/ConsoleCommand.h"
89
90namespace orxonox
91{
92    RegisterUnloadableClass(TowerDefense);
93
94    TowerDefense::TowerDefense(Context* context) : Deathmatch(context)
95    {
96        RegisterObject(TowerDefense);
97/*
98        for (int i=0; i < 16 ; i++){
99            for (int j = 0; j< 16 ; j++){
100                towermatrix[i][j] = NULL;
101            }
102        }*/
103
104
105
106        this->setHUDTemplate("TowerDefenseHUD");
107
108        //this->stats_ = new TowerDefensePlayerStats();
109
110        /* Temporary hack to allow the player to add towers and upgrade them */
111        this->dedicatedAddTower_ = createConsoleCommand( "addTower", createExecutor( createFunctor(&TowerDefense::addTower, this) ) );
112        this->dedicatedUpgradeTower_ = createConsoleCommand( "upgradeTower", createExecutor( createFunctor(&TowerDefense::upgradeTower, this) ) );
113    }
114
115    TowerDefense::~TowerDefense()
116    {
117        /* Part of a temporary hack to allow the player to add towers */
118        if (this->isInitialized())
119        {
120            if( this->dedicatedAddTower_ )
121                delete this->dedicatedAddTower_;
122        }
123    }
124
125    void TowerDefense::setCenterpoint(TowerDefenseCenterpoint *centerpoint)
126    {
127        orxout() << "Centerpoint now setting..." << endl;
128        this->center_ = centerpoint;
129        orxout() << "Centerpoint now set..." << endl;
130    }
131
132    void TowerDefense::start()
133    {
134
135        Deathmatch::start();
136
137// Waypoints: [1,3] [10,3] [10,11] [13,11] -> add the points to a matrix so the player cant place towers on the path
138        for (int i=0; i < 16 ; i++){
139            for (int j = 0; j< 16 ; j++){
140                towerModelMatrix[i][j] = NULL;
141                towerTurretMatrix[i][j] = NULL;
142            }
143        }
144
145        Model* dummyModel = new Model(this->center_->getContext());
146
147        //the path of the spacehips has to be blocked, so that no towers can be build there
148        for (int k=0; k<3; k++)
149            towerModelMatrix[1][k]=dummyModel;
150        for (int l=1; l<11; l++)
151                towerModelMatrix[l][3]=dummyModel;
152        for (int m=3; m<12; m++)
153                towerModelMatrix[10][m]=dummyModel;
154        for (int n=10; n<14; n++)
155                towerModelMatrix[n][11]=dummyModel;
156        for (int o=13; o<16; o++)
157                towerModelMatrix[13][o]=dummyModel;
158
159
160        //set initial credits, lifes and WaveNumber
161        this->setCredit(1000);
162        this->setLifes(100);
163        this->setWaveNumber(0);
164        time=0.0;
165
166        /*
167        //adds initial towers
168        for (int i=0; i <7; i++){
169            addTower(i+3,4);
170        }
171                */
172    }
173
174    // Generates a TowerDefenseEnemy. Uses Template "enemytowerdefense". Sets position at first waypoint of path.
175    void TowerDefense::addTowerDefenseEnemy(std::vector<TDCoordinate*> path, int templatenr){
176
177
178        TowerDefenseEnemy* en1 = new TowerDefenseEnemy(this->center_->getContext());
179       
180        switch(templatenr)
181        {
182        case 1 :
183            en1->addTemplate("enemytowerdefense1");
184            en1->setScale(3);
185            en1->setHealth(en1->getHealth() + this->getWaveNumber()*4);
186            break;
187
188        case 2 :
189            en1->addTemplate("enemytowerdefense2");
190            en1->setScale(2);
191            en1->setHealth(en1->getHealth() + this->getWaveNumber()*4);
192            //  en1->setShieldHealth(en1->getShield() = this->getWaveNumber()*2))
193            break;
194
195        case 3 :
196            en1->addTemplate("enemytowerdefense3");
197            en1->setScale(1);
198            en1->setHealth(en1->getHealth() + this->getWaveNumber()*4);
199            break;
200        }
201
202        en1->setTeam(2);
203        en1->getController();
204        en1->setPosition(path.at(0)->get3dcoordinate());
205        TowerDefenseEnemyvector.push_back(en1);
206
207        for(unsigned int i = 0; i < path.size(); ++i)
208        {
209            en1->addWaypoint((path.at(i)));
210        }
211    }
212
213
214    void TowerDefense::end()
215    {
216
217        Deathmatch::end();
218        ChatManager::message("Match is over! Gameover!");
219
220    }
221
222    //not working yet
223    void TowerDefense::upgradeTower(int x,int y)
224    {
225        const int upgradeCost = 20;
226
227        if (!this->hasEnoughCreditForTower(upgradeCost))
228        {
229            orxout() << "not enough credit: " << (this->getCredit()) << " available, " << upgradeCost << " needed.";
230            return;
231        }
232
233
234        Model* dummyModel2 = new Model(this->center_->getContext());
235
236        if (towerModelMatrix [x][y] == NULL || (towerModelMatrix [x][y])->getMeshSource() == dummyModel2->getMeshSource())
237        {
238            orxout() << "no tower on this position" << endl;
239            return;
240        }
241
242        else
243        {
244            (towerTurretMatrix [x][y])->upgradeTower();
245            this->buyTower(upgradeCost);
246        }
247    }
248
249    /*adds Tower at Position (x,y) and reduces credit and adds the point to the towermatrix. template ("towerturret")
250    so towers have ability if the turrets
251
252    */
253    void TowerDefense::addTower(int x, int y)
254    {
255        const int towerCost = 20;
256
257        if (!this->hasEnoughCreditForTower(towerCost))
258        {
259            orxout() << "not enough credit: " << (this->getCredit()) << " available, " << towerCost << " needed.";
260            return;
261        }
262
263        if (towerModelMatrix [x][y]!=NULL)
264        {
265            orxout() << "not possible to put tower here!!" << endl;
266            return;
267        }
268
269/*
270        unsigned int width = this->center_->getWidth();
271        unsigned int height = this->center_->getHeight();
272*/
273
274        int tileScale = (int) this->center_->getTileScale();
275
276        if (x > 15 || y > 15 || x < 0 || y < 0)
277        {
278            //Hard coded: TODO: let this depend on the centerpoint's height, width and fieldsize (fieldsize doesn't exist yet)
279            orxout() << "Can not add Tower: x and y should be between 0 and 15" << endl;
280            return;
281        }
282
283        orxout() << "Will add tower at (" << (x-8) * tileScale << "," << (y-8) * tileScale << ")" << endl;
284
285
286
287        //Create Model
288        Model* newtowermodel = new Model(this->center_->getContext());
289        newtowermodel->setMeshSource("Tower.mesh");
290        newtowermodel->setScale(45);
291        newtowermodel->setPosition(static_cast<float>((x-8) * tileScale), static_cast<float>((y-8) * tileScale), 50);
292
293
294
295        //Creates tower
296        TowerDefenseTower* towernew = new TowerDefenseTower(this->center_->getContext());
297        towernew->setPosition(static_cast<float>((x-8) * tileScale), static_cast<float>((y-8) * tileScale), 275);
298        towernew->setGame(this);
299        towernew->setTeam(1);
300
301        //Reduce credit
302         this->buyTower(towerCost);
303         towerModelMatrix [x][y]= newtowermodel;
304         towerTurretMatrix [x][y]= towernew;
305    }
306
307    bool TowerDefense::hasEnoughCreditForTower(int towerCost)
308    {
309        return ((this->getCredit()) >= towerCost);
310    }
311
312
313    bool TowerDefense::hasEnoughCreditForUpgrade()
314    {
315        return true;
316    }
317
318 
319    void TowerDefense::tick(float dt)
320    {
321        SUPER(TowerDefense, tick, dt);
322        time +=dt;
323
324        TDCoordinate* coord1 = new TDCoordinate(1,1);
325        std::vector<TDCoordinate*> path;
326        path.push_back(coord1);
327        if(time>1 && TowerDefenseEnemyvector.size() < 30)
328        {
329            //adds different types of enemys depending on the WaveNumber
330            addTowerDefenseEnemy(path, this->getWaveNumber() % 3 +1 );
331            time = time-1;
332        }
333
334        Vector3* endpoint = new Vector3(500, 700, 150);
335        //if ships are at the end they get destroyed
336        for(unsigned int i =0; i < TowerDefenseEnemyvector.size(); ++i)
337        {
338            if(TowerDefenseEnemyvector.at(i) != NULL && TowerDefenseEnemyvector.at(i)->isAlive())
339            {
340                //destroys enemys at the end of the path and reduces the life by 1. no credits gifted
341
342                Vector3 ship = TowerDefenseEnemyvector.at(i)->getRVWorldPosition();
343                float distance = ship.distance(*endpoint);
344
345                if(distance <50){
346                    TowerDefenseEnemyvector.at(i)->destroy();
347                    this->reduceLifes(1);
348                    this->buyTower(1);
349                    if (this->getLifes()==0)
350                    {
351                        this->end();
352                    }
353                }
354            }
355        }
356        //goes thorugh vector to see if an enemy is still alive. if not next wave is launched
357        int count= 0;
358        for(unsigned int i =0; i < TowerDefenseEnemyvector.size(); ++i)
359        {
360            if(TowerDefenseEnemyvector.at(i)!= NULL)
361            {
362                ++count;
363            }
364        }
365
366        if(count== 0)
367        {
368            time2 +=dt;
369            if(time2 > 10)
370            {
371                TowerDefenseEnemyvector.clear();
372                this->nextwave();
373                time=0;
374                time2=0;
375            }
376        }
377
378
379    }
380
381    // Function to test if we can add waypoints using code only. Doesn't work yet
382
383    // THE PROBLEM: WaypointController's getControllableEntity() returns null, so it won't track. How do we get the controlableEntity to NOT BE NULL???
384    /*
385    void TowerDefense::addWaypointsAndFirstEnemy()
386    {
387        SpaceShip *newShip = new SpaceShip(this->center_);
388        newShip->addTemplate("spaceshipassff");
389
390        WaypointController *newController = new WaypointController(newShip);
391        newController->setAccuracy(3);
392
393        Model *wayPoint1 = new Model(newController);
394        wayPoint1->setMeshSource("crate.mesh");
395        wayPoint1->setPosition(7,-7,5);
396        wayPoint1->setScale(0.2);
397
398        Model *wayPoint2 = new Model(newController);
399        wayPoint2->setMeshSource("crate.mesh");
400        wayPoint2->setPosition(7,7,5);
401        wayPoint2->setScale(0.2);
402
403        newController->addWaypoint(wayPoint1);
404        newController->addWaypoint(wayPoint2);
405
406        // The following line causes the game to crash
407
408        newShip->setController(newController);
409//        newController -> getPlayer() -> startControl(newShip);
410        newShip->setPosition(-7,-7,5);
411        newShip->setScale(0.1);
412        //newShip->addSpeed(1);
413
414
415
416//      this->center_->attach(newShip);
417    }
418    */
419    /*
420    void TowerDefense::playerEntered(PlayerInfo* player)
421    {
422        Deathmatch::playerEntered(player);
423
424        const std::string& message = player->getName() + " entered the game";
425        ChatManager::message(message);
426    }
427
428    bool TowerDefense::playerLeft(PlayerInfo* player)
429    {
430        bool valid_player = Deathmatch::playerLeft(player);
431
432        if (valid_player)
433        {
434            const std::string& message = player->getName() + " left the game";
435            ChatManager::message(message);
436        }
437
438        return valid_player;
439    }
440
441
442    void TowerDefense::pawnKilled(Pawn* victim, Pawn* killer)
443    {
444        if (victim && victim->getPlayer())
445        {
446            std::string message;
447            if (killer)
448            {
449                if (killer->getPlayer())
450                    message = victim->getPlayer()->getName() + " was killed by " + killer->getPlayer()->getName();
451                else
452                    message = victim->getPlayer()->getName() + " was killed";
453            }
454            else
455                message = victim->getPlayer()->getName() + " died";
456
457            ChatManager::message(message);
458        }
459
460        Deathmatch::pawnKilled(victim, killer);
461    }
462
463    void TowerDefense::playerScored(PlayerInfo* player, int score)
464    {
465        Gametype::playerScored(player, score);
466    }*/
467}
Note: See TracBrowser for help on using the repository browser.