-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1733 lines (1376 loc) · 48.7 KB
/
main.cpp
File metadata and controls
1733 lines (1376 loc) · 48.7 KB
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
// Local includes.
#include "Actor.h"
#include "Player.h"
#include "Orbitals.h"
#include "Particle.h"
#include "MenuOrbital.h"
#include "Challenge.h"
#include "Vector.h"
#include "functional_plus.h"
#include "Random.h"
#include "Collision.h"
#include "Font.h"
#include "Config.h"
#include "Parsing.h" // For high score highScoreTable generation.
#include "Draw.h"
#include "Sound.h"
#include "Keyboard.h"
#include "Timer.h"
#include "System.h"
// 3rd party includes.
#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>
// std::includes.
#include <algorithm> // For for_each.
#include <functional> // For mem_fun_ref in main.
#include <cstdio> // For file renaming in update_high_score.
#include <iomanip> // For setw in arcade_mode.
#include <sstream> // For int -> string conversions.
int spawnDelay;
int spawnWait;
Timer gameTimer;
// How many particles to create proportionate to CircleActor::mass.
int particleRatio = 200;
// Used for high score consistency. Increment when a change may effect scoring
// in any way--pretty much any game rule change at all.
const int VERSION = 11;
// SDL uses milliseconds so i will too.
const int SECOND = 1000;
int timePlayerDied = -1000;
bool showFrameTime = false;
std::ofstream loggit( "log" );
#define PANDE( cmd ) log << #cmd" ==> " << (cmd) << '\n'
bool motionBlur = false;
typedef std::tr1::shared_ptr< CircleActor > SharedCActorPtr;
typedef std::tr1::weak_ptr< CircleActor > WeakCActorPtr;
typedef std::tr1::weak_ptr< Actor > ActorPtr;
typedef std::vector< SharedCActorPtr > CActors;
typedef std::vector< ActorPtr > Actors;
typedef std::vector< Particle > Particles;
CActors cActors;
Particles particles;
bool simpleParts;
bool showExtraText = true;
// Used everywhere to write text on the screen.
std::tr1::shared_ptr<TrueTypeFont> font;
// True if the player has moved since the game started.
bool playerHasMoved = false;
// True if the player has pressed spacebar.
bool playerIncreasedGravity = false;
const Config defaultConfig; // Used when unsure about any config option.
Config fileConfig( LOCAL_FILE("config.txt") ), config = fileConfig;
int packageLevel = 0;
const int SCREEN_WIDTH = 900;
const int SCREEN_HEIGHT = 700;
typedef std::map< float, std::string > HighScoreTable;
unsigned int nHighScores;
const size_t HANDLE_SIZE = 4;
bool newHighScore = false;
std::string highScoreHandle( HANDLE_SIZE, 'x' );
HighScoreTable highScoreTable;
struct Mode
{
static void null_update(int) { }
static void null_event() { }
typedef std::tr1::shared_ptr< TextLine > LinePtr;
typedef std::vector< LinePtr > LineList;
LineList lines;
std::string name;
typedef void(*UpdateFunc)(int);
typedef void(*EventFunc)();
EventFunc init;
UpdateFunc update;
UpdateFunc onDeath;
UpdateFunc score;
UpdateFunc spawn;
bool chaos;
Mode( const std::string& name )
: name( name )
{
chaos = false;
init = null_event;
update = null_update;
onDeath = null_update;
score = null_update;
spawn = null_update;
}
};
struct PackageMode : public Mode
{
std::string tip;
std::tr1::weak_ptr<Package> weakPackage;
bool started; // Has the round started?
bool scoreSaved; // (At end:) Was the score saved?
bool playerWon;
int time;
PackageMode()
: Mode( "Package" )
{
started = scoreSaved = false;
tip = "";
}
};
Mode* mode = 0;
// FUNCTIONS //
void arcade_init();
void menu_init();
void package_init();
void training_init();
void arcade_mode( int dt );
void training_mode( int dt );
void menu( int dt );
void package_delivery( int dt );
void chaos_mode( int dt );
void on_death( int dt );
void score( int dt );
void arcade_spawn( int dt );
void chaos_spawn( int dt );
void training_spawn( int dt );
Mode arcadeMode( "Arcade" );
Mode trainingMode( "Training" );
Mode menuMode( "Menu" );
Mode chaosMode( "Chaos" );
PackageMode packageMode;
void initialize_modes()
{
arcadeMode.init = arcade_init;
arcadeMode.update = arcade_mode;
arcadeMode.onDeath = on_death;
arcadeMode.score = score;
arcadeMode.spawn = arcade_spawn;
chaosMode.init = arcade_init;
chaosMode.update = chaos_mode;
chaosMode.onDeath = on_death;
chaosMode.score = score;
chaosMode.spawn = chaos_spawn;
chaosMode.chaos = true;
trainingMode.init = training_init;
trainingMode.update = training_mode;
trainingMode.spawn = training_spawn;
menuMode.init = menu_init;
menuMode.update = menu;
packageMode.init = package_init;
packageMode.update = package_delivery;
}
std::string to_string( int x )
{
std::stringstream ss;
ss << x;
return ss.str();
}
float to_float( std::string str )
{
std::stringstream ss;
ss << str;
float x;
ss >> x;
return x;
}
void configure( const Config& cfg )
{
cfg.get( "particle-ratio", &particleRatio );
cfg.get( "prediction-length", &Orbital::predictionLength );
cfg.get( "prediction-precision", &Orbital::predictionPrecision );
cfg.get( "gravity-line", &Orbital::gravityLine );
cfg.get( "velocity-arrow", &Orbital::velocityArrow );
cfg.get( "acceleration-arrow", &Orbital::accelerationArrow );
cfg.get( "motion-blur", &motionBlur );
cfg.get( "nHighScores", &nHighScores );
cfg.get( "fps", &showFrameTime );
cfg.get( "particle-size", &Particle::sizeMult );
float opacityTmp;
cfg.get( "particle-opacity", &opacityTmp );
Particle::opacity = opacityTmp / 100.f;
int volume;
cfg.get( "music-volume", &volume );
if( volume > 128 )
volume = 128;
else if( volume < 0 )
volume = 0;
Mix_VolumeMusic( volume );
cfg.get( "sfx-volume", &volume );
if( volume > 128 )
volume = 128;
else if( volume < 0 )
volume = 0;
Mix_Volume( -1, volume );
std::string particleBehaviour;
cfg.get( "particle-behaviour", &particleBehaviour );
if( particleBehaviour == "gravity-field" ) {
Particle::gravityField = true;
simpleParts = false;
} else if( particleBehaviour == "simple" ) {
Particle::gravityField = false;
simpleParts = true;
} else {
Particle::gravityField = false;
simpleParts = false;
}
}
GLenum init_gl( int w, int h )
{
glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0, w, h, 0, -10, 10 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glEnable( GL_BLEND );
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
return glGetError();
}
#ifdef __WIN32
// Borrowed and modified from http://www.devmaster.net/forums/showthread.php?t=443
void set_vsync( int interval = 1 )
{
typedef BOOL (APIENTRY *PFNWGLSWAPINTERVALFARPROC)( int );
PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT = 0;
const char *extensions = (const char*)glGetString( GL_EXTENSIONS );
if( strstr( extensions, "WGL_EXT_swap_control" ) == 0 ) {
return; // Error: WGL_EXT_swap_control extension not supported on your computer.\n");
} else {
wglSwapIntervalEXT = (PFNWGLSWAPINTERVALFARPROC)wglGetProcAddress( "wglSwapIntervalEXT" );
if( wglSwapIntervalEXT )
wglSwapIntervalEXT( interval );
}
}
#endif
bool resize_window( float w_, float h_ )
{
float w = w_, h = h_;
float ratio = (float)SCREEN_HEIGHT / SCREEN_WIDTH;
if( !SDL_SetVideoMode( w, h, 32, SDL_OPENGL|SDL_RESIZABLE ) )
return false;
if( w*ratio > h )
// h is the limiting factor.
w = h / ratio;
else
h = w * ratio;
float wOff = ( w_ - w ) / 2;
float hOff = ( h_ - h );
glViewport( wOff, hOff, w, h );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho( 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -10, 10 );
glMatrixMode(GL_MODELVIEW);
return true;
}
bool make_sdl_gl_window( int w, int h )
{
if( ! resize_window(w,h) )
return false;
init_gl( w, h );
Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 2048 );
font.reset( new TrueTypeFont );
#ifdef __WIN32
set_vsync( 0 );
#endif
return true;
}
void update_screen()
{
if( motionBlur ) {
float q = 0.97;
glAccum( GL_MULT, q );
glAccum( GL_ACCUM, 1-q );
glAccum( GL_RETURN, 1 );
}
SDL_GL_SwapBuffers();
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
}
void spawn_player( Actor::value_type x, Actor::value_type y )
{
SharedCActorPtr player( new Player( Actor::vector_type(x,y) ) );
cActors.push_back( player );
Orbital::target = std::tr1::static_pointer_cast<Player>( player );
Player::original = Orbital::target;
Orbital::attractors.push_back( Orbital::target );
}
template< typename T >
std::tr1::weak_ptr<T> spawn( Actor::value_type x, Actor::value_type y )
{
float speed = random( .15f, .40f );
float angle = random_angle();
float vx = std::cos(angle) * speed;
float vy = std::sin(angle) * speed;
std::tr1::shared_ptr<T> newActor (
new T( Actor::vector_type(x,y), Actor::vector_type(vx,vy) )
);
cActors.push_back( newActor );
return newActor;
}
template< typename T >
std::tr1::weak_ptr<T> spawn()
{
int x, y;
x = random (
int(Arena::minX + T::RADIUS*Arena::scale),
int(Arena::maxX - T::RADIUS*Arena::scale)
);
y = random (
int(Arena::minY + T::RADIUS*Arena::scale),
int(Arena::maxY - T::RADIUS*Arena::scale)
);
return spawn<T>( x, y );
}
#include <fstream>
void spawn_particle( const Actor::vector_type& pos, const Actor::vector_type& v,
float scale, const Color& c )
{
typedef Actor::vector_type V;
scale = random( 0.5f, scale );
Particle particle (
pos, v, 0, 1, scale, c
);
particles.push_back( particle );
}
float scoreVal = 0;
std::ofstream& operator << ( std::ofstream& of, HighScoreTable& highScoreTable )
{
typedef HighScoreTable::reverse_iterator Rit;
for( Rit it=highScoreTable.rbegin(); it!=highScoreTable.rend(); it++ )
of << it->second << " = " << it->first << '\n';
return of;
}
void update_high_score()
{
std::string tableFile =
LOCAL_FILE( mode->name + " Scores.txt" );
// Get the old scores first.
std::string oldVersion = "1";
{
std::ifstream scoresIn( tableFile.c_str() );
highScoreTable.clear();
if( scoresIn )
{
std::string line;
while( std::getline( scoresIn, line ) )
{
// Comments and whitespace shouldn't appear in this
// file, but they shouldn't break this code either.
rm_comments( &line );
rm_whitespace( &line );
if( line.size() == 0 )
continue;
Variable var = evaluate_expression( line );
if( var.handle == "version" ) {
oldVersion = var.value;
continue;
}
float key;
sstream_convert( var.value, &key );
highScoreTable[ key ] = var.handle;
}
}
}
// Don't clobber out-dated high scores, back them up.
int oldVersionInt;
sstream_convert( oldVersion, &oldVersionInt );
if( highScoreTable.size() && oldVersionInt != VERSION ) {
std::stringstream filename;
std::string base( tableFile.begin(), tableFile.end()-sizeof(".txt") );
filename << base << " (" << oldVersion << ").txt";
std::rename( tableFile.c_str(), filename.str().c_str() );
highScoreTable.clear();
}
// Add the new score to the highScoreTable.
for( size_t i=0; i < HANDLE_SIZE; i++ )
highScoreHandle[i] = std::rand()%('z'-'a') + 'a';
highScoreTable[ scoreVal ] = highScoreHandle;
newHighScore = true;
// The highScoreTable is sorted by score, so highScoreTable.begin() must be the
// lowest. But only remove if the highScoreTable's too large.
while( highScoreTable.size() > nHighScores ) {
if( highScoreTable.begin()->second == highScoreHandle )
newHighScore = false;
highScoreTable.erase( highScoreTable.begin() );
}
// Now construct the high scores for display.
Vector<int,2> pos( 250, 370 );
mode->lines.push_back( Mode::LinePtr (
new TextLine( font.get(), "Scores stored in '" + mode->name +
" Scores.txt'", pos )
)
);
pos.y( pos.y() + 30 );
// The table should include two columns, handles and scores, both
// determining their width by their longest member. A two pass
// algorithm is used. Pass one finds the size of the longest members,
// the second prints them.
// Pass one:
size_t largestHandleSize = 0;
size_t largestScoreSize = 0;
for( HighScoreTable::iterator it=highScoreTable.begin();
it != highScoreTable.end(); it++ )
{
if( it->second.size() > largestHandleSize )
largestHandleSize = it->second.size();
unsigned int nDigits = std::log10( it->first );
if( nDigits > largestScoreSize )
largestScoreSize = nDigits;
}
// Use this to format the text.
std::stringstream ss;
ss.precision( 3 );
ss.fill( '.' );
const int HANDLE_WIDTH = largestHandleSize + 2;
const int SCORE_WIDTH = largestScoreSize + 5;
// To draw text with a gradient, keep track of these:
float color = 1;
float dcolor = ( 0.01 - 1 ) / highScoreTable.size();
// Pass 2:
// Assume highScoreTable is newly initialized by update_high_score.
for( HighScoreTable::reverse_iterator it = highScoreTable.rbegin();
it!=highScoreTable.rend(); it++ )
{
ss.str( "" );
ss << std::setw(HANDLE_WIDTH) << std::left << it->second;
// internal is the only iostream object that seems to work here.
// The obvious fixed << right did not work.
ss << std::setw(SCORE_WIDTH) << std::fixed << std::internal <<
it->first;
// Let the player know his/hew awesome score.
if( it->second == highScoreHandle )
ss << " ** NEW HIGH SCORE";
pos.y( pos.y() + 15 );
mode->lines.push_back (
Mode::LinePtr (
new TextLine( font.get(), ss.str(), pos )
)
);
mode->lines.back()->color = Color( color, color, 0 );
color += dcolor;
if( it->second == highScoreHandle )
mode->lines.back()->color = Color( 1, 0, 0 );
}
// Update the file.
std::ofstream out( tableFile.c_str() );
out << "version = " << VERSION << '\n';
out << highScoreTable;
}
// This is called for each actor and returns true if it should be deleted.
// It may seem unclean, but it also handles all on-death events.
bool delete_me( SharedCActorPtr& actor )
{
static Sound explosions[] = {
Sound( LOCAL_FILE("art/sfx/Explode1.wav") ),
Sound( LOCAL_FILE("art/sfx/Explode2.wav") ),
Sound( LOCAL_FILE("art/sfx/Explode3.wav") ),
Sound( LOCAL_FILE("art/sfx/Explode4.wav") ),
};
static const int N_EXPLOSIONS = sizeof( explosions ) / sizeof( Sound );
if( actor->deleteMe )
{
particles.size();
// Explode.
for( int i=0; i < std::abs(actor->mass()*particleRatio); i++ )
spawn_particle( actor->s, actor->v/6.0f, actor->radius()/9,
actor->color() );
// Add to score if player is alive.
if( !Orbital::target.expired() )
scoreVal += actor->score_value();
// If the player's what just died...
if( actor.get() == Orbital::target.lock().get() )
{
timePlayerDied = gameTimer.time_ms();
update_high_score();
}
// Let it be heard.
explosions[ random(0, N_EXPLOSIONS) ].play();
}
return actor->deleteMe;
}
// Resets whatever mode the game is in.
// If no mode is given, it resets the current mode.
void reset( Mode* newMode = 0 )
{
if( mode )
mode->lines.clear();
if( newMode )
Mix_FadeOutMusic( 200 );
Arena::minX = Arena::minY = 3;
Arena::maxX = SCREEN_WIDTH-3;
Arena::maxY = SCREEN_HEIGHT-3;
Player::SharedPlayerPtr target = Orbital::target.lock();
newHighScore = false;
// If we're switching to a different mode...
if( newMode && newMode != mode ) {
mode = newMode;
// Erase package mode progress, if any.
packageLevel = 0;
// Before clearing the actors, make them explode.
for( size_t i=0; i < cActors.size(); i++ )
cActors[i]->deleteMe = true;
// But don't explode the player!
if( target )
target->deleteMe = false;
for_each( cActors.begin(), cActors.end(), delete_me );
} else {
// Normal resets clear the screen.
particles.clear();
}
// We need to clear cActors, but keep the player. We'll clear it
// completely, then respawn the player in the same place so the user
// doesn't notice..
Actor::vector_type playerPos( 350, 300 );
if( target )
playerPos = target->s;
cActors.clear();
spawn_player( playerPos.x(), playerPos.y() );
gameTimer.reset();
spawnDelay = 6000;
spawnWait = 30;
timePlayerDied = 0;
scoreVal = 0;
mode->init();
}
enum Spawns { ORBITAL, STOPPER, TWISTER, NEGATIVE, GREEDY, N_SPAWN_SLOTS=9 };
Spawns slotsTmp[] = {
STOPPER, ORBITAL,
ORBITAL, ORBITAL, ORBITAL, TWISTER,
TWISTER, ORBITAL, TWISTER
};
std::vector<Spawns> spawnSlots (
slotsTmp, slotsTmp + sizeof(slotsTmp)/sizeof(slotsTmp[0])
);
WeakCActorPtr delegate_spawn( int spawnCode )
{
WeakCActorPtr s;
switch( spawnCode )
{
case ORBITAL: s = spawn<Orbital>(); break;
case STOPPER: s = spawn<Stopper>(); break;
case TWISTER: s = spawn<Twister>(); break;
case NEGATIVE: s = spawn<Negative>(); break;
case GREEDY : s = spawn<Greedy>(); break;
default: break; // Should never be reached.
}
return s;
}
WeakCActorPtr standard_spawn( const std::vector<Spawns>& slots, int maxTime )
{
unsigned int rank = (float)slots.size() / maxTime * gameTimer.time_ms();
if( rank > slots.size() )
rank = slots.size();
int newSpawn = slots[ random(0, rank) ];
return delegate_spawn( newSpawn );
}
void play_song( Music& song )
{
if( ! song.playing() && !Orbital::target.expired() )
{
song.fade_in( 1 * SECOND );
}
if( song.playing() && Orbital::target.expired() )
Mix_FadeOutMusic( 2500 );
}
void chaos_spawn( int dt )
{
static Spawns slotsTmp[] = {
ORBITAL, TWISTER,
NEGATIVE, ORBITAL, STOPPER, GREEDY,
NEGATIVE, TWISTER, ORBITAL, TWISTER
};
static std::vector<Spawns> chaosSlots (
slotsTmp, slotsTmp + sizeof(slotsTmp)/sizeof(slotsTmp[0])
);
// Time to spawn a new enemy?
spawnWait -= dt;
if( spawnWait < 0 )
{
// This is calibrated to be 3 seconds when gameTime=50 seconds.
// PROOF:
// D = delay, T = gameTime
// If D = 5000 - a sqrt(T) and D(50,000) = 2000:
// 3000 = 5000 - a sqrt(50000)
// 2000 = a sqrt(5*100*100)
// 2000 = 100 * a * sqrt(5)
// a = 20 / sqrt(5)
spawnDelay =
5*SECOND - std::sqrt(gameTimer.time_ms()) * (20.f/std::sqrt(5));
if( spawnDelay < 1 * SECOND )
spawnDelay = 1 * SECOND;
spawnWait = spawnDelay;
SharedCActorPtr spawn = standard_spawn( chaosSlots, 40*SECOND).lock();
Orbital::attractors.push_back( spawn );
spawn->isAttractor = true;
}
}
void chaos_mode( int )
{
static Music menuSong( LOCAL_FILE("art/music/Stuck Zipper.ogg") );
static int lastScore = 0;
play_song( menuSong );
if( (int)scoreVal != lastScore )
{
mode->lines[0].reset (
new TextLine( font.get(), "Score: " + to_string((int)scoreVal),
vector(100,100) )
);
lastScore = scoreVal;
}
mode->lines[0]->color = Color( 0.8, 0.8, 0 );
}
void score( int dt )
{
float sum = 0;
unsigned int nEnemies = 0;
unsigned int nActive = 0;
for( size_t i=1; i < cActors.size(); i++ )
{
if( cActors[i]->isActive )
{
nActive++;
if( cActors[i]->isMovable )
{
sum += cActors[i]->score_value();
nEnemies++;
}
}
}
scoreVal += sum / 4.0 * nEnemies*nEnemies * (float(dt)/SECOND);
}
void arcade_spawn( int )
{
int nMoving = 0;
for( size_t i=1; i < cActors.size(); i++ )
nMoving += cActors[i]->isActive && cActors[i]->isMovable;
// If cActors has only active enemies + the player
// and there's one or zero enemies...
if( nMoving <= 1 && cActors.back()->isActive )
{
enum SpawnPoints {
ORBITAL_POINTS = 2,
STOPPER_POINTS = 1,
TWISTER_POINTS = 3
};
// An arbitrary equation. Not very tested.
int points = std::sqrt(scoreVal) / 5.f + 3.f;
int orbitalChance = 1.3f * scoreVal + 1;
int stopperChance = 1.0f * scoreVal + 3;
int twisterChance = 2.0f * scoreVal - 250*2;
if( twisterChance < 0 )
twisterChance = 0;
int sum = orbitalChance + stopperChance + twisterChance;
while( points > 0 )
{
int pick = random( 0, sum );
Spawns code = N_SPAWN_SLOTS;
if( pick <= orbitalChance ) {
code = ORBITAL;
points -= ORBITAL_POINTS;
} else if( pick <= stopperChance+orbitalChance ) {
code = STOPPER;
points -= STOPPER_POINTS;
} else {
code = TWISTER;
points -= TWISTER_POINTS;
}
delegate_spawn( code );
}
}
}
void arcade_init()
{
Mode::LinePtr line (
new TextLine( font.get(), "Score: 0",
vector(100,100) )
);
mode->lines.push_back( line );
}
void arcade_mode( int )
{
static Music menuSong( LOCAL_FILE("art/music/Stuck Zipper.ogg") );
static int lastScore = 0;
play_song( menuSong );
if( (int)scoreVal != lastScore )
{
mode->lines[0].reset (
new TextLine( font.get(), "Score: " + to_string((int)scoreVal),
vector(100,100) )
);
lastScore = scoreVal;
mode->lines[0]->color = Color( 0.8, 0.8, 0 );
}
}
void on_death_lower_color( Mode::LinePtr& ptr )
{
ptr->color[3] -= 0.001;
}
void on_death( int )
{
if( gameTimer.time_ms() < timePlayerDied + 30*SECOND )
{
glColor3f( 1, 1, 1 );
font->draw( "Press r to reset, m for menu", 600, 200 );
}
else
{
for_each (
mode->lines.begin(), mode->lines.end(),
on_death_lower_color
);
}
}
void training_init()
{
if( showExtraText )
{
LinePrinter intro( font.get(), vector(50,50) );
intro.add_line( "This is how-to-play mode." );
intro.add_line( "Move around with WASD (like in an FPS) or the arrow keys." );
intro.add_line( "Spawn enemies to practice dealing with them." );
intro.add_line( " Don't worry, you're invincible here.." );
intro.add_line( " " );
intro.add_line( "Press ENTER to switch between chaos/arcade physics. (Some enemies only available in chaos mode.)" );
intro.add_line( " " );
intro.add_line( "To return to the menu, press M." );
LinePrinter spawnList( font.get(), vector(650,50) );
spawnList.add_line( "Press Z to spawn an Orbital." );
spawnList.lines.back()->color = Color( 0.4f, 0.4f, 1.0f );
spawnList.add_line( "Press X to spawn a Stopper." );
spawnList.lines.back()->color = Color( 0.7f, 0.7f, 0.7f );
spawnList.add_line( "Press C to spawn a Twister." );
spawnList.lines.back()->color = Color( 1.0f, 0.1f, 0.1f );
spawnList.add_line( "Press V to spawn a Negative. (chaos mode)" );
spawnList.lines.back()->color = Color( 0.3f, 1.0f, 1.0f );
spawnList.add_line( "Press B to spawn a Greedy. (chaos mode)" );
spawnList.lines.back()->color = Color( 1.0f, 0.0f, 1.0f );
mode->lines.insert( mode->lines.end(), intro.lines.begin(), intro.lines.end() );
mode->lines.insert( mode->lines.end(), spawnList.lines.begin(), spawnList.lines.end() );
}
}
void set_delete_me( CActors::value_type& a )
{
a->deleteMe = true;
}
void training_mode( int )
{
// This is a sandbox mode where the player can't die and s/he can manually
// spawn any enemy in the game.
// These colors correlate, somewhat, to the colors of the enemies.
static Color colors[ N_SPAWN_SLOTS ];
colors[ ORBITAL ] = Color( 0.4f, 0.4f, 1.0f );
colors[ STOPPER ] = Color( 0.7f, 0.7f, 0.7f );
colors[ TWISTER ] = Color( 1.0f, 0.1f, 0.1f );
colors[ NEGATIVE ] = Color( 0.3f, 1.0f, 1.0f );
colors[ GREEDY ] = Color( 1.0f, 0.0f, 1.0f );
// Swap the mode when enter is pressed.
if( Keyboard::key_state('\r') ) {
mode->chaos = ! mode->chaos;
int offset = !Orbital::target.expired();
for_each( cActors.begin()+offset, cActors.end(), set_delete_me );
}
Orbital::target.lock()->invinsible = true;
}
void training_spawn( int )
{
// Tips will appear on the bottom of the screen after an enemy is spawned.
static const char* tips[ N_SPAWN_SLOTS ];
tips[ ORBITAL ] = "Orbitals are the most common spawns, and most enemies share at lease something in common with them.";
tips[ TWISTER ] = "While an orbital's motion is circular, the twister's motion is elliptical, like the earth around the sun.";
tips[ NEGATIVE ] = "A negative is attracted to you, like an orbital, but repels all other enemies. It's mass is negative.";
tips[ GREEDY ] = "A greedy will only orbit the player, ignoring everything else.";
tips[ STOPPER ] = "Stoppers are slow, big, though light orbitals. When hit, one will stop; if it again, it will move again."
"\nThe only way to kill a stopper is to run into it while it's stopped.";
// A newly spawned enemy.
std::tr1::weak_ptr<CircleActor> p;
int spawnCode = -1;
static int recentSpawn = -1;
if( Keyboard::key_state('z') )
spawnCode = ORBITAL;
else if( Keyboard::key_state('x') )
spawnCode = STOPPER;
else if( Keyboard::key_state('c') )
spawnCode = TWISTER;