Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 10351 was 10351, checked in by landauf, 9 years ago

using the 'official' way to define a non-static console command

  • Property svn:eol-style set to native
File size: 15.2 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    static const std::string __CC_addTower_name  = "addTower";
93    static const std::string __CC_upgradeTower_name = "upgradeTower";
94
95    SetConsoleCommand("TowerDefense", __CC_addTower_name,  &TowerDefense::addTower ).addShortcut().defaultValues(1);
96    SetConsoleCommand("TowerDefense", __CC_upgradeTower_name, &TowerDefense::upgradeTower).addShortcut().defaultValues(0);
97
98    RegisterUnloadableClass(TowerDefense);
99
100    TowerDefense::TowerDefense(Context* context) : Deathmatch(context)
101    {
102        RegisterObject(TowerDefense);
103/*
104        for (int i=0; i < 16 ; i++){
105            for (int j = 0; j< 16 ; j++){
106                towermatrix[i][j] = NULL;
107            }
108        }*/
109
110
111
112        this->setHUDTemplate("TowerDefenseHUD");
113
114        //this->stats_ = new TowerDefensePlayerStats();
115
116        ModifyConsoleCommand(__CC_addTower_name).setObject(this);
117        ModifyConsoleCommand(__CC_upgradeTower_name).setObject(this);
118    }
119
120    TowerDefense::~TowerDefense()
121    {
122        /* Part of a temporary hack to allow the player to add towers */
123        if (this->isInitialized())
124        {
125            ModifyConsoleCommand(__CC_addTower_name).setObject(NULL);
126            ModifyConsoleCommand(__CC_upgradeTower_name).setObject(NULL);
127        }
128    }
129
130    void TowerDefense::setCenterpoint(TowerDefenseCenterpoint *centerpoint)
131    {
132        orxout() << "Centerpoint now setting..." << endl;
133        this->center_ = centerpoint;
134        orxout() << "Centerpoint now set..." << endl;
135    }
136
137    void TowerDefense::start()
138    {
139
140        Deathmatch::start();
141
142// Waypoints: [1,3] [10,3] [10,11] [13,11] -> add the points to a matrix so the player cant place towers on the path
143        for (int i=0; i < 16 ; i++){
144            for (int j = 0; j< 16 ; j++){
145                towerModelMatrix[i][j] = NULL;
146                towerTurretMatrix[i][j] = NULL;
147            }
148        }
149
150        Model* dummyModel = new Model(this->center_->getContext());
151
152        //the path of the spacehips has to be blocked, so that no towers can be build there
153        for (int k=0; k<3; k++)
154            towerModelMatrix[1][k]=dummyModel;
155        for (int l=1; l<11; l++)
156                towerModelMatrix[l][3]=dummyModel;
157        for (int m=3; m<12; m++)
158                towerModelMatrix[10][m]=dummyModel;
159        for (int n=10; n<14; n++)
160                towerModelMatrix[n][11]=dummyModel;
161        for (int o=13; o<16; o++)
162                towerModelMatrix[13][o]=dummyModel;
163
164
165        //set initial credits, lifes and WaveNumber
166        this->setCredit(1000);
167        this->setLifes(100);
168        this->setWaveNumber(0);
169        time=0.0;
170
171        /*
172        //adds initial towers
173        for (int i=0; i <7; i++){
174            addTower(i+3,4);
175        }
176                */
177    }
178
179    // Generates a TowerDefenseEnemy. Uses Template "enemytowerdefense". Sets position at first waypoint of path.
180    void TowerDefense::addTowerDefenseEnemy(std::vector<TDCoordinate*> path, int templatenr){
181
182
183        TowerDefenseEnemy* en1 = new TowerDefenseEnemy(this->center_->getContext());
184       
185        switch(templatenr)
186        {
187        case 1 :
188            en1->addTemplate("enemytowerdefense1");
189            en1->setScale(3);
190            en1->setHealth(en1->getHealth() + this->getWaveNumber()*4);
191            break;
192
193        case 2 :
194            en1->addTemplate("enemytowerdefense2");
195            en1->setScale(2);
196            en1->setHealth(en1->getHealth() + this->getWaveNumber()*4);
197            //  en1->setShieldHealth(en1->getShield() = this->getWaveNumber()*2))
198            break;
199
200        case 3 :
201            en1->addTemplate("enemytowerdefense3");
202            en1->setScale(1);
203            en1->setHealth(en1->getHealth() + this->getWaveNumber()*4);
204            break;
205        }
206
207        en1->setTeam(2);
208        en1->getController();
209        en1->setPosition(path.at(0)->get3dcoordinate());
210        TowerDefenseEnemyvector.push_back(en1);
211
212        for(unsigned int i = 0; i < path.size(); ++i)
213        {
214            en1->addWaypoint((path.at(i)));
215        }
216    }
217
218
219    void TowerDefense::end()
220    {
221
222        Deathmatch::end();
223        ChatManager::message("Match is over! Gameover!");
224
225    }
226
227    //not working yet
228    void TowerDefense::upgradeTower(int x,int y)
229    {
230        const int upgradeCost = 20;
231
232        if (!this->hasEnoughCreditForTower(upgradeCost))
233        {
234            orxout() << "not enough credit: " << (this->getCredit()) << " available, " << upgradeCost << " needed.";
235            return;
236        }
237
238
239        Model* dummyModel2 = new Model(this->center_->getContext());
240
241        if (towerModelMatrix [x][y] == NULL || (towerModelMatrix [x][y])->getMeshSource() == dummyModel2->getMeshSource())
242        {
243            orxout() << "no tower on this position" << endl;
244            return;
245        }
246
247        else
248        {
249            (towerTurretMatrix [x][y])->upgradeTower();
250            this->buyTower(upgradeCost);
251        }
252    }
253
254    /*adds Tower at Position (x,y) and reduces credit and adds the point to the towermatrix. template ("towerturret")
255    so towers have ability if the turrets
256
257    */
258    void TowerDefense::addTower(int x, int y)
259    {
260        const int towerCost = 20;
261
262        if (!this->hasEnoughCreditForTower(towerCost))
263        {
264            orxout() << "not enough credit: " << (this->getCredit()) << " available, " << towerCost << " needed.";
265            return;
266        }
267
268        if (towerModelMatrix [x][y]!=NULL)
269        {
270            orxout() << "not possible to put tower here!!" << endl;
271            return;
272        }
273
274/*
275        unsigned int width = this->center_->getWidth();
276        unsigned int height = this->center_->getHeight();
277*/
278
279        int tileScale = (int) this->center_->getTileScale();
280
281        if (x > 15 || y > 15 || x < 0 || y < 0)
282        {
283            //Hard coded: TODO: let this depend on the centerpoint's height, width and fieldsize (fieldsize doesn't exist yet)
284            orxout() << "Can not add Tower: x and y should be between 0 and 15" << endl;
285            return;
286        }
287
288        orxout() << "Will add tower at (" << (x-8) * tileScale << "," << (y-8) * tileScale << ")" << endl;
289
290
291
292        //Create Model
293        Model* newtowermodel = new Model(this->center_->getContext());
294        newtowermodel->setMeshSource("Tower.mesh");
295        newtowermodel->setScale(45);
296        newtowermodel->setPosition(static_cast<float>((x-8) * tileScale), static_cast<float>((y-8) * tileScale), 50);
297
298
299
300        //Creates tower
301        TowerDefenseTower* towernew = new TowerDefenseTower(this->center_->getContext());
302        towernew->setPosition(static_cast<float>((x-8) * tileScale), static_cast<float>((y-8) * tileScale), 275);
303        towernew->setGame(this);
304        towernew->setTeam(1);
305
306        //Reduce credit
307         this->buyTower(towerCost);
308         towerModelMatrix [x][y]= newtowermodel;
309         towerTurretMatrix [x][y]= towernew;
310    }
311
312    bool TowerDefense::hasEnoughCreditForTower(int towerCost)
313    {
314        return ((this->getCredit()) >= towerCost);
315    }
316
317
318    bool TowerDefense::hasEnoughCreditForUpgrade()
319    {
320        return true;
321    }
322
323 
324    void TowerDefense::tick(float dt)
325    {
326        SUPER(TowerDefense, tick, dt);
327        time +=dt;
328
329        TDCoordinate* coord1 = new TDCoordinate(1,1);
330        std::vector<TDCoordinate*> path;
331        path.push_back(coord1);
332        if(time>1 && TowerDefenseEnemyvector.size() < 30)
333        {
334            //adds different types of enemys depending on the WaveNumber
335            addTowerDefenseEnemy(path, this->getWaveNumber() % 3 +1 );
336            time = time-1;
337        }
338
339        Vector3* endpoint = new Vector3(500, 700, 150);
340        //if ships are at the end they get destroyed
341        for(unsigned int i =0; i < TowerDefenseEnemyvector.size(); ++i)
342        {
343            if(TowerDefenseEnemyvector.at(i) != NULL && TowerDefenseEnemyvector.at(i)->isAlive())
344            {
345                //destroys enemys at the end of the path and reduces the life by 1. no credits gifted
346
347                Vector3 ship = TowerDefenseEnemyvector.at(i)->getRVWorldPosition();
348                float distance = ship.distance(*endpoint);
349
350                if(distance <50){
351                    TowerDefenseEnemyvector.at(i)->destroy();
352                    this->reduceLifes(1);
353                    this->buyTower(1);
354                    if (this->getLifes()==0)
355                    {
356                        this->end();
357                    }
358                }
359            }
360        }
361        //goes thorugh vector to see if an enemy is still alive. if not next wave is launched
362        int count= 0;
363        for(unsigned int i =0; i < TowerDefenseEnemyvector.size(); ++i)
364        {
365            if(TowerDefenseEnemyvector.at(i)!= NULL)
366            {
367                ++count;
368            }
369        }
370
371        if(count== 0)
372        {
373            time2 +=dt;
374            if(time2 > 10)
375            {
376                TowerDefenseEnemyvector.clear();
377                this->nextwave();
378                time=0;
379                time2=0;
380            }
381        }
382
383
384    }
385
386    // Function to test if we can add waypoints using code only. Doesn't work yet
387
388    // THE PROBLEM: WaypointController's getControllableEntity() returns null, so it won't track. How do we get the controlableEntity to NOT BE NULL???
389    /*
390    void TowerDefense::addWaypointsAndFirstEnemy()
391    {
392        SpaceShip *newShip = new SpaceShip(this->center_);
393        newShip->addTemplate("spaceshipassff");
394
395        WaypointController *newController = new WaypointController(newShip);
396        newController->setAccuracy(3);
397
398        Model *wayPoint1 = new Model(newController);
399        wayPoint1->setMeshSource("crate.mesh");
400        wayPoint1->setPosition(7,-7,5);
401        wayPoint1->setScale(0.2);
402
403        Model *wayPoint2 = new Model(newController);
404        wayPoint2->setMeshSource("crate.mesh");
405        wayPoint2->setPosition(7,7,5);
406        wayPoint2->setScale(0.2);
407
408        newController->addWaypoint(wayPoint1);
409        newController->addWaypoint(wayPoint2);
410
411        // The following line causes the game to crash
412
413        newShip->setController(newController);
414//        newController -> getPlayer() -> startControl(newShip);
415        newShip->setPosition(-7,-7,5);
416        newShip->setScale(0.1);
417        //newShip->addSpeed(1);
418
419
420
421//      this->center_->attach(newShip);
422    }
423    */
424    /*
425    void TowerDefense::playerEntered(PlayerInfo* player)
426    {
427        Deathmatch::playerEntered(player);
428
429        const std::string& message = player->getName() + " entered the game";
430        ChatManager::message(message);
431    }
432
433    bool TowerDefense::playerLeft(PlayerInfo* player)
434    {
435        bool valid_player = Deathmatch::playerLeft(player);
436
437        if (valid_player)
438        {
439            const std::string& message = player->getName() + " left the game";
440            ChatManager::message(message);
441        }
442
443        return valid_player;
444    }
445
446
447    void TowerDefense::pawnKilled(Pawn* victim, Pawn* killer)
448    {
449        if (victim && victim->getPlayer())
450        {
451            std::string message;
452            if (killer)
453            {
454                if (killer->getPlayer())
455                    message = victim->getPlayer()->getName() + " was killed by " + killer->getPlayer()->getName();
456                else
457                    message = victim->getPlayer()->getName() + " was killed";
458            }
459            else
460                message = victim->getPlayer()->getName() + " died";
461
462            ChatManager::message(message);
463        }
464
465        Deathmatch::pawnKilled(victim, killer);
466    }
467
468    void TowerDefense::playerScored(PlayerInfo* player, int score)
469    {
470        Gametype::playerScored(player, score);
471    }*/
472}
Note: See TracBrowser for help on using the repository browser.