Tennix 0.4.2
[tennix.git] / game.c
blob8160b50d75ad87066dc6196cf2a0b9f0b1803b0b
2 /**
4 * Tennix! SDL Port
5 * Copyright (C) 2003, 2007 Thomas Perl <thp@perli.net>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 * MA 02110-1301, USA.
22 **/
24 #include <stdio.h>
25 #include <math.h>
27 #include "tennix.h"
28 #include "game.h"
29 #include "graphics.h"
30 #include "input.h"
31 #include "sound.h"
33 void game( bool singleplayer) {
34 GameState s = {
35 { 0, 0, 0.0, 0.0, 0.0 },
36 { 0, 0, 0, 0, 0 },
37 { GAME_X_MIN-RACKET_X_MID*2, GAME_Y_MID, 0, 0, 1, DESIRE_NORMAL, PLAYER_TYPE_HUMAN, false },
38 { GAME_X_MAX+RACKET_X_MID*2, GAME_Y_MID, 0, 0, 0, DESIRE_NORMAL, PLAYER_TYPE_HUMAN, false },
42 true,
43 "welcome to tennix " VERSION,
44 { 0 },
45 { 0 },
46 REFEREE_NORMAL,
48 WINNER_NONE,
49 false,
50 GR_CTT_GRASS,
51 { 0 },
53 false,
54 { { { 0 } } },
55 0.0
58 strcpy( s.game_score_str, format_game( &s));
59 strcpy( s.sets_score_str, format_sets( &s));
61 Uint32 ot = SDL_GetTicks();
62 Uint32 nt;
63 Uint32 dt = GAME_TICKS;
64 Uint32 diff;
65 Uint32 accumulator = 0;
66 bool quit = false;
67 int x, y, z;
69 if( singleplayer) {
70 #ifdef DEBUG
71 s.player1.type = PLAYER_TYPE_AI;
72 #endif
73 s.player2.type = PLAYER_TYPE_AI;
76 game_setup_serve( &s);
77 sound_audience();
79 /* smoothen n-gram */
80 for( x = 0; x<NGRAM_STEPS; x++) {
81 for( y = 0; y<NGRAM_STEPS; y++) {
82 for( z = 0; z<NGRAM_STEPS; z++) {
83 s.ngram[x][y][z] = 1;
88 while( !quit) {
89 nt = SDL_GetTicks();
90 diff = nt-ot;
91 if( diff > 2000) {
92 diff = 0;
95 accumulator += diff;
96 ot = nt;
98 while( accumulator >= dt) {
99 quit = step( &s);
100 s.time += dt;
101 accumulator -= dt;
103 if( s.was_stopped) {
104 ot = SDL_GetTicks();
105 s.was_stopped = false;
109 render( &s);
114 bool step( GameState* s) {
115 Uint8 *keys;
116 SDL_Event e;
118 if( get_phase( s) < 1.0) {
119 if( !s->ground.jump) {
120 sound_ground();
122 if( IS_OUT_Y( s->ball.y)) {
123 /* out - responsibilities stay the same */
124 s->status = "out!";
125 sound_out();
126 s->referee = REFEREE_OUT;
127 } else {
128 /* not out - responsibilities change */
129 s->player1.responsible = !(s->player2.responsible = !s->player2.responsible);
130 s->status = format_status( s);
131 s->referee = REFEREE_NORMAL;
134 s->ground.jump = 3;
135 s->ground.x = s->ball.x;
136 s->ground.y = s->ball.y;
137 } else {
138 if( s->ground.jump && !(s->time%5)) s->ground.jump--;
141 if( IS_OUT_X(s->ball.x) || IS_OFFSCREEN_Y(s->ball.y)) {
142 if( IS_OFFSCREEN( s->ball.x, s->ball.y)) {
143 s->player1_serves = s->player1.responsible;
145 score_game( s, s->player2.responsible);
146 strcpy( s->game_score_str, format_game( s));
147 strcpy( s->sets_score_str, format_sets( s));
149 if( s->player1.responsible) {
150 if( s->player1.type == PLAYER_TYPE_HUMAN && s->player2.type == PLAYER_TYPE_AI) {
151 s->status = "computer scores";
152 } else {
153 s->status = "player 2 scores";
155 s->referee = REFEREE_PLAYER2;
156 } else {
157 if( s->player1.type == PLAYER_TYPE_HUMAN && s->player2.type == PLAYER_TYPE_AI) {
158 s->status = "player scores";
159 } else {
160 s->status = "player 1 scores";
162 s->referee = REFEREE_PLAYER1;
165 game_setup_serve( s);
166 sound_applause();
167 SDL_Delay( 500);
168 start_fade();
169 s->was_stopped = true;
170 s->history_size = 0;
171 s->history_is_locked = 0;
172 s->ngram_prediction = 0.0;
173 #ifdef DEBUG
174 printf( "-- game reset --\n");
175 #endif
178 if( IS_OUT_X(s->ball.x)) {
179 if( !s->history_is_locked && s->referee != REFEREE_OUT) {
180 s->history[s->history_size] = (int)(NGRAM_STEPS*s->ball.y/HEIGHT);
181 s->history_size++;
182 if( s->history_size == 3) {
183 s->ngram[s->history[0]][s->history[1]][s->history[2]] += 10;
184 #ifdef DEBUG
185 printf( "history: %d, %d, %d\n", s->history[0], s->history[1], s->history[2]);
186 #endif
187 s->ngram_prediction = ngram_predictor( s);
188 s->history[0] = s->history[1];
189 s->history[1] = s->history[2];
190 s->history_size--;
192 s->history_is_locked = true;
194 if( s->ball.move_x <= 0 && IS_NEAR_X( s->player1.x, s->ball.x) && IS_NEAR_Y( s->player1.y, s->ball.y) && s->player1.state && s->referee != REFEREE_OUT) {
195 s->ball.x = GAME_X_MIN;
196 if( s->player1.state == PLAYER_STATE_MAX) {
197 s->ball.move_x = PLAYER_POWERSHOT;
198 } else {
199 s->ball.move_x = 2.5 + 2.0*s->player1.state/PLAYER_STATE_MAX;
201 s->ball.move_y = get_move_y( s, 1);
202 s->player2.responsible = !(s->player1.responsible = 1);
203 s->ball.jump += 1.0-2.0*(s->player1.state<5);
204 sound_applause_stop();
205 sound_racket();
206 } else if( s->ball.move_x >= 0 && IS_NEAR_X( s->player2.x, s->ball.x) && IS_NEAR_Y( s->player2.y, s->ball.y) && s->player2.state && s->referee != REFEREE_OUT) {
207 s->ball.x = GAME_X_MAX;
208 if( s->player2.state == PLAYER_STATE_MAX) {
209 s->ball.move_x = -PLAYER_POWERSHOT;
210 } else {
211 s->ball.move_x = -(2.5 + 2.0*s->player2.state/PLAYER_STATE_MAX);
213 s->ball.move_y = get_move_y( s, 2);
214 s->player1.responsible = !(s->player2.responsible = 1);
215 s->ball.jump += 1.0-2.0*(s->player2.state<5);
216 sound_applause_stop();
217 sound_racket();
220 } else {
221 s->history_is_locked = false;
224 /* Update ball_dest for debugging purposes */
225 get_move_y( s, 1);
226 get_move_y( s, 2);
228 s->ball.x += s->ball.move_x;
229 s->ball.y += s->ball.move_y;
231 if( s->player1.state) s->player1.state--;
232 if( s->player2.state) s->player2.state--;
234 SDL_PollEvent( &e);
235 keys = SDL_GetKeyState( NULL);
237 if( keys['c'] && s->time%50==0) {
238 s->court_type++;
239 if( s->court_type > GR_CTT_LAST) {
240 s->court_type = GR_CTT_FIRST;
244 if( !is_fading() && !s->is_over) {
245 if( s->player1.type == PLAYER_TYPE_HUMAN) {
246 input_human( &s->player1, keys['w'], keys['s'], keys['d']);
247 } else {
248 input_ai( &s->player1, &s->ball, &s->player2, s);
251 if( s->player2.type == PLAYER_TYPE_HUMAN) {
252 input_human( &s->player2, keys['o'], keys['l'], keys['k']);
253 } else {
254 input_ai( &s->player2, &s->ball, &s->player1, s);
258 if( keys['f']) SDL_WM_ToggleFullScreen( screen);
259 if( keys['y']) SDL_SaveBMP( screen, "screenshot.bmp");
261 if( keys['p']) {
262 while( keys['p']) {
263 SDL_PollEvent( &e);
264 keys = SDL_GetKeyState( NULL);
265 SDL_Delay( 10);
267 while( keys['p'] == 0) {
268 SDL_PollEvent( &e);
269 keys = SDL_GetKeyState( NULL);
270 SDL_Delay( 10);
272 while( keys['p']) {
273 SDL_PollEvent( &e);
274 keys = SDL_GetKeyState( NULL);
275 SDL_Delay( 10);
277 s->was_stopped = true;
280 if( keys[SDLK_ESCAPE] || keys['q']) return true;
282 limit_value( &s->player1.y, PLAYER_Y_MIN, PLAYER_Y_MAX);
283 limit_value( &s->player2.y, PLAYER_Y_MIN, PLAYER_Y_MAX);
284 limit_value( &s->ball.jump, BALL_JUMP_MIN, BALL_JUMP_MAX);
286 return false;
289 void render( GameState* s) {
290 if( s->winner != WINNER_NONE) {
291 if( !s->is_over) {
292 start_fade();
293 s->is_over = true;
295 clearscr();
296 show_sprite( GR_RACKET, 2*(s->winner-1), 4, WIDTH/2 - get_image_width( GR_RACKET)/8, HEIGHT/2 - get_image_height( GR_RACKET), 255);
297 sprintf( s->game_score_str, "player %d wins the match with %s", s->winner, format_sets( s));
298 font_draw_string( GR_DKC2_FONT, s->game_score_str, (WIDTH-font_get_string_width( GR_DKC2_FONT, s->game_score_str))/2, HEIGHT/2 + 30, s->time/20, ANIMATION_WAVE | ANIMATION_BUNGEE);
299 updatescr();
300 return;
302 clearscr();
303 fill_image( s->court_type, 120, 120, 400, 250);
304 show_image( GR_COURT, 0, 0, 255);
305 show_sprite( GR_REFEREE, s->referee, 4, 250, 10, 255);
306 show_image( GR_SHADOW, s->ball.x-BALL_X_MID, s->ball.y + get_phase( s) - BALL_Y_MID, 255);
308 show_sprite( GR_RACKET, (!s->player1.state), 4, s->player1.x-RACKET_X_MID, s->player1.y-RACKET_Y_MID, 255);
309 show_sprite( GR_RACKET, (!s->player2.state)+2, 4, s->player2.x-RACKET_X_MID, s->player2.y-RACKET_Y_MID, 255);
311 if( s->ground.jump) {
312 show_sprite( GR_GROUND, s->ground.jump-1, 3, s->ground.x - BALL_X_MID, s->ground.y - BALL_Y_MID, 128);
315 if( s->ball.move_x > 0) {
316 show_sprite( GR_BALL, (s->time/500)%4, 4, s->ball.x-BALL_X_MID, s->ball.y-BALL_Y_MID, 255);
317 } else if( s->ball.move_x < 0) {
318 show_sprite( GR_BALL, 3-(s->time/500)%4, 4, s->ball.x-BALL_X_MID, s->ball.y-BALL_Y_MID, 255);
319 } else {
320 show_sprite( GR_BALL, 0, 4, s->ball.x-BALL_X_MID, s->ball.y-BALL_Y_MID, 255);
324 font_draw_string( GR_DKC2_FONT, s->game_score_str, 14, 14, 0, ANIMATION_NONE);
325 font_draw_string( GR_DKC2_FONT, s->sets_score_str, (WIDTH-font_get_string_width( GR_DKC2_FONT, s->sets_score_str))-14, 14, 0, ANIMATION_NONE);
327 font_draw_string( GR_DKC2_FONT, s->status, (WIDTH-font_get_string_width( GR_DKC2_FONT, s->status))/2, HEIGHT-50, s->time/30, ANIMATION_WAVE);
329 #ifdef DEBUG
330 line_horiz( s->player1.y, 255, 0, 0);
331 line_horiz( s->player2.y, 0, 0, 255);
332 line_horiz( s->ball.y, 0, 255, 0);
334 line_vert( s->player1.x, 255, 0, 0);
335 line_vert( s->player2.x, 0, 0, 255);
336 line_vert( s->ball.x, 0, 255, 0);
338 line_horiz( s->player1.ball_dest, 255, 0, 255);
339 line_horiz( s->player2.ball_dest, 0, 255, 255);
341 line_horiz( GAME_Y_MIN, 100, 100, 100);
342 line_horiz( GAME_Y_MAX, 100, 100, 100);
343 #endif
345 updatescr();
348 void limit_value( float* value, float min, float max) {
349 if( *value < min) {
350 *value = min;
351 } else if( *value > max) {
352 *value = max;
356 float get_phase( GameState* s) {
357 float pos, fract;
358 float x, min, max, direction;
360 x = s->ball.x;
361 min = GAME_X_MIN;
362 max = GAME_X_MAX;
363 direction = s->ball.move_x;
365 pos = (direction>0)?(1-GROUND_PHASE):(GROUND_PHASE);
367 fract = (x-min)/(max-min);
369 if( fract < pos) {
370 fract = fract/pos;
371 return fabsf( cosf(PI*fract/2))*PHASE_AMP*s->ball.jump;
372 } else {
373 fract = (pos-fract)/(1-pos);
374 return fabsf( sinf(PI*fract/2))*PHASE_AMP*s->ball.jump;
378 float get_move_y( GameState* s, unsigned char player) {
379 float pct, dest, x_len, y_len;
380 float py, by, pa, move_x;
382 py = (player==1)?(s->player1.y):(s->player2.y);
383 by = s->ball.y;
384 pa = RACKET_Y_MID*2;
385 move_x = s->ball.move_x;
387 /* -1.0 .. 1.0 for racket hit position */
388 pct = (by-py)/(pa/2);
389 limit_value( &pct, -1.0, 1.0);
391 /* Y destination for ball */
392 dest = GAME_Y_MID + pct*(GAME_Y_MAX-GAME_Y_MIN);
393 if( player == 1) {
394 s->player1.ball_dest = dest;
395 } else {
396 s->player2.ball_dest = dest;
399 /* lengths for the ball's journey */
400 if( player == 1) {
401 x_len = fabsf(GAME_X_MAX - s->ball.x);
402 y_len = dest - by + MOVE_Y_SEED-rand()%MOVE_Y_SEED*2;
403 } else {
404 x_len = s->ball.x - GAME_X_MIN;
405 y_len = by - dest + MOVE_Y_SEED-rand()%MOVE_Y_SEED*2;
408 /* return the should-be value for move_y */
409 return (y_len*move_x)/(x_len);
412 void input_human( Player* player, bool up, bool down, bool hit) {
413 if( up) {
414 player->y -= 6;
417 if( down) {
418 player->y += 6;
421 if( hit) {
422 if( !player->state && !player->state_locked) {
423 player->state = PLAYER_STATE_MAX;
424 player->state_locked = true;
426 } else {
427 player->state_locked = false;
431 void input_ai( Player* player, Ball* ball, Player* opponent, GameState* s) {
432 float fact = 1.7;
433 float target;
435 if( fabsf( player->y - ball->y) > RACKET_Y_MID*5) {
436 fact = 3.5;
439 target = GAME_Y_MID + (opponent->ball_dest - GAME_Y_MID)/5;
441 if( player->responsible) {
442 if( player->desire == DESIRE_NORMAL && !IS_NEAR_Y_AI( player->y, ball->y)) {
443 if( player->y < ball->y) {
444 player->y += fmin( 2*fact, ball->y - player->y);
445 } else if( player->y > ball->y) {
446 player->y -= fmin( 2*fact, player->y - ball->y);
450 if( (ball->move_x != 0 || IS_NEAR_Y_AI( player->y, ball->y)) && IS_NEAR_X_AI( player->x, ball->x) && !player->state && rand()%4) {
451 player->state = PLAYER_STATE_MAX;
453 } else if( ball->move_x == 0) {
454 if( player->desire == DESIRE_NORMAL && !IS_NEAR_Y_AI( player->y, target)) {
455 if( player->y < target) {
456 player->y += fmin( fact, (target-player->y)/40.0);
457 } else if( player->y > target) {
458 player->y -= fmin( fact, (player->y-target)/40.0);
461 } else if( s->ngram_prediction > 0.0) {
462 target = s->ngram_prediction*((float)HEIGHT)/((float)(NGRAM_STEPS));
463 target = GAME_Y_MID + (target-GAME_Y_MID)*1.5;
465 if( player->desire == DESIRE_NORMAL && !IS_NEAR_Y_AI( player->y, target)) {
466 if( player->y < target) {
467 player->y += fmin( fact, (target-player->y)/40.0);
468 } else if( player->y > target) {
469 player->y -= fmin( fact, (player->y-target)/40.0);
472 } else {/*
473 if( player->desire == DESIRE_NORMAL) {
474 if( !IS_NEAR_Y_AI( player->y, target)) {
475 player->y += (target - player->y)/40.0;
481 void game_setup_serve( GameState* s) {
482 s->ball.jump = 7.5;
483 s->ball.y = GAME_Y_MID;
484 s->ball.move_x = 0.0;
485 s->ball.move_y = 0.0;
487 if( s->player1_serves) {
488 s->player1.responsible = true;
489 s->player1.ball_dest = 0.0;
490 s->ball.x = GAME_X_MIN-RACKET_X_MID*1.5;
491 } else {
492 s->player1.responsible = false;
493 s->player2.ball_dest = 0.0;
494 s->ball.x = GAME_X_MAX+RACKET_X_MID*1.5;
497 s->player2.responsible = !(s->player1.responsible);
500 float ngram_predictor( GameState* s) {
501 unsigned int count = 0;
502 unsigned long sum = 0;
503 int x, y, z;
504 float result;
506 if( s->history_size < 3) {
507 return 0.0;
510 x = s->history[1];
511 y = s->history[2];
513 for( z = 0; z<NGRAM_STEPS; z++) {
514 count += s->ngram[x][y][z];
515 sum += z * s->ngram[x][y][z];
518 result = ((float)(sum))/((float)(count));
519 #ifdef DEBUG
520 printf( "predicting next = %.2f\n", result);
521 #endif
523 return result;
526 void score_game( GameState* s, bool player1_scored) {
527 Player* winner = (player1_scored)?(&(s->player1)):(&(s->player2));
528 Player* loser = (player1_scored)?(&(s->player2)):(&(s->player1));
530 if( s->current_set >= SETS_TO_WIN*2-1) {
531 return;
534 winner->game++;
535 if( loser->game < winner->game-1) {
536 if( winner->game >= 4) {
537 winner->game = loser->game = 0;
538 winner->sets[s->current_set]++;
539 /* scoring the set.. */
540 if( (winner->sets[s->current_set] == 6 && loser->sets[s->current_set] < 5) ||
541 winner->sets[s->current_set] == 7) {
542 s->current_set++;
543 s->winner = game_get_winner( s);
549 char* format_sets( GameState* s) {
550 static char sets[100];
551 static char tmp[100];
552 int i, max = s->current_set;
554 sets[0] = '\0';
556 if( s->winner != WINNER_NONE) {
557 max--;
559 for( i=0; i<=max; i++) {
560 sprintf( tmp, "%d:%d, ", s->player1.sets[i], s->player2.sets[i]);
561 strcat( sets, tmp);
564 sets[strlen(sets)-2] = '\0';
566 return sets;
569 char* format_game( GameState* s) {
570 static char game[100];
571 static const int game_scoring[] = { 0, 15, 30, 40 };
573 if( s->player1.game < 4 && s->player2.game < 4) {
574 sprintf( game, "%d - %d", game_scoring[s->player1.game], game_scoring[s->player2.game]);
575 } else if( s->player1.game > s->player2.game) {
576 strcpy( game, "advantage player 1");
577 } else if( s->player1.game < s->player2.game) {
578 strcpy( game, "advantage player 2");
579 } else {
580 strcpy( game, "deuce");
583 return game;
586 char* format_status( GameState* s) {
587 static char status[100];
588 static const char* set_names[] = { "first", "second", "third", "fourth", "fifth" };
590 sprintf( status, "%d:%d in %s set", s->player1.sets[s->current_set], s->player2.sets[s->current_set], set_names[s->current_set]);
592 return status;
595 int game_get_winner( GameState* s) {
596 int i;
597 int sets[2] = {0};
599 for( i=0; i<s->current_set; i++) {
600 if( s->player1.sets[i] > s->player2.sets[i]) {
601 sets[0]++;
602 } else {
603 sets[1]++;
607 if( sets[0] == SETS_TO_WIN) return WINNER_PLAYER1;
608 if( sets[1] == SETS_TO_WIN) return WINNER_PLAYER2;
610 return WINNER_NONE;