File:  [Local Repository] / talos / src / talos.c
Revision 1.1.1.1 (vendor branch): download - view: text, annotated - select for diffs
Tue Jun 30 01:53:13 2009 UTC (15 years, 4 months ago) by nick
Branches: TALOS, MAIN
CVS tags: V1_0, HEAD
Initial Import

/*
 * Froggix 
 *
 * Nicholas DeClario 2009
 * <nick@declario.com>
 *
 * This program is distributed under the GNU Public License
 *   <Insert GNU license blurb here>
 */


/*
 * Our pretty standard includes
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

#include <SDL.h>
#include <SDL_mixer.h>
#include <SDL_image.h>
#include <SDL_ttf.h>

/* 
 * Set some basic definitions
 */
#define VER "$Id: talos.c,v 1.1.1.1 2009/06/30 01:53:13 nick Exp $";
#define TITLE "Talos"
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
#define FALSE 0
#define TRUE 1
#define LIVES 3
#define COLORKEY 255, 0, 255
#define BGCOLOR 0, 0, 0
#define TALOS_START_X 290
#define TALOS_START_Y 425
#define UP 1
#define DOWN 2
#define LEFT 3
#define RIGHT 4
#define X 0
#define Y 1
#define FRAME 24
#define HFRAME 12

/* Point table */
#define HIGH_SCORE 4630

/* baddies */
#define VEHICLE 0
#define LOG 1
#define TURTLE 2
#define GATOR 3
#define SNAKE 4
#define BEAVER 5

/* Turtles */
#define DIVE_START_TIME 50
#define DIVE_PHASE_TIME 20
#define MAX_TURTLES 9
#define TURTLE_ANIM_TIME 5

/* Vehicles */
#define MAX_VEHICLES 40


/*
 * Froggers dstruct
 */
typedef struct {
	int placement[2];
	int oldPlacement[2];
	int direction;
	int location; 
	int hopCount;
	int currentRow;
	int alive;
	int riding;
	int ridingIdx;
	int ridingType;
	int talos;	/* Are we talos or bonus talos */
	int deathType;
	int deathCount;

	SDL_Rect src;
	SDL_Rect dst;

	Mix_Chunk *s_hop;
	Mix_Chunk *s_squash;
	Mix_Chunk *s_splash;
	Mix_Chunk *s_extra;
} talosObj;

/*
 * Vehicles
 */
typedef struct {
	int placement[2];
	int oldPlacement[2];
	int direction; 	// LEFT or RIGHT
	int row;  	// row
	int speed;	// How fast are we traveling
	int level;	// Must be >= this level to display
		
	SDL_Rect src;
} vehicleObj;

int keyEvents( SDL_Event event );
int mySDLInit( void );
void beginGame( void );
int loadMedia( void );
int heartbeat( void );
int updateGameState( void );
void checkFly( void );
void checkGator( void );
void configGameScreen( void );
void drawGameScreen( void );
void drawBackground( void );
int getRowPixel ( int row );
int collisionRow ( void );
int freeFrog( int score );
int collideFrogger ( int x, int y, int h, int w );
void checkFroggerBorder( void );
void levelUp( void );
int checkGoals( void );
void talosReset( void );
void moveFrogger( void );
void ridingFrogger( );
void drawTitleScreen( void );
void drawPauseScreen( void );
void drawGameOver( void );
int drawDeathSequence( int deathType );
int checkTimer( void );
void drawScore( int high, int score );
void drawNumbers( int num, int x, int y );
void drawGoals( void );
void drawTimer( int length );
void drawLives( int lives );
void drawLevel( int level );
void drawWood( void );
void drawTurtles( void );
void drawVehicles( void );
void drawImage(SDL_Surface *srcimg, int sx, int sy, int sw, int sh, SDL_Surface *dstimg, int dx, int dy, int alpha );
void playSound( Mix_Chunk *sound );
void setFullScreenMode( void );

int flyTimer = 0;
int gatorTimer = 0;
int level = 0;
int playing = 0;
int lives = 0;
int players = 0;
int score = 0;
int givenFreeFrog = 0;
int hScore = HIGH_SCORE;
int redraw_all = 0;
int fullscreen = 0;
int drawBG = 0;
int goDelay;
float timeLeft;
talosObj talos;

Mix_Chunk  *s_freeFrog;
SDL_Surface *gfx;
SDL_Surface *background; // This is the talos back drop
SDL_Rect backgroundRect;
SDL_Surface *titleSurface; // Title 'Froggix' image
SDL_Surface *screen; //This pointer will reference the backbuffer 
SDL_Rect leftBorderRect;
SDL_Rect rightBorderRect;
TTF_Font *font;

int debugBorder = 0;

/*
 * int mySDLInit(void);
 *
 * This starts the basic SDL initialization for everything we'll need
 * 	
 */
int mySDLInit( void ) {
	int result = 1;

	if( SDL_Init( SDL_INIT_VIDEO ) != 0 ) {
		fprintf( stderr, "Warning: Unable to initialize video: %s\n", SDL_GetError( ) );
		result--;
	}

	if( TTF_Init( ) == -1 ) {
		fprintf( stderr, "Warning: Unable to initialize font engine: %s\n", TTF_GetError( ) );
		result--;
	}

	if( SDL_Init( SDL_INIT_AUDIO ) != 0 ) {
		fprintf( stderr, "Warning: Unable to initialize audio: %s\n", SDL_GetError( ) );
		result--;
	}
	
	if( Mix_OpenAudio( 11025, AUDIO_S16, 2, 512 ) < 0 ) {
		fprintf( stderr, "Warning: Audio set failed: %s\n", SDL_GetError( ) );
		result--;
	}

	screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, 16, SDL_HWSURFACE );

	if ( screen == NULL ) {
		fprintf( stderr, "Error: Unable to set video mode: %s\n", SDL_GetError( ) );
		result--;
	}

	SDL_WM_SetCaption( TITLE, NULL );

	return result;
}

/*
 * void beginGame( void );
 *
 * Main game routine
 */
void beginGame( void ) {
	float	next_heartbeat = 0;
	SDL_Event event;
	int 	done = 0;

	printf ( "D: Starting main game loop\n" );

	if ( loadMedia( ) <= 0 ) {
		fprintf( stderr, "Error: Failed to load graphics and audio!\n" );
		return;
	}

	drawBackground( );

	while( ! done ) {
		while( SDL_PollEvent( &event ) ) {
			done = keyEvents( event );
		}

		/* Check the heartbeat to see if we're ready */
		if ( SDL_GetTicks( ) >= next_heartbeat ) {
			next_heartbeat = SDL_GetTicks( ) + heartbeat( );
		}
		SDL_Delay( 30 );
	}

	SDL_FreeSurface( gfx );
}

int loadMedia( void ) {
	int result = 1;

	/*
 	 * Load talos's textures and sounds
 	 */
	gfx = IMG_Load( "images/talos.png" );
	if ( gfx == NULL ) {
		fprintf( stderr, "Error: 'images/talos.bmp' could not be open: %s\n", SDL_GetError( ) );
		result--;
	}

	if ( SDL_SetColorKey( gfx, SDL_SRCCOLORKEY | SDL_RLEACCEL, SDL_MapRGB( gfx->format, COLORKEY ) ) == -1 ) 
		fprintf( stderr, "Warning: colorkey will not be used, reason: %s\n", SDL_GetError( ) );

	background = IMG_Load( "images/gameboard.png" );

	if ( gfx == NULL ) {
		fprintf( stderr, "Error: 'images/gameboard.png' could not be open: %s\n", SDL_GetError( ) );
		result--;
	}

	titleSurface = IMG_Load( "images/talos-title.png" );
	if ( titleSurface == NULL ) {
		fprintf( stderr, "Error: 'images/talos-title.png' could not be open: %s\n", SDL_GetError( ) );
		result--;
	}

	font = TTF_OpenFont( "fonts/CourierNew-Bold.ttf", 22 );
	if ( font == NULL ) {
		printf( "TTF_OpenFont: %s\n", TTF_GetError( ) );
		result--;
	}

	talos.s_hop = Mix_LoadWAV( "sounds/talos-hop.wav" );

	if ( talos.s_hop == NULL ) 
		fprintf( stderr, "Warning: dp_talos_hop.wav could not be opened: %s\n", SDL_GetError( ) );

	talos.s_squash = Mix_LoadWAV( "sounds/dp_talos_squash.wav" );
	if ( talos.s_squash == NULL )
		fprintf( stderr, "Warning: dp_talos_plunk could not be opened %s\n", SDL_GetError( ));

	talos.s_splash = Mix_LoadWAV( "sounds/dp_talos_plunk.wav" );
	if ( talos.s_splash == NULL )
		fprintf( stderr, "Warning: dp_talos_splash could not be opened %s\n", SDL_GetError( ));

	s_freeFrog = Mix_LoadWAV( "sounds/dp_talos_extra.wav" );
	if ( s_freeFrog == NULL )
		fprintf( stderr, "Warning: dp_talos_extra could not be opened %s\n", SDL_GetError( ));

	return result;
}

/*
 * void keyEvents( void );
 *
 * Process the incoming keyboard and mouse events
 *
 */
int keyEvents( SDL_Event event ) {
	int done = 0;

	/* Always check for shutdown */
	switch( event.type ) {
		case SDL_QUIT:
			done = 1;
			break;
		case SDL_KEYDOWN:
			/* printf( "Found key: %i\n", event.key.keysym.sym );*/
			switch( event.key.keysym.sym ) {
				case SDLK_ESCAPE:
					done = 1;
					break;
				case 102:
					setFullScreenMode( );
					break;
				default: 
					break;
			}
			break;
		default: 	
			break;
	}
	/* We are playing the game */
	if ( level ) {
		/* Main game playing input */
		if ( playing ) {
			if ( event.type == SDL_KEYDOWN && talos.alive ) {
				switch( event.key.keysym.sym ) {
					case SDLK_UP:
						if ( ! talos.direction ) {
							talos.hopCount = 0;
							talos.direction = UP;
							talos.currentRow++;
							playSound( talos.s_hop );
						}
						break;
					case SDLK_DOWN:
						if ( ! talos.direction ) {
							talos.hopCount = 0;
							talos.direction = DOWN;
							talos.currentRow--;
							playSound( talos.s_hop );
						}
						break;
					case SDLK_LEFT:
						if ( ! talos.direction ) {
							talos.hopCount = 0;
							talos.direction = LEFT;
							playSound( talos.s_hop );
						}
						break;
					case SDLK_RIGHT:
						if ( ! talos.direction ) {
							talos.hopCount = 0;
							talos.direction = RIGHT;
							playSound( talos.s_hop );
						}
						break;
					case 108:
						levelUp( );
						fprintf( stderr, "Increase level to %i.\n", level );
						break;
					default:
						break;
				}
/* Uncomment for positioning debug information
				printf( "x,y,d => %i,%i,%i,%i\n", talos.placement[X],
							       talos.placement[Y],
							       talos.direction,
							       talos.currentRow );
*/
			}
			/* Game over man, game over! */
			if ( ! lives ) {
		
			}
		}
		/* we're at the pause screen */
		else {

		}
	}
	/* Main intro screen input */
	else {
		if ( event.type == SDL_KEYUP ) {
			switch( event.key.keysym.sym ) {
				case SDLK_ESCAPE:
					done = 1;
					break;
				case SDLK_1:
					printf( "D: Starting single player game\n" );
					level = 1;
					lives = LIVES;
					playing = TRUE;
					score = 0;
					players = 1;
					redraw_all = 1;
					break;
				default:
					break;
			}
		}
	}

	return done;
}

int updateGameState( void ) {

	if ( ! drawBG ) configGameScreen( );

	if ( lives <= 0 ) {
		goDelay++;
		drawGameOver( );
		/* Display game over screen for 50 ticks before returning
 		 * to the main screen */
		if ( goDelay > 7 ) {
			playing = 0;
			lives   = 0;
			level   = 0;
			score   = 0;
			givenFreeFrog = 0;
			drawBG  = 0;
			
		}
		return 500;
	}

	drawGameScreen( );

	return 50;
}

void configGameScreen( void ) {
	drawBG = 1;

	/*
 	 * Draw background map
 	 */
	//drawBackground( );
	drawImage( background, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, screen, 0, 0, 255 );

	/* Cars drive on rows 1 - 5
 	 * Logs are on rows 8, 9 and 11, 8 = short, 9 long, 11 medium
 	 * Turtles are on rows 7, 10
 	 * Frogger starts on Row 0, 
 	 * Sidewalk is row 6
 	 * and the goal is row 12
 	 */

	/* I MUST figure out a better way to handle the logs, turtles and cars */

	/* 
 	 * Draw talos in starting position 
 	 */
	talosReset( );
}

void drawGameScreen( void ) {
	/* 
 	 * Update talos
 	 */
	if ( talos.direction ) moveFrogger( );
	if ( talos.riding ) ridingFrogger( );

	/*
 	 * Update and draw everthing else
 	 */
	checkFly( );
	checkGator( );
	drawImage( background, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, screen, 0, 0, 255 );
	drawScore( 0, score );
	drawScore( 1, hScore );
	drawGoals( );
	drawLives( lives );
	drawLevel( level );
	drawWood( );
	drawTurtles( );
	drawVehicles( );

	if ( talos.alive == FALSE ) {
		talos.riding = FALSE;
		if ( ! drawDeathSequence( talos.deathType ) ) {
			lives--;
			if ( lives < 0 ) { drawGameOver( ); }
			else { talosReset( ); }	
		}
	}

	if ( talos.alive )  {
		talos.alive = checkTimer( );
		drawImage( gfx, talos.src.x, talos.src.y, talos.src.w,
			   talos.src.h, screen, talos.dst.x, talos.dst.y, 255 );
	}
	if ( ! debugBorder ) {
		SDL_FillRect( screen, &leftBorderRect,  SDL_MapRGB( screen->format, BGCOLOR ) );
		SDL_FillRect( screen, &rightBorderRect, SDL_MapRGB( screen->format, BGCOLOR ) );
	}

	SDL_Flip( screen );
}

void drawBackground( void ) {
        /*
         * Draw background map
         */
        backgroundRect.x = 0;
        backgroundRect.y = 0;
        SDL_BlitSurface( background, NULL, screen, &backgroundRect );
	SDL_UpdateRect( screen, 0, 0, 0, 0 );
}

/*
 * This calculates the pixel top of the requested row 
 */
int getRowPixel ( int row ) {
	return 0;//ROW_BASE - ( row * HOP_DISTANCE );
}

/*
 * Check our fly timers to determine if we need to display or
 * remove a fly from the goal area
 */
void checkFly ( void ) {
}

/*
 * Check our gator timers.  Similiar to fly timers above, however, the gator
 * has an extra stage as it enters in to the goal area.
 */
void checkGator ( void ) {
}

/*
 * This does collision detection based on the row talos
 * is in to help reduce overhead 
 */
int collisionRow ( void ) {
	return 0;
}

/* If the player gets enough points, award them a free talos */
int freeFrog ( int score ) {
	return 0;
}

/* Check what talos is colliding with */
int collideFrogger ( int x, int y, int h, int w ) {
	h++; w++;
	
        if ( ( talos.placement[Y] >= ( y + h ) ) ||
             ( talos.placement[X] >= ( x + w ) ) ||
             ( y >= ( talos.placement[Y] + FRAME ) ) ||
             ( x >= ( talos.placement[X] + FRAME ) ) ) {
                return( 0 );
        }
        return( 1 );
}

/* Check left and right borders */
void checkFroggerBorder( void ) {

}

void levelUp ( void ) {
}

int checkGoals ( void ) {
	return 0;
}

void talosReset ( void ) {
}

/*
 * This actually moves talos...  I need to come up with a better
 * algorithm for calculating the distance and time
 */
void moveFrogger( void ) {
	int x = 0;
	int y = 0;
	int h = FRAME;
	int w = FRAME;
	
	talos.oldPlacement[Y] = talos.placement[Y];
	talos.oldPlacement[X] = talos.placement[X];

	switch( talos.direction ) {
		case UP:
			x = FRAME;
			// talos.placement[Y] -= ( HOP_DISTANCE / HOP_SPEED );
			break;
		case DOWN:
			x = ( 5 * FRAME );
			// talos.placement[Y] += ( HOP_DISTANCE / HOP_SPEED );
			break;
		case LEFT:
			x = ( 7 * FRAME );
			// talos.placement[X] -= ( HOP_DISTANCE / HOP_SPEED );
			break;
		case RIGHT:
			x = ( 3 * FRAME );
			//talos.placement[X] += ( HOP_DISTANCE / HOP_SPEED );
			break;	
	}

	checkFroggerBorder( );

	/* select the frame to display */
	talos.src.y = y;
	talos.src.x = x;
	talos.src.w = w;
	talos.src.h = h;

	/* Set the old place to be erased */
	talos.dst.y = talos.oldPlacement[Y];
	talos.dst.x = talos.oldPlacement[X];

	SDL_FillRect( screen, NULL, SDL_MapRGB( screen->format, BGCOLOR ) );

	/* Place the new position */
	talos.dst.y = talos.placement[Y];
	talos.dst.x = talos.placement[X];

	talos.hopCount++;

}

void ridingFrogger( void ) {
}

void drawTitleScreen( void ) {
	SDL_Surface *introText;
	SDL_Color fontColor = { 123, 158, 53, 255 };
	int center = ( SCREEN_WIDTH / 2 ) - ( titleSurface->w / 2 );
	int i;
	char *txt[] = { "Press 1 for single player game",
		        "Press 2 for two player games",
		        "Press F for full screen mode",
		        "Press ESC to quit" };

	// drawBackground( );

	drawImage( titleSurface, 0, 0, titleSurface->w, 
		   titleSurface->h, screen, center, 100, 255 );

	for( i = 0; i <= 3; i++ ) {
		introText = TTF_RenderText_Solid( font, txt[i], fontColor );
		drawImage( introText, 0, 0, introText->w, introText->h, screen, 
			   140, 300 + ( i * introText->h ), 255 );
	}

	SDL_Flip( screen );
}

void drawPauseScreen( void ) {
	printf( "D: Draw Pause Screen\n" );

}

void drawGameOver( void ) {
	printf( "D: Game Over\n" );
}

void playSound( Mix_Chunk *sound ) {
	Mix_PlayChannel( -1, sound, 0 );
}

void setFullScreenMode( void ) {
	/* Lets give fullscreen mode a try */
	if ( ! fullscreen ) {
		screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, 16, SDL_HWSURFACE | SDL_FULLSCREEN );
		fullscreen = TRUE;
	}
	/* Switch back to window mode */
	else {
		screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, 16, SDL_HWSURFACE );
		fullscreen = FALSE;
	}

	printf( "D: Fullscreen : %i\n", fullscreen );
}

int drawDeathSequence( int deathType ) {
	return 1;
}

/* draw green timer and return 0 if out of time */
int checkTimer( void ) {
	return 1;
}

void drawScore( int high, int score ) {
	int x = 169;
	int y = 14;

	if ( score > hScore ) hScore = score;	
	if ( high ) x = 260;
		
	drawNumbers( score, x, y );		
}

void drawNumbers( int num, int x, int y ) {
	char numStr[6] = "00000";
	int i;

	/* Assume anything less than 50 pixels location is a score and
         * pad with '0'.
         */
	if ( y <= 15 ) sprintf( numStr, "%05i", num );
	else  	       sprintf( numStr, "%i", num );

	for ( i = 0; i <= 4; i++ ) {
		char c = numStr[i];
		int n = atoi( &c );

		drawImage( gfx, n * HFRAME, FRAME * 3 , HFRAME, FRAME, 
			   screen, x + ( i * HFRAME ) + 2, y, 255 );
	}
}

/* Normally this functions manages and draws the flys, gators and saved taloss
 * but if drawDebugRect below is turned on it will draw the rectangle
 * used for collision detectiong for debuggin purposes in timer green
 */
void drawGoals( void ) {

}

void drawTimer( int length ) {
}

void drawLives( int lives ) {
}

void drawLevel( int level ) {
}

void drawWood ( void ) {
}

void drawTurtles ( void ) {
}

void drawVehicles ( void ) {

}

void drawImage( SDL_Surface *srcimg, int sx, int sy, int sw, int sh, 
		SDL_Surface *dstimg, int dx, int dy, int alpha ) {
  if ((!srcimg) || (alpha == 0)) return; 
  SDL_Rect src, dst;        

  src.x = sx;  src.y = sy;  src.w = sw;     src.h = sh;
  dst.x = dx;  dst.y = dy;  dst.w = src.w;  dst.h = src.h;

  if (alpha != 255) SDL_SetAlpha(srcimg, SDL_SRCALPHA, alpha); 
  SDL_BlitSurface(srcimg, &src, dstimg, &dst);                
}

int heartbeat ( void ) {
	int ticks;
	if ( level ) {
		if ( playing ) {
			ticks = updateGameState( );
			if ( ticks <= 0 ) ticks = 50;
			return ticks;		
		}
		else {
			drawPauseScreen( );
			return 500;
		}
	}
	else {
		drawTitleScreen( );
		return 500;
	}

	return 50;
}

/*
 * Main program starts here.  We'll init the video and audio
 * and then begin our main program loop here
 *
 */
int main ( int argc, char **argv ) {
	if ( mySDLInit( ) <= 0 ) {
		fprintf( stderr, "Failure to start %s\n", TITLE );
		return 255;
	}

	beginGame( );

	SDL_Quit( );
	
	return 0;
}

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>