-
Notifications
You must be signed in to change notification settings - Fork 0
/
galcon.cpp
1003 lines (861 loc) · 28.4 KB
/
galcon.cpp
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
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2013 Auston Sterling
See license.txt for copying permission.
-----Galcon Game Main Body-----
Auston Serling
Contains the main body for the game "Galcon" (Unnamed so far).
*/
#include "planet.h"
#include "fleet.h"
#include "projectile.h"
#include "vec2f.h"
#include "ai.h"
#include "lineDrawer.h"
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <list>
#include <cmath>
#include <sstream>
#include <ctime>
#include <cstdlib>
const int SCREEN_WIDTH = 1000;
const int SCREEN_HEIGHT = 750;
const int LEVEL_WIDTH = 1000;
const int LEVEL_HEIGHT = 750;
const int CAMERA_SPEED = 400;
const int FPS_CAP = 60;
SDL_Surface* loadImage(std::string filename)
{
//The image that's loaded
SDL_Surface *loadedImage = NULL;
//The optimized surface
SDL_Surface *optimizedImage = NULL;
//Make all images look in images folder
filename = "images/" + filename;
//Load the file
loadedImage = IMG_Load(filename.c_str());
//If the image loaded
if (loadedImage != NULL)
{
//Create an optimized surface
optimizedImage = SDL_DisplayFormat(loadedImage);
//Free the old surface
SDL_FreeSurface(loadedImage);
//If the surface was optimized
if (optimizedImage != NULL)
{
//Color key surface
SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, SDL_MapRGB( optimizedImage->format, 160, 150, 0 ) );
}
}
return optimizedImage;
}
//Main function
int main(int argc, char* argv[])
{
/*
-----
// INITIALIZATION
-----
*/
//Seed RNG
srand(time(NULL));
//Initialize all SDL subsystems
if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
{
return 1;
}
//Initialize SDL_TTF
TTF_Init();
TTF_Font * planetFont = TTF_OpenFont("corbel.ttf", 20);
//Set up the screen
SDL_Surface* screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_SWSURFACE);
//Make sure screen set up
if (screen == NULL)
{
return false;
}
//Set the window caption
SDL_WM_SetCaption("GAEM", NULL);
//Create an event manager
SDL_Event event;
//Store keystates
Uint8* keystates;
//Set up camera
SDL_Rect camera = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT};
float camerax = 0;
float cameray = 0;
/*
-----
GAME SETUP
-----
*/
//Set up ship stats
std::vector<ShipStats> shipstats(10);
for (int i = 0; i < 10; i++)
{
shipstats[i].attack = i+1;
shipstats[i].defense = i+1;
shipstats[i].speed = DEFAULT_FLEET_SPEED;
shipstats[i].interceptRange = 200;
shipstats[i].interceptDamage = 0.1;
shipstats[i].interceptCD = 250;
}
//Set up ship type 1: Heavy ship
shipstats[1].attack = 3;
shipstats[1].defense = 2;
shipstats[1].speed = DEFAULT_FLEET_SPEED/2;
//Set up ship type 2: Fiery attack ship
shipstats[2].attack = 2;
shipstats[2].defense = 1;
shipstats[2].speed = DEFAULT_FLEET_SPEED*1.25;
//Set up buildings and building rules
std::list<Building> buildings;
std::vector<std::list<Building*> > buildRules;
buildRules.resize(2);
SDL_Surface* b01 = loadImage("b01.png");
SDL_Surface* bc01 = loadImage("bc01.png");
SDL_Surface* b02 = loadImage("b02.png");
SDL_Surface* bc02 = loadImage("bc02.png");
buildings.push_back(Building(b01, bc01, "build 0 2")); //0
buildings.push_back(Building(b02, bc02, "fire damage 2 1")); //1
buildings.push_back(Building(b01, bc01, "build 1 4")); //2
buildings.push_back(Building(b01, bc01, "build 2 2")); //3
buildings.push_back(Building(b02, bc02, "aura damage 1 total")); //4
//0
std::list<Building>::iterator bi = buildings.begin();
buildRules[0].push_back(&(*bi));
bi->setBuildTime(15000);
bi++;
//1
buildRules[0].push_back(&(*bi));
bi->setBuildTime(10000);
bi->setRange(250);
bi++;
//2
buildRules[0].push_back(&(*bi));
bi->setBuildTime(15000);
bi++;
//3
buildRules[1].push_back(&(*bi));
bi->setBuildTime(15000);
bi++;
//4
buildRules[1].push_back(&(*bi));
bi->setBuildTime(10000);
bi->setRange(200);
bi->setCD(1000);
//Building images are now in rotation caches
SDL_FreeSurface(b01);
SDL_FreeSurface(bc01);
SDL_FreeSurface(b02);
SDL_FreeSurface(bc02);
//Create a list of planets
std::list<Planet> planets;
//The standard rate of production of basic ship 0
float ship0rate = 1.0;
//The array of indicators
SDL_Surface* indicator[3];
indicator[1] = loadImage("selectorb.png");
indicator[2] = loadImage("selectorr.png");
SDL_Surface* planet0img = loadImage("planet0.png");
SDL_Surface* planet1img = loadImage("planet1.png");
SDL_Surface* planet1_1img = loadImage("planet1-1.png");
//Create the planets at random
//First, create two home planets
std::vector<int> homestart;
homestart.resize(1,3);
planets.push_back(Planet(planet0img, 1.0,
Vec2f(rand()%100, 100 + rand()%(LEVEL_HEIGHT-200)), 0));
planets.back().setOwner(1, indicator);
planets.back().setShipRate(0, ship0rate);
planets.back().setRotSpeed(M_PI/20);
planets.back().addShips(3, 0);
planets.push_back(Planet(planet0img, 1.0,
Vec2f(LEVEL_WIDTH-(2*UNSCALED_PLANET_RADIUS)-(rand()%100),
100 + rand()%(LEVEL_HEIGHT-200)), 0));
planets.back().setOwner(2, indicator);
planets.back().setShipRate(0, ship0rate);
planets.back().setRotSpeed(M_PI/20);
planets.back().addShips(3, 0);
//Now repeatedly create planets until either a target density is reached
//or we go too many tries without finding a spot for a new planet.
char tries = 0;
char maxTries = 10;
double density = 0.13;
double totalSize = LEVEL_WIDTH*LEVEL_HEIGHT;
double currentSize = M_PI*UNSCALED_PLANET_RADIUS*UNSCALED_PLANET_RADIUS*2;
double spacing = 23;
while (currentSize/totalSize < density && tries < maxTries)
{
//Create a new planet at a completely random location with a random size
//For now, make half normal and half volcanic
float psize = (double(rand())/double(RAND_MAX))*0.7 + 0.5;
Planet p(planet0img, psize,
Vec2f(rand()%(LEVEL_WIDTH-int(2*UNSCALED_PLANET_RADIUS*psize)),
rand()%(LEVEL_HEIGHT-int(2*UNSCALED_PLANET_RADIUS*psize))), 0);;
if (rand()%2 == 0)
{
p.setType(0);
p.setImage(planet0img);
}
else
{
p.setType(1);
p.setImage(planet1img);
}
//Make sure it doesn't collide with any other planets
bool skip = false;
for (planetIter pi = planets.begin(); pi != planets.end(); pi++)
{
Vec2f ppos = p.pos()+Vec2f(UNSCALED_PLANET_RADIUS*p.size(),UNSCALED_PLANET_RADIUS*p.size());
Vec2f pipos = pi->pos()+Vec2f(UNSCALED_PLANET_RADIUS*pi->size(),UNSCALED_PLANET_RADIUS*pi->size());
if ((pipos-ppos).length() <
p.size()*UNSCALED_PLANET_RADIUS +
pi->size()*UNSCALED_PLANET_RADIUS + spacing)
{
//There's a collision. Increment tries and try again
tries++;
skip = true;
break;
}
}
if (skip) continue;
//At this point, we know there's no collision. Reset tries
tries = 0;
//Add a few more random attributes
p.setOwner(0, indicator);
p.setShipRate(0, ship0rate);
p.setRotSpeed((fmod(rand(),M_PI)/5) - M_PI/10);
p.setDifficulty(p.size()*20 + rand()%15 - 9);
//Add this planet to the current size
currentSize += M_PI*(UNSCALED_PLANET_RADIUS*p.size())*(UNSCALED_PLANET_RADIUS*p.size());
//Add it to the list
planets.push_back(p);
}
//Set up fleet list
std::list<Fleet> fleets;
//Set up projectile list
std::list<Projectile> projectiles;
//Filler to act as NULL
planetIter planNull;
//The currently selected planet
planetIter selectPlanet = planNull;
//Set up AI
std::list<GalconAI> ai;
//For now, AI controls player 2
GalconAISettings aiSet;
aiSet.attackFraction = .8;
aiSet.surplusDefecitThreshold = .25;
aiSet.attackExtraNeutral = .2;
aiSet.attackExtraEnemy = .7;
aiSet.perPlanetAttackStrength = .5;
aiSet.delay = 200;
aiSet.maximumBuildingFraction = .8;
aiSet.minimumDefenseForBuilding = 10;
aiSet.distancePower = 1.15;
ai.push_back(GalconAI(2, aiSet));
ai.begin()->init(planets, shipstats);
ai.begin()->activate();
//The number of the locally playing player
char localPlayer = 1;
//The type of ship that will currently be sent
int shipSendType = 0;
//A line drawer for the main surface
LineDrawer linedraw(screen);
/*
-----
MAIN LOOP
-----
*/
int time = SDL_GetTicks();
uint8_t quit = 0;
while (quit == 0)
{
//Update time and dt
//Cap FPS
int dt = SDL_GetTicks() - time;
float minms = 1000.0/float(FPS_CAP);
if (dt < minms) SDL_Delay(minms-dt);
time = SDL_GetTicks();
//Update keystates
keystates = SDL_GetKeyState(NULL);
//Check for arrow keys/wasd
if (keystates[SDLK_UP] || keystates[SDLK_w])
{
cameray -= CAMERA_SPEED * (dt/1000.0);
if (cameray < 0) cameray = 0;
}
if (keystates[SDLK_RIGHT] || keystates[SDLK_d])
{
camerax += CAMERA_SPEED * (dt/1000.0);
if (camerax > LEVEL_WIDTH - SCREEN_WIDTH) camerax = LEVEL_WIDTH - SCREEN_WIDTH;
}
if (keystates[SDLK_DOWN] || keystates[SDLK_s])
{
cameray += CAMERA_SPEED * (dt/1000.0);
if (cameray > LEVEL_HEIGHT - SCREEN_HEIGHT) cameray = LEVEL_HEIGHT - SCREEN_HEIGHT;
}
if (keystates[SDLK_LEFT] || keystates[SDLK_a])
{
camerax -= CAMERA_SPEED * (dt/1000.0);
if (camerax < 0) camerax = 0;
}
//Update camera from camerax and cameray to struct
camera.x = camerax;
camera.y = cameray;
//Handle events
while (SDL_PollEvent(&event))
{
//Quit if requested
if (event.type == SDL_QUIT)
{
quit = 1;
}
//Check for escape key, QWERTY to construct buildings, or numbers to select
//ship type.
//BUILDING CONSTRUCTION AND TYPE SELECTION THIS WAY IS TEMPORARY
if (event.type == SDL_KEYDOWN)
{
switch (event.key.keysym.sym)
{
case SDLK_ESCAPE:
quit = 1;
break;
case SDLK_q:
if (selectPlanet != planNull)
{
if (selectPlanet->owner() != localPlayer ||
buildRules[selectPlanet->type()].size() < 1) break;
selectPlanet->build(*(buildRules[selectPlanet->type()].begin()),
buildRules);
}
break;
case SDLK_w:
if (selectPlanet != planNull)
{
if (selectPlanet->owner() != localPlayer ||
buildRules[selectPlanet->type()].size() < 2) break;
selectPlanet->build(*(++buildRules[selectPlanet->type()].begin()),
buildRules);
}
break;
case SDLK_e:
if (selectPlanet != planNull)
{
if (selectPlanet->owner() != localPlayer ||
buildRules[selectPlanet->type()].size() < 3) break;
std::list<Building*>::iterator i;
i = buildRules[selectPlanet->type()].begin();
i++; i++;
selectPlanet->build(*i, buildRules);
}
break;
case SDLK_1:
shipSendType = 0;
break;
case SDLK_2:
shipSendType = 1;
break;
case SDLK_3:
shipSendType = 2;
break;
case SDLK_4:
shipSendType = 3;
break;
case SDLK_5:
shipSendType = 4;
break;
default:
break;
}
}
//Check for mouse clicks
if (event.type == SDL_MOUSEBUTTONDOWN)
{
//Left click
if (event.button.button == SDL_BUTTON_LEFT)
{
//Used to select a planet
//Check if any are being clicked on
selectPlanet = planNull;
//Adjust mouse coordinates based on camera
Vec2f click(event.button.x + camera.x, event.button.y + camera.y);
for (planetIter i = planets.begin(); i != planets.end(); i++)
{
//See if distance from center is less than planet radius
Vec2f center(i->x() + (UNSCALED_PLANET_RADIUS * i->size()),
i->y() + (UNSCALED_PLANET_RADIUS * i->size()));
if ((click-center).length() < UNSCALED_PLANET_RADIUS * i->size())
{
//Ensure the planet belongs to this person
if ((*i).owner() == localPlayer)
{
selectPlanet = i;
break;
}
}
}
}
//Right click
if (event.button.button == SDL_BUTTON_RIGHT)
{
//Used to choose the destination for a fleet
//See if we have a selected planet
if (selectPlanet != planNull)
{
//Adjust mouse coordinates based on camera
Vec2f click(event.button.x + camera.x, event.button.y + camera.y);
//Check to see if any are being clicked on
for (planetIter i = planets.begin(); i != planets.end(); i++)
{
Vec2f center(i->x() + (UNSCALED_PLANET_RADIUS * i->size()),
i->y() + (UNSCALED_PLANET_RADIUS * i->size()));
//See if distance from center is less than planet radius
if ((click-center).length() < UNSCALED_PLANET_RADIUS * i->size())
{
//Split ships from the source planet
int transfer = (*selectPlanet).splitShips(0.5, shipSendType);
//Make sure we actually have a ship in the fleet
if (transfer > 0)
{
//Add the new fleet
fleets.push_back(Fleet(transfer, shipSendType, shipstats[shipSendType], &(*selectPlanet), &(*i)));
break;
}
}
}
}
}
}
}
//Draw a white background
SDL_Rect back = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT};
SDL_FillRect(screen, &back, 0xFFFFFF);
//Update and display fleets
for (fleetIter i = fleets.begin(); i != fleets.end(); i++)
{
(*i).update();
//Check for arrival at destination
//See if distance from center is less than planet radius
Vec2f tar((*i).dest()->x() + (UNSCALED_PLANET_RADIUS*(*i).dest()->size()),
(*i).dest()->y() + (UNSCALED_PLANET_RADIUS*(*i).dest()->size()));
if ((tar-i->pos()).length() < UNSCALED_PLANET_RADIUS * (i->dest())->size())
{
//Check if friendly or hostile
if ((*i).dest()->owner() == (*i).owner())
{
//Add the fleet to the new planet
(*((*i).dest())).addShips(i->ships(), i->type());
}
else //Hostile
{
//Attack!
//Get ship counts before the attack
std::vector<int> ships1 = i->dest()->shipcount();
int oldowner = i->dest()->owner();
//Actually do the attack
(*((*i).dest())).takeAttack(i->ships(), i->type(), i->owner(), shipstats, indicator);
//If the attack changed ownership of the selected planet,
//deselect it
if (oldowner != i->dest()->owner() && i->dest() == &(*selectPlanet)) selectPlanet = planNull;
//Get ship counts after the attack
std::vector<int> ships2 = i->dest()->shipcount();
//Notify the defending AI about the losses
for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
{
if (oldowner != j->player()) continue;
float newdefense = 0;
for (unsigned int k = 0; k < ships1.size(); k++)
{
int diff;
//If ownership has changed
if (oldowner != i->dest()->owner())
{
diff = ships1[k];
j->notifyPlanetLoss(i->dest());
}
else
{
diff = ships1[k] - ships2[k];
}
newdefense += diff * shipstats[k].defense;
}
j->notifyDefendLoss(newdefense);
}
//Notify the attacking AI about the losses
for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
{
if (i->owner() != j->player()) continue;
float lost;
//If the attack failed
if (i->dest()->owner() != i->owner())
{
//Lost everything
lost = i->ships();
}
else //Successful attack
{
//Lose the difference
lost = i->ships() - i->dest()->totalDefense(shipstats);
j->notifyPlanetGain(i->dest());
}
j->notifyAttackLoss(lost);
}
}
//Delete all projectiles with this fleet as its target
for (projectileIter pi = projectiles.begin(); pi != projectiles.end(); pi++)
{
if (pi->target() == &(*(i)))
{
pi = projectiles.erase(pi);
pi--;
}
}
//Delete the fleet
i = fleets.erase(i);
i--;
continue;
}
//Check for interception
//Compare against every other fleet
for (fleetIter j = fleets.begin(); j != fleets.end(); j++)
{
//Atempt interception
char status = i->intercept(&(*j), shipstats);
//Greater than 0: Draw line
if (status <= 0) continue;
SDL_Color red = {255, 0, 0};
SDL_Color orange = {255, 255, 0};
linedraw.line(i->pos(), j->pos(), orange, red);
//Equal to 2: Dealt damage, but didn't notify
if (status == 2)
{
//Notify the AI before we go around deleting things
for (std::list<GalconAI>::iterator k = ai.begin(); k != ai.end(); k++)
{
if (k->player() == j->owner())
{
k->notifyFleetDamage(std::min(double(shipstats[i->type()].interceptDamage),
double(j->totalDefense(shipstats))));
}
}
}
//Equal to 3: Destroy target
if (status != 3) break;
//We can have the projectile code handle the cleanup later
//Create a fake projectile right on top of it to deal the final blow
std::stringstream convertnum;
convertnum << "damage ";
convertnum << shipstats[i->type()].interceptDamage*i->ships()*2;
projectiles.push_back(Projectile(j->pos(), &(*j),
convertnum.str(),
shipstats[j->type()].speed*2));
//Don't attack more than one ship
break;
}
(*i).display(screen, camera);
}
//Update and display planets
for (planetIter i = planets.begin(); i != planets.end(); i++)
{
//Get ship counts before the update
std::vector<int> ships1 = i->shipcount();
//Update the planet
(*i).update();
//Get ship counts after the update
std::vector<int> ships2 = i->shipcount();
//Notify a controlling AI about the construction
for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
{
if (i->owner() != j->player()) continue;
float newattack = 0;
float newdefense = 0;
for (unsigned int k = 0; k < ships1.size(); k++)
{
int diff = ships2[k] - ships1[k];
newattack += diff * shipstats[k].attack;
newdefense += diff * shipstats[k].defense;
}
j->notifyConstruction(newattack, newdefense);
}
//If this planet is selected, add an indicator
if (i == selectPlanet)
{
SDL_Rect temprect = {Sint16((*i).x()-10 - camera.x), Sint16((*i).y()-10 - camera.y), Uint16(UNSCALED_PLANET_RADIUS * (*i).size() * 2 + 20), Uint16(UNSCALED_PLANET_RADIUS * (*i).size() * 2 + 20)};
SDL_FillRect(screen, &temprect, SDL_MapRGB(screen->format, 100, 100, 100));
}
//If this is a lava planet and it is depleted, replace the image
if (i->typeInfo() < 0 && i->type() == 1)
{
i->setImage(planet1_1img);
i->setTypeInfo(0);
i->setRotSpeed(0);
i->setShipRate(0, ship0rate * PLANET1_DEPLETION_PENALTY);
}
//Iterate over all buildings to handle effects from buildings to other objects
for (unsigned int j = 0; j < i->buildcount(); j++)
{
//Get the building
BuildingInstance* b = i->building(j);
//Skip over nonexistant and incomplete buildings
if (!(b->exists()) || j == Uint32(i->buildIndex())) continue;
//Try to make it fire, remember result
bool fire = b->fire();
//Create a string stream and vector for tokens
std::stringstream ss(b->effect());
std::string item;
std::vector<std::string> tokens;
while (std::getline(ss, item, ' '))
{
tokens.push_back(item);
}
//Ensure the size is at least two
if (tokens.size() < 3) continue;
//Parse it and apply effects that involve multiple objects
//Fire projectile: fire <effect> <effectvars> <speed as multiplier>
if (tokens[0] == "fire")
{
//Ensure size of four
if (tokens.size() != 4) continue;
//Loop over all potential target fleets, find closest
Fleet* closest = NULL;
float closestDist = -1;
Vec2f coords = i->buildcoords(j);
for (fleetIter k = fleets.begin(); k != fleets.end(); k++)
{
//Only check further if it's an enemy fleet
if (k->owner() == i->owner()) continue;
//Compute the distance between them
double dist = (coords-k->pos()).length();
//Continue if the fleet is out of range
if (dist > b->range()) continue;
//Compare with previous best
if (dist < closestDist || closestDist < -0.5)
{
closestDist = dist;
closest = &(*k);
}
}
//Fire a projectile from the building to the fleet
if (closest != NULL)
{
if (fire)
{
//Create a proper string for the projectile
std::string projstr;
for (unsigned int word = 1; word < tokens.size()-1; word++)
{ projstr += tokens[word] + " "; }
projectiles.push_back(Projectile(coords, closest, projstr, std::atof(tokens[tokens.size()-1].c_str())));
}
}
}
//Aura: aura <effect> <effectvars>
if (tokens[0] == "aura")
{
//Find number of ships in range
int shipcount = 0;
for (fleetIter k = fleets.begin(); k != fleets.end(); k++)
{
//Only check further if it's an enemy fleet
if (k->owner() == i->owner()) continue;
//Compute the distance between them
double dist = (i->buildcoords(j)-k->pos()).length();
if (dist <= b->range()) shipcount += k->ships();
}
//Deal damage with a fake projectile
if (fire)
{
bool hit = false;
for (fleetIter k = fleets.begin(); k != fleets.end(); k++)
{
//Only check further if it's an enemy fleet
if (k->owner() == i->owner()) continue;
//Compute the distance between them
double dist = (i->buildcoords(j)-k->pos()).length();
if (dist > b->range()) continue;
hit = true;
std::string projstr;
//Divide appropriately if needed
if (tokens[tokens.size()-1] == "total")
{
std::stringstream toa;
toa << atof(tokens[tokens.size()-2].c_str())*float(k->ships())/float(shipcount);
tokens[tokens.size()-1] = toa.str();
}
//Depleted volcanic planets don't do as much
if (i->type() == 1 && i->typeInfo() <= 0)
{
std::stringstream toa;
toa << atof(tokens[tokens.size()-2].c_str())*PLANET1_DEPLETION_PENALTY;
tokens[tokens.size()-1] = toa.str();
}
//Create the projectile
for (unsigned int word = 1; word < tokens.size()-1; word++)
{
projstr += tokens[word] + " ";
}
projectiles.push_back(Projectile(k->pos(), &(*k), projstr, 1));
}
//Volcanic planets will lost some fuel
if (i->type() == 1 && hit && i->typeInfo() != 0)
{
i->setTypeInfo(i->typeInfo()-PLANET1_DEPLETION_RATE);
if (i->typeInfo() == 0) i->setTypeInfo(-1);
}
}
}
} //for each building
(*i).display(screen, planetFont, camera);
}
//Update and display projectiles
for (projectileIter i = projectiles.begin(); i != projectiles.end(); i++)
{
(*i).update();
//Check if the projectile has hit its target fleet
if ((i->pos() - i->target()->pos()).length() < 12.345) //MAGIC NUMBER >:(
{
//Tokenize string to determine effect
std::stringstream ss(i->effect());
std::string item;
std::vector<std::string> tokens;
while (std::getline(ss, item, ' '))
{
tokens.push_back(item);
}
//Damage: damage <amount>
if (tokens[0] == "damage")
{
//Ensure size of two
if (tokens.size() != 2) continue;
//Deliver the damage
//Notify the AI before we go around deleting things
for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
{
if (j->player() == i->target()->owner())
{
j->notifyFleetDamage(std::min(std::atof(tokens[1].c_str()), double(i->target()->totalDefense(shipstats))));
}
}
//Check to see if the fleet is destroyed by this
if (!(i->target()->takeHit(std::atof(tokens[1].c_str()), shipstats)))
{
//Delete the fleet
for (fleetIter fi = fleets.begin(); fi != fleets.end(); fi++)
{
if (&(*fi) == &(*(i->target())))
{
fleets.erase(fi);
break;
}
}
//Delete all projectiles with this fleet as the target
for (projectileIter pi = projectiles.begin(); pi != projectiles.end(); pi++)
{
if (pi->target() == i->target())
{
if (pi == i) continue;
pi = projectiles.erase(pi);
pi--;
}
}
}
//Either way, destroy this projectile
i = projectiles.erase(i);
i--;
continue;
}
}
(*i).display(screen, camera);
}
//Perform AI calculations
for (std::list<GalconAI>::iterator i = ai.begin(); i != ai.end(); i++)
{
//Get the command list
commandList com = i->update(planets, fleets, shipstats, buildRules);
//Execute each command
for (commandList::iterator j = com.begin(); j != com.end(); j++)
{
//Extract the info from the command
Planet* source = j->first;
int amount = j->second.first;
Planet* dest = j->second.second;
//Handle building construction
if (source == dest)
{
std::list<Building*>::iterator build = buildRules[source->type()].begin();
while (amount > 0)
{
amount--;
build++;
}
//Build it!
source->build((*build), buildRules);
continue;
}
//Get the number of ships from the source
std::vector<int> ships = source->shipcount();
//Send out a fleet for each ship type used
std::vector<int> newfleet;
newfleet.resize(ships.size());
int total = 0;
for (unsigned int k = 0; k < ships.size(); k++)
{
//Handle it differently for attack or defense
float typeTotal;
if (dest->owner() == source->owner())
{
//Check the total defense of this ship type
typeTotal = ships[k] * shipstats[k].defense;
}
else
{
//Check the total attack of this ship type
typeTotal = ships[k] * shipstats[k].attack;
}
//If there's more ships requested than there are of this type
if (total + typeTotal <= amount)
{
//Add them all
newfleet[k] += ships[k];
total += typeTotal;
}
else //More ships than space in the requested fleet
{
//Find the proper amount
//# of ships to send = defense requested / def per ship
float properAmount = (amount - total) / (typeTotal / ships[k]);
newfleet[k] += properAmount;
break;
}
}
//Fleet is built, send each type that has some ships
for (unsigned int k = 0; k < newfleet.size(); k++)
{
if (newfleet[k] == 0) continue;
fleets.push_back(Fleet(newfleet[k], k, shipstats[k], source, dest));
//Also subtract the fleet from the original planet
newfleet[k] *= -1;
source->addShips(newfleet[k], k);
}
}
}
//Flipoo
if (SDL_Flip(screen) == -1)
{
return 1;
}
}
//Free surfaces
SDL_FreeSurface(indicator[1]);
SDL_FreeSurface(indicator[2]);
SDL_FreeSurface(planet0img);
SDL_FreeSurface(planet1img);
SDL_FreeSurface(planet1_1img);
//Clean up TTF
TTF_CloseFont(planetFont);
TTF_Quit();