-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.c
executable file
·1450 lines (1272 loc) · 35.7 KB
/
main.c
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
/* This code is released under the GNU GPL v2 license. */
//SDLpong main file
//compile (on linux) with:
//gcc main.c Sound.c -o pong -lSDL -lSDL_gfx -lSDL_ttf -lSDL_image -lSDL_mixer -I/usr/include/SDL
/* SDLpong written by Brandon Foltz as practice for coding in C.
This code may not be as nice/clean as it could be, but it's a
learning experience, so bear with my n00bishness. It could
also (probably) be written in considerably less code, but I
wrote it this way in an attempt to keep everything organized
and easily understandable. Comments abound. */
/*
TODO: Ball serving for players
TODO: Multiple source files?
TODO: Graphics settings?
TODO: Clean up code!
*/
//standard includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//file handling and sys stuff
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
//game specific includes
#include "main.h"
//sound
#include "Sound.h"
//definitions
//engine
//#define WINDOW_WIDTH 640
//#define WINDOW_HEIGHT 480
#define DEFAULT_WIN_WIDTH 640
#define DEFAULT_WIN_HEIGHT 480
#define BPP 32
#define WINDOW_TITLE "SpacePong"
#define MAX_FPS 32 //set this to some high number to pseudo-uncap fps (even numbers plz)
#define DATADIR "data"
#define FALSE 0
#define TRUE !FALSE
//--help text
#define HELP_TEXT " Usage: pong [options] \n" \
" -w [window width in pixels] default: 640 \n" \
" -h [window height in pixels] default: 480\n" \
" -f starts game in fullscreen mode"
//menu
#define MENU_TEXT "Spacebar to play. Esc to quit. Tab for 2 players."
#define MENU_TEXT2 "Up/Down keys for Player 1, A/Z for Player 2."
#define MENU_TEXT3 "Written by: Brandon Foltz."
//game
//these are all old defaults for 640x480
//#define PADDLE_SPEED 8
//#define PADDLE_LENGTH 64
//#define PADDLE_WIDTH 12
//#define BALL_MAX_SPEED 10 //this should be less than paddle width to avoid glitching
//#define BALL_SIZE 6
#define BALL_DELAY 3 //after score, ball delays movement for this many seconds
#define MAX_SCORE 10 //game ends at this score
//some values to tweak AI difficulty with
//#define AI_REACT_DIST 320 //WINDOW_WIDTH / 2 //bot wont react until ball reaches middle of screen
//#define AI_TOLERANCE 20 //lower num = greater difficulty. more than half PADDLE_LENGTH = bot fail, hard.
//effects values
#define BALL_HIT_SPARKS 12
#define BALL_TRAIL_LIFE 16
#define BACKGROUND_SPEED 1.5 //experiment with floating values
#define PADDLE_FADETIME 16 //in frames. lower = faster
#ifdef _WIN32
int WinMain(int argc, char *argv[])
{
main(argc, argv);
}
#endif
int main(int argc, char *argv[])
{
InitArgs(argc, argv);
if(!InitSDL(GameState)) //set up SDL stuffz
{
puts("SDL Init failed!");
return 0; //no need to GameQuit() because nothing is initialized
}
InitScales();
InitSamples();
InitMisc();
SetGameState(STATE_MENU);
InitMenu();
UpdateProgressBar(1,100); //finished loading, game starts!
//start the game loop
Frames.maxframetime = (1000 / MAX_FPS);
if(GameState.debug)
printf("Frames.maxframetime: %d\n", Frames.maxframetime);
Frames.framestart = SDL_GetTicks();
Frames.update = SDL_GetTicks();
Frames.framems = 1;
while(GameState.state != STATE_QUITTING)
{
Frames.framestart = SDL_GetTicks();
CalcFPS(); //not part of "game" code. consider it engine code.
GameLoop(); //compartmentalize main game code
Frames.frametime += (SDL_GetTicks() - Frames.framestart);
Frames.framems = (SDL_GetTicks() - Frames.framestart);
RegulateFPS(); //if this starts bugging out, just stick SDL_Delay(30); in its place
Frames.framems = 0;
}
if(GameState.debug)
printf("GameState at end = %d\n",GameState.state);
puts("If the public doesn't like one's work... one has to accept the fact, gracefully.");
//lets me know the end of the program is reached
return 0;
}
//#####################################
//General Purpose/Engine Functions
//#####################################
int InitArgs(int argc, char *argv[])
{
//might want some extra error checking in here
//initializing default gamestate params
GameState.resx = DEFAULT_WIN_WIDTH;
GameState.resy = DEFAULT_WIN_HEIGHT;
GameState.fullscreen = 0;
int i = 0;
for(i=0;i<argc;i++)
{
if(0 == strcmp(argv[i], "-w"))
GameState.resx = atoi(argv[i+1]);
else if(0 == strcmp(argv[i], "-h"))
GameState.resy = atoi(argv[i+1]);
else if(0 == strcmp(argv[i], "-f"))
GameState.fullscreen = 1;
else if(0 == strcmp(argv[i], "--help"))
{
puts(HELP_TEXT);
GameQuit();
}
}
return 1; //unless fail
}
int InitSDL(s_state GameState)
{
//this func returns 0 on failure, 1 on success
if (SDL_Init(SDL_INIT_VIDEO) < 0 ) //initialize SDL video
{
puts("SDL Video Init failed!");
return 0;
}
if(TTF_Init() < 0) //initialize SDL text
{
puts("SDL TTF_Init failed!");
return 0;
}
if(!(font = TTF_OpenFont(DATADIR"/arial.ttf", 14))) //load font
{
puts("Unable to load font! (arial.ttf)");
return 0;
}
//set up SDL window
if(!(GameState.fullscreen))
{
if (!(screen = SDL_SetVideoMode(GameState.resx, GameState.resy, BPP, SDL_HWSURFACE)))
//SDL_FULLSCREEN)))//SDL_SWSURFACE || SDL_FULLSCREEN)))char imgname[64];
{
puts("SDL Init Failed.");
SDL_Quit();
return 0;
}
}
else if(GameState.fullscreen)
{
if (!(screen = SDL_SetVideoMode(GameState.resx, GameState.resy, BPP, SDL_FULLSCREEN | SDL_HWSURFACE)))
{
puts("SDL Init Failed.");
SDL_Quit();
return 0;
}
}
SDL_WM_SetCaption(WINDOW_TITLE, WINDOW_TITLE); //set window caption
if(GameState.debug)
puts("SDL Init Success!");
return 1; //success!
}
void InitMisc(void)
{
//render "loading..."
//SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));
DrawText("Loading...", (GameState.resx / 2) - 22, (GameState.resy / 2) - 32);
UpdateProgressBar(0,1);
GameState.debug = 0; //debug mode is only useful when run from terminal
GameState.state = 1; //initialize it to avoid quitting on start
SetGameState(STATE_INITIALIZING); //for consistency's sake
GameState.paused = 0;
GameState.winner = -1; //-1 means no games have been played, so no winner
srand((unsigned)time(NULL)); //seed the randomizer ONLY ONCE!
LoadBackgrounds();
UpdateProgressBar(0,1);
//init sprite states!
int i;
for(i=0;i<MAX_SPRITES;i++)
Sprite[i].enabled = 0;
Ball.r = 255; Ball.g = 255; Ball.b = 255; Ball.a = 255;
for(i=0;i<2;i++)
{
Paddle[i].r = 255;
Paddle[i].g = 255;
Paddle[i].b = 255;
Paddle[i].a = 255;
Paddle[i].defr = 255;
Paddle[i].defg = 255;
Paddle[i].defb = 255;
Paddle[i].defa = 255;
Paddle[i].ticks = 0;
Paddle[i].score = 0;
}
UpdateProgressBar(0,1);
}
void InitScales(void)
{
Paddle[0].width = GameState.resx / 50;
Paddle[0].height = GameState.resy / 7;
Paddle[0].speed = GameState.resy / 60;
Paddle[1].width = GameState.resx / 50;
Paddle[1].height = GameState.resy / 7;
Paddle[1].speed = GameState.resy / 60;
Ball.maxspeed = GameState.resx / 64;
Ball.size = GameState.resx / 80;
//init default AI values
AI.reactdist = GameState.resx / 2;
AI.tolerance = 20;
}
void InitSamples(void)
{
if(!(SoundInitSound(2, 22050, 512)))
puts(SoundGetError());
Samples.paddlehit = -1;
Samples.wallhit = -1;
Samples.paddlehit = SoundLoadSampleWAV(DATADIR"/paddle_hit.wav");
//puts(Sound_GetError());
Samples.wallhit = SoundLoadSampleWAV(DATADIR"/wall_hit.wav");
//puts(Sound_GetError());
printf("Paddle sample: %d, Wall sample: %d\n", \
Samples.paddlehit, Samples.wallhit);
puts(SoundGetError());
}
void DrawText(char text[128], int x, int y)
{
//could use a better text drawing function...
SDL_Color foregroundColor = { 255, 255, 255, 255 };
//SDL_Color backgroundColor = { 0, 0, 0 };
SDL_Rect textLocation = { x, y, 0, 0 };
//textSurface = TTF_RenderText_Shaded(font, text, foregroundColor, backgroundColor);
textSurface = TTF_RenderText_Solid(font, text, foregroundColor);
SDL_BlitSurface(textSurface, NULL, screen, &textLocation);
SDL_FreeSurface(textSurface); //have to free after render (otherwise memory leak)
}
void ClearScreen(int r, int g, int b)
{
//fill the screen with whatever rgb color
SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, r, g, b));
}
SDL_Surface *LoadImage(char filename[128])
{
//Temporary storage for the image that's loaded
SDL_Surface *loadedImage = NULL;
//The optimized image that will be used
SDL_Surface* optimizedImage = NULL;
loadedImage = IMG_Load(filename);//SDL_LoadBMP(filename);
if(loadedImage != NULL)
{
//Create an optimized image
optimizedImage = SDL_DisplayFormat(loadedImage);
//Free the old image
SDL_FreeSurface(loadedImage);
}
//Return the optimized image
return optimizedImage;
}
void SpawnSprite(s_sprite TmpSprite)
{
int i;
for(i=0;i<MAX_SPRITES;i++)
{
if(!(Sprite[i].enabled))
{
Sprite[i].enabled = 1;
Sprite[i].type = TmpSprite.type;
Sprite[i].x = TmpSprite.x;
Sprite[i].y = TmpSprite.y;
Sprite[i].xspeed = TmpSprite.xspeed;
Sprite[i].yspeed = TmpSprite.yspeed;
Sprite[i].w = TmpSprite.w;
Sprite[i].h = TmpSprite.h;
Sprite[i].tick = 0;
Sprite[i].lifespan = TmpSprite.lifespan;
Sprite[i].r = TmpSprite.r;
Sprite[i].g = TmpSprite.g;
Sprite[i].b = TmpSprite.b;
Sprite[i].a = TmpSprite.a;
Sprite[i].alphafade = TmpSprite.alphafade;
Sprite[i].faderate = TmpSprite.faderate;
break;
}
}
}
void ManageSprites(void)
{
int i;
for(i=0;i<MAX_SPRITES;i++)
{
if(Sprite[i].enabled)
{
if(Sprite[i].tick < Sprite[i].lifespan)
{
Sprite[i].tick += 1;
Sprite[i].x += Sprite[i].xspeed;
Sprite[i].y += Sprite[i].yspeed;
if(Sprite[i].alphafade)
Sprite[i].a -= Sprite[i].faderate;
//here is sprite physics
Sprite[i].x += Sprite[i].xspeed;
Sprite[i].y += Sprite[i].yspeed;
}
else if(Sprite[i].tick >= Sprite[i].lifespan)
{
Sprite[i].enabled = 0;
Sprite[i].tick = 0;
}
}
}
}
void RenderSprites(void)
//Much of this is untested/unused. Just written for completeness.
{
int i;
for(i=0;i<MAX_SPRITES;i++)
{
if(Sprite[i].enabled)
{
if(Sprite[i].type == SPRITE_IMAGE)
{
SDL_Rect offset,srcoffset;
offset.x = Sprite[i].x;
offset.y = Sprite[i].y;
offset.w = Sprite[i].w;
offset.h = Sprite[i].h;
srcoffset.x = Sprite[i].x;
srcoffset.y = Sprite[i].y;
srcoffset.w = Sprite[i].w;
srcoffset.h = Sprite[i].h;
//FIXME: This isn't correct
//SDL_BlitSurface(background, &srcoffset, screen, &offset );
}
else if(Sprite[i].type == SPRITE_PIXEL)
{
pixelRGBA(screen, Sprite[i].x, Sprite[i].y, \
Sprite[i].r, Sprite[i].g, Sprite[i].b, \
Sprite[i].a);
}
else if(Sprite[i].type == SPRITE_SPARK)
{
lineRGBA(screen, Sprite[i].x, Sprite[i].y, \
Sprite[i].x + Sprite[i].xspeed, \
Sprite[i].y + Sprite[i].yspeed, \
Sprite[i].r, Sprite[i].g, Sprite[i].b, \
Sprite[i].a);
}
else if(Sprite[i].type == SPRITE_RECT)
{
rectangleRGBA(screen, Sprite[i].x, Sprite[i].y, \
Sprite[i].x + Sprite[i].w, \
Sprite[i].y + Sprite[i].h, \
Sprite[i].r, Sprite[i].g, Sprite[i].b, \
Sprite[i].a);
}
else if(Sprite[i].type == SPRITE_FILLEDRECT)
{
boxRGBA(screen, Sprite[i].x, Sprite[i].y, \
Sprite[i].x + Sprite[i].w, \
Sprite[i].y + Sprite[i].h, \
Sprite[i].r, Sprite[i].g, Sprite[i].b, \
Sprite[i].a);
}
else if(Sprite[i].type == SPRITE_CIRCLE)
{
circleRGBA(screen, Sprite[i].x, Sprite[i].y, Sprite[i].rad, \
Sprite[i].r, Sprite[i].g, Sprite[i].b, Sprite[i].a);
}
else if(Sprite[i].type == SPRITE_FILLEDCIRCLE)
{
filledCircleRGBA(screen, Sprite[i].x, Sprite[i].y, Sprite[i].rad, \
Sprite[i].r, Sprite[i].g, Sprite[i].b, Sprite[i].a);
}
}
}
}
void SetGameState(enum GAME_STATES state)
{
if(GameState.state == STATE_QUITTING)
{
puts("Game Quitting!");
GameQuit();
}
GameState.state = state;
if(GameState.debug)
printf("GameState set to %d\n",GameState.state);
//check again to see if it was set to STATE_QUITTING
//and go ahead and quit from here. No point in waiting
//STATE_QUITTING checks in the game loop are basically just for safety
if(GameState.state == STATE_QUITTING)
{
puts("Game Quitting!");
GameQuit();
}
}
void RegulateFPS(void)
{
int timetodelay;
timetodelay = Frames.maxframetime - Frames.framems;
if(timetodelay > 0)
{
if(timetodelay < Frames.maxframetime)
SDL_Delay(timetodelay);
}
}
void CalcFPS(void)
{
if ((SDL_GetTicks() - (Frames.update)) > 1000)
{
Frames.fps = (Frames.frames) / (float)((SDL_GetTicks()-(Frames.update))) * 1000;
Frames.update = SDL_GetTicks();
if(GameState.debug)
printf("FPS: %4.3f, Avg. Frametime: %3.3fms\n",Frames.fps,(Frames.frametime / Frames.frames));
Frames.frames=0;
Frames.frametime=0;
}
Frames.frames++;
}
int RandInt(int min, int max)
{
int Neg;
if(min < 0)
{
Neg = rand() % 10 + 1;
if(Neg > 5)
return (rand() % max) + min;
else if(Neg <= 5)
return -((rand() % max) + min);
}
else
return (rand() % max) + min;
return 0;
}
float RandFloat(float min, float max)
{
int Neg;
if(min < 0)
{
Neg = rand() % 10 + 1;
if(Neg > 5)
return ( ((float)rand()/RAND_MAX) * (max-min)) + min; //space parentheses like this for readability?
else if(Neg <= 5)
return -( ( ((float)rand()/RAND_MAX) * (max-min)) + min);
}
else
return ( ((float)rand()/RAND_MAX) * (max-min)) + min;
return 0;
}
int DetectJPGs(char indir[256])
{
//TODO: pass an array byref to take the filenames
//TODO: and run this at start, loading images to pointer array
//or maybe not...
DIR *dhandle;
struct dirent *drecord;
struct stat sbuf;
int numfiles = 0;
dhandle = opendir(indir);
if(dhandle == NULL)
printf("(DetectJPGs) Failed to open directory!\n");
puts("Detecting .jpg files...");
while((drecord = readdir(dhandle)) != NULL)
{
stat(drecord->d_name,&sbuf);
if(!(strcmp(drecord->d_name+(strlen(drecord->d_name) - 4),".jpg")))
{
numfiles++;
printf("%s\n",drecord->d_name);
}
}
closedir(dhandle);
printf("Number of JPG's found: %d\n", numfiles);
return numfiles;
}
int UpdateProgressBar(int mode, int param)
{
if (mode == 0)
progressbar += param;
else if(mode == 1)
progressbar = param;
//bar container
rectangleRGBA(screen, (GameState.resx / 2) - 52, (GameState.resy / 2) - 12, \
(GameState.resx / 2) + 52, (GameState.resy / 2) + 11, \
255,255,255,255);
//bar
SDL_Rect bar;
bar.x = (GameState.resx / 2) - 50;
bar.y = (GameState.resy / 2) - 10;
bar.h = 20;
bar.w = progressbar;
SDL_FillRect(screen, &bar, SDL_MapRGB(screen->format, 0, 255, 0));
/*rectangleRGBA(screen, (GameState.resx / 2) - 50, (GameState.resy / 2) - 10, \
((GameState.resx / 2) - 50) + progressbar, (GameState.resy / 2) + 10, \
0,255,0,255); */
SDL_Flip(screen);
return 1;
}
void GameQuit(void)
{
TTF_Quit();
SDL_Quit();
if(GameState.debug)
puts("Hasta la vista, baby!");
exit(EXIT_SUCCESS);
}
//#####################################
//Menu Functions
//#####################################
void InitMenu(void)
{
Ball.x = RandInt(1,GameState.resx - Ball.size);
Ball.y = RandInt(1,GameState.resy - Ball.size);
Ball.xspeed = RandFloat(1,Ball.maxspeed);
Ball.yspeed = RandFloat(1,Ball.maxspeed);
Paddle[0].score = 0; Paddle[1].score = 0; //better fix...
}
void MenuLogic(void)
{
//Paddle[0].score = 0; Paddle[1].score = 0; //hackish fix...
MenuPhysics();
ManageBackground();
ManageSprites();
MenuRender();
RenderSprites();
SDL_Flip(screen);
}
void MenuKeyCheck(void)
{
while(SDL_PollEvent(&SDLevent))
{
switch (SDLevent.type)
{
case SDL_QUIT:
SetGameState(STATE_QUITTING);
break;
case SDL_KEYDOWN:
//if(GameState.debug)
//printf("Key pressed: %d\n",SDLevent.key.keysym.sym);
if(SDLevent.key.keysym.sym == SDLK_ESCAPE)
{
if(GameState.debug)
puts("Escape key pressed, quitting!");
SetGameState(STATE_QUITTING);
}
//spacebar to play!
else if(SDLevent.key.keysym.sym == SDLK_SPACE)
{
//setup and begin playing
if(GameState.debug)
puts("Starting game...");
GameState.twoplayer = 0;
SetGameState(STATE_INITIALIZING);
InitGame();
}
else if(SDLevent.key.keysym.sym == SDLK_TAB)
{
//setup and begin playing
if(GameState.debug)
puts("Starting game...");
GameState.twoplayer = 1;
SetGameState(STATE_INITIALIZING);
InitGame();
}
else if(SDLevent.key.keysym.sym == SDLK_d)
{
if(!GameState.debug)
{
GameState.debug = 1;
puts("Debug mode on.");
}
else
{
GameState.debug = 0;
puts("Debug mode off.");
}
}
else if(SDLevent.key.keysym.sym == SDLK_f)
{
if(!GameState.fullscreen)
{
GameState.fullscreen = 1;
InitSDL(GameState);
}
else
{
GameState.fullscreen = 0;
InitSDL(GameState);
}
}
else if(SDLevent.key.keysym.sym == SDLK_b)
{
InitBackground();
}
break;
}
}
}
void MenuPhysics(void)
{
//move ball around
Ball.x += Ball.xspeed;
Ball.y += Ball.yspeed;
BallTrail(BALL_TRAIL_LIFE); //ball trail
//check if it hits the sides, and make it bounce off
//nothing fancy, just using center of block as coords
if((Ball.x + Ball.size / 2) <= 0 || (Ball.x + Ball.size / 2) >= GameState.resx)
{
Ball.xspeed = -(Ball.xspeed);
BallSpark(BALL_HIT_SPARKS);
}
if((Ball.y + Ball.size / 2) <= 0 || (Ball.y + Ball.size / 2) >= GameState.resy)
{
Ball.yspeed = -(Ball.yspeed);
BallSpark(BALL_HIT_SPARKS);
}
}
void MenuRender(void)
{
//draw bkg before anything else
SDL_Rect offset,srcoffset;
offset.x = 0;
offset.y = 0;
offset.w = GameState.resx;
offset.h = GameState.resy;
srcoffset.x = Background.x;
srcoffset.y = Background.y;
srcoffset.w = GameState.resx;
srcoffset.h = GameState.resy;
SDL_BlitSurface(Background.image, &srcoffset, screen, &offset );
//char imgname[64];
//draw the ball. It be bouncin' (and it's actually a square)
SDL_Rect balldims;
balldims.x = Ball.x;
balldims.y = Ball.y;
balldims.w = Ball.size;
balldims.h = Ball.size;
SDL_FillRect(screen, &balldims, SDL_MapRGB(screen->format, 255, 255, 255));
//print winning text on menu once game is over
char EndRoundText[128];
if (GameState.winner >= 0)
{
if (GameState.twoplayer)
{
if (GameState.winner == 0)
{
sprintf(EndRoundText, "Player 1 Wins!");
DrawText(EndRoundText, ((GameState.resx / 2) - (strlen(EndRoundText) * 2)),(GameState.resy / 2) - 24);
}
else if (GameState.winner == 1)
{
sprintf(EndRoundText, "Player 2 Wins!");
DrawText(EndRoundText, ((GameState.resx / 2) - (strlen(EndRoundText) * 2)),(GameState.resy / 2) - 24);
}
}
else
{
if (GameState.winner == 0)
{
sprintf(EndRoundText, "You Win!");
DrawText(EndRoundText, ((GameState.resx / 2) - (strlen(EndRoundText) * 2)),(GameState.resy / 2) - 24);
}
else if (GameState.winner == 1)
{
sprintf(EndRoundText, "Bot Wins!");
DrawText(EndRoundText, ((GameState.resx / 2) - (strlen(EndRoundText) * 2)),(GameState.resy / 2) - 24);
}
}
}
//drawing the menu in the (more or less) middle of the screen
DrawText(MENU_TEXT, ((GameState.resx / 2) - (strlen(MENU_TEXT) * 2)),(GameState.resy / 2));
DrawText(MENU_TEXT2, ((GameState.resx / 2) - (strlen(MENU_TEXT2) * 2)),(GameState.resy / 2) + 14);
DrawText(MENU_TEXT3, ((GameState.resx / 2) - (strlen(MENU_TEXT3) * 2)),(GameState.resy / 2) + 28);
}
//#####################################
//Game Functions
//#####################################
void GameLoop(void)
{
//can only do one key check per frame due to the way SDL queue's events
//keypresses and other events
/*keychecking (specifically state-changing key checks)
go ahead of other stuff to avoid a bug */
/*switch(GameState.state)
{
case STATE_MENU:
MenuKeyCheck();
break;
case STATE_PLAYING:
GameKeyCheck();
break;
default:
break;
}*/
//herp why don't we just do it this way... as seen below
//don't see why they can't go into their respective logic functions...
switch(GameState.state)
{
/*Each state has it's own rendering/physics
function. This cuts down on complexity (as compared to
one big function with lots of condition checking). */
case STATE_QUITTING:
GameQuit();
break;
case STATE_MENU:
MenuKeyCheck();
MenuLogic();
break;
case STATE_PLAYING:
GameKeyCheck();
GameLogic();
break;
default:
puts("Houston, we have a problem.");
break;
}
}
void GameLogic(void)
{
if(!(GameState.paused))
{
if(!(GameState.twoplayer))
AIThink();
GamePhysics();
GoalCheck();
ManageBackground();
ManageSprites();
PaddleEffects();
}
GameRender();
RenderSprites();
SDL_Flip(screen);
}
void GameKeyCheck(void)
{
//check keystates for game stuffs before keydown events that will
//break the loop
SDL_KeyStates = SDL_GetKeyState( NULL );
if(SDL_KeyStates[SDLK_UP])
Paddle[1].yspeed = -(Paddle[1].speed);
else if(SDL_KeyStates[SDLK_DOWN])
Paddle[1].yspeed = Paddle[1].speed;
if(GameState.twoplayer)
{
if(SDL_KeyStates[SDLK_a])
Paddle[0].yspeed = -(Paddle[0].speed);
else if(SDL_KeyStates[SDLK_z])
Paddle[0].yspeed = Paddle[0].speed;
}
while(SDL_PollEvent(&SDLevent))
{
switch (SDLevent.type)
{
case SDL_QUIT:
SetGameState(STATE_QUITTING); //could do it directly
//but this avoids errors
break;
case SDL_KEYDOWN:
if(GameState.debug)
printf("Key pressed: %d\n",SDLevent.key.keysym.sym);
if(SDLevent.key.keysym.sym == SDLK_ESCAPE)
{
if(GameState.debug)
puts("Escape key pressed, quitting!");
SetGameState(STATE_QUITTING);
}
else if(SDLevent.key.keysym.sym == SDLK_SPACE)
{
//something?
}
else if(SDLevent.key.keysym.sym == SDLK_d)
{
if(!GameState.debug)
{
GameState.debug = 1;
puts("Debug mode on.");
}
else
{
GameState.debug = 0;
puts("Debug mode off.");
}
}
else if(SDLevent.key.keysym.sym == SDLK_p)
{
if(!GameState.paused)
{
GameState.paused = 1;
}
else
{
GameState.paused = 0;
}
}
else if(SDLevent.key.keysym.sym == SDLK_f)
{
if(!GameState.fullscreen)
{
GameState.fullscreen = 1;
InitSDL(GameState);
}
else
{
GameState.fullscreen = 0;
InitSDL(GameState);
}
}
else if(SDLevent.key.keysym.sym == SDLK_m)
{
SetGameState(STATE_MENU);
InitMenu();
GameState.paused = 0;
}
else if(SDLevent.key.keysym.sym == SDLK_b)
{
InitBackground();
}
break;
case SDL_KEYUP:
if(SDLevent.key.keysym.sym == SDLK_UP)
Paddle[1].yspeed = 0;
else if(SDLevent.key.keysym.sym == SDLK_DOWN)
Paddle[1].yspeed = 0;
if(GameState.twoplayer)
{
if(SDLevent.key.keysym.sym == SDLK_a)
Paddle[0].yspeed = 0;
else if(SDLevent.key.keysym.sym == SDLK_z)
Paddle[0].yspeed = 0;
}
}
}
}
void GamePhysics(void)
{
int over,under,i; //vars used in this func
int playchannel; //for debuggin sound
//move paddles
for(i=0;i<2;i++)
{
if(Paddle[i].y >= 0 && (Paddle[i].y + Paddle[i].height) <= GameState.resy)
Paddle[i].y += Paddle[i].yspeed;
}
//bot sets it's own velocity in AIThink() function, but follows same rules as player
//if it's out of bounds, move it back
for(i=0;i<2;i++)
{
if(Paddle[i].y < 0)
{
under = 0 - Paddle[i].y;
Paddle[i].y += under;
}
else if((Paddle[i].y + Paddle[i].height) > GameState.resy)
{
over = (Paddle[i].y + Paddle[i].height) - GameState.resy;
Paddle[i].y -= over;
}
}
//move ball around
if(Ball.movedelay <= 0)
{
Ball.x += Ball.xspeed;
Ball.y += Ball.yspeed;
BallTrail(BALL_TRAIL_LIFE); //ball trail (no point in trailing when it's not moving!)