author | andyq <andyq> | 2003-01-21 20:37:00 (UTC) |
---|---|---|
committer | andyq <andyq> | 2003-01-21 20:37:00 (UTC) |
commit | 0a6563fcc2f49857c581d9def24407a3a4ef526c (patch) (side-by-side diff) | |
tree | f1b82a4bd7582ef2cb722cffb87eecff1e1f96e6 | |
parent | 50b5915b48fc5cbacf23e4d2b75d7a266f141a4a (diff) | |
download | opie-0a6563fcc2f49857c581d9def24407a3a4ef526c.zip opie-0a6563fcc2f49857c581d9def24407a3a4ef526c.tar.gz opie-0a6563fcc2f49857c581d9def24407a3a4ef526c.tar.bz2 |
Clean up of code - fixed memory leaks (most of them) and added new custom config menu
25 files changed, 682 insertions, 300 deletions
diff --git a/noncore/games/sfcave-sdl/animatedimage.cpp b/noncore/games/sfcave-sdl/animatedimage.cpp index d9d6ff6..441c647 100644 --- a/noncore/games/sfcave-sdl/animatedimage.cpp +++ b/noncore/games/sfcave-sdl/animatedimage.cpp @@ -1,13 +1,13 @@ #include "SDL.h" #include "SDL_image.h" #include "constants.h" #include "animatedimage.h" -AnimatedImage :: AnimatedImage( QString file, int nFrames ) +AnimatedImage :: AnimatedImage( string file, int nFrames ) { nrFrames = nFrames; currentFrame = 0; // Load image image = IMG_Load( (const char *)file.c_str() ); @@ -16,15 +16,12 @@ AnimatedImage :: AnimatedImage( QString file, int nFrames ) nrFrames = 0; image = 0; return; } SDL_SetColorKey(image, SDL_SRCCOLORKEY | SDL_RLEACCEL, SDL_MapRGB( image->format, 0, 0, 0 ) ); -// image = SDL_DisplayFormat( tmp ); - -// SDL_FreeSurface( tmp ); frameWidth = image->w/nrFrames; frameHeight = image->h; } AnimatedImage :: ~AnimatedImage() { @@ -44,12 +41,15 @@ bool AnimatedImage :: nextFrame() return rc; } void AnimatedImage :: draw( SDL_Surface *screen, int x, int y ) { + if ( !image ) + return; + SDL_Rect dst; dst.x = currentFrame * frameWidth; dst.y = 0; dst.w = frameWidth; dst.h = frameHeight; diff --git a/noncore/games/sfcave-sdl/animatedimage.h b/noncore/games/sfcave-sdl/animatedimage.h index 1b38e6d..3c03f52 100644 --- a/noncore/games/sfcave-sdl/animatedimage.h +++ b/noncore/games/sfcave-sdl/animatedimage.h @@ -3,13 +3,13 @@ #include "SDL.h" class AnimatedImage { public: - AnimatedImage( QString file, int nFrames ); + AnimatedImage( string file, int nFrames ); ~AnimatedImage(); bool nextFrame(); void draw( SDL_Surface *screen, int x, int y ); bool AtEnd(); void reset() { currentFrame = 0; } diff --git a/noncore/games/sfcave-sdl/bfont.cpp b/noncore/games/sfcave-sdl/bfont.cpp index 0f29104..7dec8f5 100644 --- a/noncore/games/sfcave-sdl/bfont.cpp +++ b/noncore/games/sfcave-sdl/bfont.cpp @@ -70,16 +70,12 @@ void BFont::LoadFont (const char *filename) Chars[x].h = 0; Chars[x].w = 0; } InitFont(); // Init the font } } - else - { - cerr << "Error! The font has not been loaded!" << endl; - } } BFont * BFont :: SetFontColor(Uint8 r, Uint8 g, Uint8 b) { int x,y; @@ -110,13 +106,12 @@ BFont * BFont :: SetFontColor(Uint8 r, Uint8 g, Uint8 b) if (SDL_MUSTLOCK(surface)) SDL_LockSurface(surface); if (SDL_MUSTLOCK(Surface)) SDL_LockSurface(Surface); color_key = xGetPixel(Surface, 0, Surface->h-1); - printf("looking...\n"); for( x=0; x < Surface->w; x++) { for( y=0; y < Surface->h; y++) { old_r = old_g = old_b = 0; pixel = xGetPixel(Surface,x,y); if (pixel != color_key) { @@ -128,13 +123,13 @@ BFont * BFont :: SetFontColor(Uint8 r, Uint8 g, Uint8 b) pixel = SDL_MapRGB(surface->format,new_r,new_g,new_b); } PutPixel(surface,x,y,pixel); } } - printf("unlooking...\n"); + if (SDL_MUSTLOCK(surface)) SDL_UnlockSurface(surface); if (SDL_MUSTLOCK(Surface)) SDL_UnlockSurface(Surface); SDL_SetColorKey(surface, SDL_SRCCOLORKEY, color_key); } diff --git a/noncore/games/sfcave-sdl/constants.h b/noncore/games/sfcave-sdl/constants.h index 8fadae4..f10764e 100644 --- a/noncore/games/sfcave-sdl/constants.h +++ b/noncore/games/sfcave-sdl/constants.h @@ -1,12 +1,11 @@ #ifndef __CONSTANTS_H #define __CONSTANTS_H #include <string> using namespace std; -#define QString string #ifdef QWS #define IMAGES_PATH "/opt/QtPalmtop/pics/sfcave/data/" #define SOUND_PATH "/opt/QtPalmtop/sounds/sfcave/" #else #define IMAGES_PATH "./images/" @@ -52,16 +51,34 @@ using namespace std; #define MENU_GAME_SFCAVE 13 #define MENU_GAME_GATES 14 #define MENU_GAME_FLY 15 #define MENU_DIFFICULTY_EASY 16 #define MENU_DIFFICULTY_NORMAL 17 #define MENU_DIFFICULTY_HARD 18 -#define MENU_SOUNDS 19 -#define MENU_SOUND_ON 20 -#define MENU_SOUND_OFF 21 -#define MENU_MUSIC_ON 22 -#define MENU_MUSIC_OFF 23 +#define MENU_DIFFICULTY_HARD 18 +#define MENU_DIFFICULTY_CUSTOM 19 +#define MENU_SOUNDS 20 +#define MENU_SOUND_ON 21 +#define MENU_SOUND_OFF 22 +#define MENU_MUSIC_ON 23 +#define MENU_MUSIC_OFF 24 +#define MENU_CUSTOM_THRUST 25 +#define MENU_CUSTOM_GRAVITY 26 +#define MENU_CUSTOM_MAXSPEEDUP 27 +#define MENU_CUSTOM_MAXSPEEDDOWN 28 +#define MENU_CUSTOM_INCREASE 29 +#define MENU_CUSTOM_DECREASE 30 +#define MENU_CUSTOM_SAVE 31 +#define MENU_CUSTOM_CANCEL 32 // Sounds #define SND_EXPLOSION 0 #define SND_THRUST 1 +#define INGAME_MUSIC SOUND_PATH "ingame.mod" + +// Constants for player values +#define PLAYER_THRUST 0 +#define PLAYER_GRAVITY 1 +#define PLAYER_MAX_SPEED_UP 2 +#define PLAYER_MAX_SPEED_DOWN 3 + #endif diff --git a/noncore/games/sfcave-sdl/fly_game.cpp b/noncore/games/sfcave-sdl/fly_game.cpp index f5ab401..7605c3f 100644 --- a/noncore/games/sfcave-sdl/fly_game.cpp +++ b/noncore/games/sfcave-sdl/fly_game.cpp @@ -14,12 +14,13 @@ FlyGame :: FlyGame( SFCave *p, int w, int h, int diff ) player = new Player( w, h ); highScore = 0; } FlyGame :: ~FlyGame() { + // terrain and player get deleted by parent class } void FlyGame :: init() { Game :: init(); @@ -31,12 +32,21 @@ void FlyGame :: init() case MENU_DIFFICULTY_NORMAL: player->setMovementInfo( 0.35, 0.4, 2.5, 3 ); break; case MENU_DIFFICULTY_HARD: player->setMovementInfo( 0.4, 0.6, 4, 5 ); break; + case MENU_DIFFICULTY_CUSTOM: + { + double thrust = parent->loadDoubleSetting( "Fly_custom_player_thrust", 0.3 ); + double gravity = parent->loadDoubleSetting( "Fly_custom_player_gravity", 0.2 ); + double maxUp = parent->loadDoubleSetting( "Fly_custom_player_maxupspeed", 1.5 ); + double maxDown = parent->loadDoubleSetting( "Fly_custom_player_maxdownspeed", 1.5 ); + player->setMovementInfo( thrust, gravity, maxUp, maxDown ); + break; + } } startScoring = false; } void FlyGame :: update( int state ) @@ -47,13 +57,13 @@ void FlyGame :: update( int state ) { if ( nrFrames % 3 == 0 ) { int diff = terrain->getMapBottom( 10 ) - player->getY(); int tmpScore = ((FlyTerrain *)terrain)->getScore( 1, diff ); -// printf( "diff - %d score - %d\n", diff, tmpScore ); + if ( !startScoring ) { if ( tmpScore > 0 ) startScoring = true; } @@ -66,13 +76,12 @@ void FlyGame :: update( int state ) score += tmpScore; } } if ( checkCollisions() ) { -// printf( "Crashed!\n" ); parent->changeState( STATE_CRASHING ); return; } // Game logic goes here terrain->moveTerrain( 5 ); diff --git a/noncore/games/sfcave-sdl/font.cpp b/noncore/games/sfcave-sdl/font.cpp index 2976d48..1988252 100644 --- a/noncore/games/sfcave-sdl/font.cpp +++ b/noncore/games/sfcave-sdl/font.cpp @@ -5,30 +5,42 @@ BFont *FontHandler :: menuSelFont; BFont *FontHandler :: menuUnSelFont; BFont *FontHandler :: whiteFont; BFont *FontHandler :: colouredFont; BFont *FontHandler :: helpFont; -void FontHandler :: init() +bool FontHandler :: init() { // Load font images // Convert to fonts menuSelFont = new BFont( IMAGES_PATH "sel_menu_font.bmp" ); menuUnSelFont = new BFont( IMAGES_PATH "unsel_menu_font.bmp" ); whiteFont = new BFont( IMAGES_PATH "score_font.bmp" ); helpFont = new BFont( IMAGES_PATH "help_font.bmp" ); colouredFont = 0; + + // Check if we are installed correctly (we need fonts to function) + if ( menuSelFont == 0 || menuUnSelFont == 0 || whiteFont == 0 || helpFont == 0 ) + { + printf( "One or more fonts are not installed correctly\n" ); + return false; + } + + return true; } void FontHandler :: cleanUp() { + if ( menuSelFont ) delete menuSelFont; + if ( menuUnSelFont ) delete menuUnSelFont; + if ( whiteFont ) delete whiteFont; + if ( helpFont ) delete helpFont; - if ( colouredFont ) delete colouredFont; } int FontHandler :: TextWidth( int font, const char *text ) { diff --git a/noncore/games/sfcave-sdl/font.h b/noncore/games/sfcave-sdl/font.h index e5bb707..5f0674a 100644 --- a/noncore/games/sfcave-sdl/font.h +++ b/noncore/games/sfcave-sdl/font.h @@ -10,13 +10,13 @@ #define FONT_COLOURED_TEXT 4 #define FONT_HELP_FONT 5 class FontHandler { public: - static void init(); + static bool init(); static void cleanUp(); static int TextWidth( int font, const char *text ); static int FontHeight( int font ); static void draw( SDL_Surface *screen, int font, const char *text, int x, int y ); static void changeColor( int font, int r, int g, int b ); diff --git a/noncore/games/sfcave-sdl/game.cpp b/noncore/games/sfcave-sdl/game.cpp index a644696..e41e510 100644 --- a/noncore/games/sfcave-sdl/game.cpp +++ b/noncore/games/sfcave-sdl/game.cpp @@ -73,55 +73,59 @@ void Game :: handleKeys( SDL_KeyboardEvent &key ) { if ( key.type == SDL_KEYDOWN ) { if ( !press ) replayList.push_back( nrFrames ); press = true; - -// if ( thrustChannel == -1 && parent->getState() == STATE_PLAYING ) -// thrustChannel = SoundHandler :: playSound( SND_THRUST, -1, -1, false ); } else { if ( press ) replayList.push_back( nrFrames ); press = false; - if ( thrustChannel != -1 ) - { -// SoundHandler :: stopSound( thrustChannel, true, 300 ); -// thrustChannel = -1; - } } } } -QString Game :: getGameDifficultyText() +string Game :: getGameDifficultyText() { - QString ret; + string ret; if ( difficulty == MENU_DIFFICULTY_EASY ) ret = "Easy"; else if ( difficulty == MENU_DIFFICULTY_NORMAL ) ret = "Medium"; else if ( difficulty == MENU_DIFFICULTY_HARD ) ret = "Hard"; + else if ( difficulty == MENU_DIFFICULTY_CUSTOM ) + ret = "Custom"; return ret; } void Game :: setDifficulty( string diff ) { if ( diff == "Easy" ) difficulty = MENU_DIFFICULTY_EASY; else if ( diff == "Medium" ) difficulty = MENU_DIFFICULTY_NORMAL; else if ( diff == "Hard" ) difficulty = MENU_DIFFICULTY_HARD; + else if ( diff == "Custom" ) + difficulty = MENU_DIFFICULTY_CUSTOM; + + init(); +} + +void Game :: setDifficulty( int diff ) +{ + difficulty = diff; + init(); } void Game :: update( int state ) { nrFrames ++; @@ -163,20 +167,19 @@ void Game :: preDraw( SDL_Surface *screen ) { } void Game :: draw( SDL_Surface *screen ) { char tmp[100]; - QString scoreText; + string scoreText; sprintf( tmp, "Score: %06ld High Score: %06ld", score, highScore ); -// printf( "%s\n", (const char *)scoreText ); FontHandler::draw( screen, FONT_WHITE_TEXT, tmp, 3, 10 ); if ( parent->getState() == STATE_CRASHED ) { - QString crashText; + string crashText; crashText = "Game Over"; int x = (240 - FontHandler::TextWidth( FONT_WHITE_TEXT, (const char *)crashText.c_str() )) / 2; FontHandler::draw( screen, FONT_WHITE_TEXT, (const char *)crashText.c_str(), x, 150 ); int fontHeight = FontHandler::FontHeight( FONT_WHITE_TEXT ); crashText = "Press Middle Button to play again"; @@ -220,26 +223,26 @@ void Game :: setSeed( int seed ) currentSeed = ((unsigned long) time((time_t *) NULL)); else currentSeed = seed; PutSeed( currentSeed ); } -void Game :: saveReplay( QString file ) +void Game :: saveReplay( string file ) { FILE *out; out = fopen( file.c_str(), "w" ); if ( !out ) { printf( "Couldn't write to /home/root/%s\n", file.c_str() ); parent->setMenuStatusText( "Couldn't save replay file" ); return; } // Build up string of values // Format is:: <landscape seed> <game type> <difficulty> <framenr> <framenr>....... - QString val; + string val; char tmp[20]; sprintf( tmp, "%d %d ", currentSeed, difficulty ); val = tmp; list<int>::iterator it = replayList.begin(); while( it != replayList.end() ) @@ -248,26 +251,23 @@ void Game :: saveReplay( QString file ) val += tmp; it++; } val += "\n"; - QString line; + string line; sprintf( tmp, "%d\n", val.length() ); line = tmp; fwrite( line.c_str(), 1, line.length(), out ); fwrite( val.c_str(), 1, val.length(), out ); fclose( out ); - - printf( "Replay saved to %s\n", (const char *)file.c_str() ); - } -void Game :: loadReplay( QString file ) +void Game :: loadReplay( string file ) { FILE *in = fopen( (const char *)file.c_str(), "r" ); if ( in == 0 ) { @@ -282,15 +282,14 @@ void Game :: loadReplay( QString file ) int length = -1; sscanf( line, "%d", &length ); char *data = new char[length+1]; fread( data, 1, length, in ); -// printf( "data - %s", data ); - QString sep = " "; + string sep = " "; StringTokenizer st( data, sep ); // print it out vector<string>::iterator it = st.begin(); currentSeed = atoi( (*it).c_str() ); @@ -305,15 +304,12 @@ void Game :: loadReplay( QString file ) replayList.push_back( v ); } delete data; fclose( in ); - - printf( "Replay loaded from %s\n", (const char *)file.c_str() ); - } Game *Game :: createGame( SFCave *p, int w, int h, string game, string difficulty ) { Game *g; diff --git a/noncore/games/sfcave-sdl/game.h b/noncore/games/sfcave-sdl/game.h index 56fa6a1..087f848 100644 --- a/noncore/games/sfcave-sdl/game.h +++ b/noncore/games/sfcave-sdl/game.h @@ -22,35 +22,36 @@ public: virtual void stateChanged( int from, int to ); void setReplay( bool val ) { replay = val; } void handleKeys( SDL_KeyboardEvent &key ); - QString getGameName() { return gameName; } + string getGameName() { return gameName; } int getDifficulty() { return difficulty; } - QString getGameDifficultyText(); - void setDifficulty( int diff ) { difficulty = diff; } + string getGameDifficultyText(); + void setDifficulty( int diff ); void setDifficulty( string diff ); long getScore() { return score; } long getHighScore() { return highScore; } void increaseScore( long val ) { score += val; } void clearScore() { score = 0; } bool gotHighScore() { return (score >= highScore); } bool isReplayAvailable() { return replayList.size() > 0; } Terrain *getTerrain() { return terrain; } + Player *getPlayer() { return player; } void setSeed( int seed ); - void loadReplay( QString file ); - void saveReplay( QString file ); + void loadReplay( string file ); + void saveReplay( string file ); static Game *createGame( SFCave *p, int w, int h, string game, string difficulty ); protected: - QString gameName; + string gameName; int thrustChannel; int difficulty; SFCave *parent; @@ -66,17 +67,15 @@ protected: long score; long highScore; // Stuff for the replays int currentSeed; -// QListIterator<int> *replayIt; list<int> replayList; list<int>::iterator replayIt; -// QList<int> replayList; bool replay; - QString replayFile; + string replayFile; private: }; #endif diff --git a/noncore/games/sfcave-sdl/gates_game.cpp b/noncore/games/sfcave-sdl/gates_game.cpp index 1a9bc89..762801d 100644 --- a/noncore/games/sfcave-sdl/gates_game.cpp +++ b/noncore/games/sfcave-sdl/gates_game.cpp @@ -15,12 +15,13 @@ GatesGame :: GatesGame( SFCave *p, int w, int h, int diff ) player = new Player( w, h ); highScore = 0; } GatesGame :: ~GatesGame() { + // terrain and player get deleted by parent class } void GatesGame :: init() { Game :: init(); @@ -43,12 +44,25 @@ void GatesGame :: init() player->setMovementInfo( 0.4, 0.6, 4, 5 ); break; case MENU_DIFFICULTY_HARD: gapHeight = 25; player->setMovementInfo( 0.6, 0.8, 6, 7 ); break; + case MENU_DIFFICULTY_CUSTOM: + { + // Read custom difficulty settings for this game + gapHeight = parent->loadIntSetting( "Gates_custom_gapHeight", 75 ); + + double thrust = parent->loadDoubleSetting( "Gates_custom_player_thrust", 0.4 ); + double gravity = parent->loadDoubleSetting( "Gates_custom_player_gravity", 0.6 ); + double maxUp = parent->loadDoubleSetting( "Gates_custom_player_maxupspeed", 4.0 ); + double maxDown = parent->loadDoubleSetting( "Gates_custom_player_maxdownspeed", 5.0 ); + player->setMovementInfo( thrust, gravity, maxUp, maxDown ); + + break; + } } for ( int i = 0 ; i < BLOCKSIZE ; ++i ) blocks[i].y( -1 ); } @@ -74,13 +88,12 @@ void GatesGame :: update( int state ) nextGate = nrFrames + nextInt( 50 ) + gateDistance; addGate(); } if ( checkCollisions() ) { -// printf( "Crashed!\n" ); parent->changeState( STATE_CRASHING ); return; } terrain->moveTerrain( 5 ); moveBlocks( 5 ); diff --git a/noncore/games/sfcave-sdl/help.cpp b/noncore/games/sfcave-sdl/help.cpp index 91c62da..f1728f6 100644 --- a/noncore/games/sfcave-sdl/help.cpp +++ b/noncore/games/sfcave-sdl/help.cpp @@ -54,13 +54,12 @@ void Help :: init() }
void Help :: draw( SDL_Surface *screen )
{
stars->draw( screen );
-
list<string>::iterator it = textList.begin();
// Move to start of text
for ( int i = 0 ; i < currLine && it != textList.end() ; ++i )
it++;
diff --git a/noncore/games/sfcave-sdl/menu.cpp b/noncore/games/sfcave-sdl/menu.cpp index 0a7366f..a4a4216 100644 --- a/noncore/games/sfcave-sdl/menu.cpp +++ b/noncore/games/sfcave-sdl/menu.cpp @@ -5,13 +5,13 @@ #include "sfcave.h" #include "game.h" #include "menu.h" #include "font.h" #include "starfield.h" -MenuOption :: MenuOption( QString text, int id ) +MenuOption :: MenuOption( string text, int id ) { menuText = text; menuId = id; nextMenu = 0; highlighted = false; } @@ -112,19 +112,21 @@ Menu :: Menu( SFCave *p ) item->setNextMenu( options ); item = gameType->addMenuOption( "Back", MENU_BACK ); item->setNextMenu( options ); typeMenu->setNextMenu( gameType ); // Game Difficulty menu + MenuOption *customMenu = 0; Menu *gameDifficulty = new Menu( options ); item = gameDifficulty->addMenuOption( "Easy", MENU_DIFFICULTY_EASY ); item->setNextMenu( options, false ); item = gameDifficulty->addMenuOption( "Normal", MENU_DIFFICULTY_NORMAL ); item->setNextMenu( options, false ); item = gameDifficulty->addMenuOption( "Hard", MENU_DIFFICULTY_HARD ); item->setNextMenu( options, false ); + customMenu = gameDifficulty->addMenuOption( "Custom", MENU_DIFFICULTY_CUSTOM ); item = gameDifficulty->addMenuOption( "Back", MENU_BACK ); item->setNextMenu( options, false ); difficultyMenu->setNextMenu( gameDifficulty ); // Sounds Menu Menu *sounds = new Menu( options ); @@ -133,12 +135,35 @@ Menu :: Menu( SFCave *p ) sounds->addMenuOption( "Music On", MENU_MUSIC_ON ); sounds->addMenuOption( "Music Off", MENU_MUSIC_OFF ); item = sounds->addMenuOption( "Back", MENU_BACK ); item->setNextMenu( options, false ); soundsMenu->setNextMenu( sounds ); + // Custom Menu + Menu *custom = new Menu( gameDifficulty ); + Menu *updown = new Menu( custom ); + item = custom->addMenuOption( "Thrust", MENU_CUSTOM_THRUST ); + item->setNextMenu( updown ); + item = custom->addMenuOption( "Gravity", MENU_CUSTOM_GRAVITY ); + item->setNextMenu( updown ); + item = custom->addMenuOption( "Max Speed Up", MENU_CUSTOM_MAXSPEEDUP ); + item->setNextMenu( updown ); + item = custom->addMenuOption( "Max Speed Down", MENU_CUSTOM_MAXSPEEDDOWN ); + item->setNextMenu( updown ); + item = custom->addMenuOption( "Back", MENU_BACK ); + item->setNextMenu( gameDifficulty, false ); + customMenu->setNextMenu( custom ); + + // Up down menu + item = updown->addMenuOption( "Increase", MENU_CUSTOM_INCREASE ); + item = updown->addMenuOption( "Decrease", MENU_CUSTOM_DECREASE ); + item = updown->addMenuOption( "Save", MENU_CUSTOM_SAVE ); + item->setNextMenu( custom, false ); + item = updown->addMenuOption( "Cancel", MENU_CUSTOM_CANCEL ); + item->setNextMenu( custom, false ); + // Set static variables for menu selection up mainMenu = this; currentMenuOption = 0; resetToTopMenu(); @@ -212,13 +237,12 @@ void Menu :: draw( SDL_Surface *screen ) int Menu :: handleKeys( SDL_KeyboardEvent &key ) { if ( key.type != SDL_KEYDOWN ) return -1; - statusText = ""; switch( key.keysym.sym ) { case SDLK_DOWN: { // Move to next menu item currentMenu->currentMenuOption->highlight( false ); @@ -273,50 +297,49 @@ int Menu :: handleKeys( SDL_KeyboardEvent &key ) break; } case SDLK_LEFT: if ( currentMenu->parentMenu != 0 ) { + statusText = ""; currentMenu = currentMenu->parentMenu; - printf( "HERE\n" ); return -1; } break; case SDLK_RETURN: case SDLK_SPACE: { + statusText = ""; // select menu item int id = currentMenu->currentMenuOption->getMenuId(); -// // if the current item has a child menu then move to that menu + + // if the current item has a child menu then move to that menu Menu *next = currentMenu->currentMenuOption->getNextMenu(); if ( next != 0 ) { bool down = currentMenu->currentMenuOption->isDownMenuTree(); currentMenu = next; if ( down ) initCurrentMenu(); -// return -1; } -// else - { + return id; - } break; } default: break; } return -1; } -MenuOption *Menu :: addMenuOption( QString text, int id ) +MenuOption *Menu :: addMenuOption( string text, int id ) { MenuOption *item = new MenuOption( text, id ); listItems.push_back( item ); return item; diff --git a/noncore/games/sfcave-sdl/menu.h b/noncore/games/sfcave-sdl/menu.h index 08f7528..6a5ef40 100644 --- a/noncore/games/sfcave-sdl/menu.h +++ b/noncore/games/sfcave-sdl/menu.h @@ -10,25 +10,25 @@ class SFCave; class StarField; class Menu; class MenuOption { public: - MenuOption( QString text, int id ); + MenuOption( string text, int id ); ~MenuOption(); void highlight( bool val ) { highlighted = val; } int draw( SDL_Surface *screen, int y ); void setNextMenu( Menu *item, bool down = true ); Menu *getNextMenu() { return nextMenu; } int getMenuId() { return menuId; } bool isDownMenuTree() { return downMenuTree; } private: int menuId; - QString menuText; + string menuText; bool highlighted; bool downMenuTree; Menu *nextMenu; }; @@ -37,17 +37,17 @@ class Menu public: Menu( SFCave *p ); ~Menu(); void draw( SDL_Surface *screen ); int handleKeys( SDL_KeyboardEvent & ); - MenuOption *addMenuOption( QString text, int id ); + MenuOption *addMenuOption( string text, int id ); void resetToTopMenu(); void initCurrentMenu(); - void setStatusText( QString text ) { statusText = text; } + void setStatusText( string text ) { statusText = text; } protected: private: static SDL_Surface * sfcaveTextImage; int angle; @@ -55,13 +55,13 @@ private: static Menu *mainMenu; static Menu *currentMenu; Menu *parentMenu; StarField *stars; - QString statusText; + string statusText; SFCave *parent; list<MenuOption *> listItems; MenuOption *currentMenuOption; Menu( Menu* p ); diff --git a/noncore/games/sfcave-sdl/player.cpp b/noncore/games/sfcave-sdl/player.cpp index 830ee78..2d52ae2 100644 --- a/noncore/games/sfcave-sdl/player.cpp +++ b/noncore/games/sfcave-sdl/player.cpp @@ -8,14 +8,14 @@ Player :: Player( int w, int h ) { sWidth = w; sHeight = h; - thrustUp = 0.4; - thrustDown = 0.6; + thrust = 0.4; + gravity = 0.6; maxUpSpeed = 4.0; maxDownSpeed = 5.0; explosion = new AnimatedImage( IMAGES_PATH "explosion.bmp", 15 ); init(); } @@ -77,37 +77,34 @@ void Player :: drawTrails( SDL_Surface *screen ) return; for ( int i = 0 ; i < TRAILSIZE ; ++i ) { if ( trail[i].x() >= 0 ) { -// int r = (int) ((255.0/pos.x()) * (trail[i].x)); -// int g = (int) ((150.0/pos.x()) * (trail[i].x)); int c = (int)((150.0/50) * (50.0 - (pos.x() - trail[i].x() ) )); -// SDL_FillRect( screen, &trail[i], SDL_MapRGBA( screen->format, r, g, 0, 0 ) ); //(int)(1.5*c), 0, 255 ) ); boxRGBA( screen, trail[i].x(), trail[i].y(), trail[i].x() + 2, trail[i].y() + 2, 255, (int)(1.5*c), 0, c ); } } } void Player :: move( bool up ) { // Find enpty trail and move others moveTrails(); if ( up ) - thrust -= thrustUp; + currentThrust -= thrust; else - thrust += thrustDown; + currentThrust += gravity; - if ( thrust > maxDownSpeed ) - thrust = maxDownSpeed; - else if ( thrust < -maxUpSpeed ) - thrust = -maxUpSpeed; + if ( currentThrust > maxDownSpeed ) + currentThrust = maxDownSpeed; + else if ( currentThrust < -maxUpSpeed ) + currentThrust = -maxUpSpeed; - pos.moveBy( 0, (int)(thrust) ); + pos.moveBy( 0, (int)(currentThrust) ); } void Player :: moveTrails() { bool done = false; bool stillVisible = false; @@ -149,14 +146,139 @@ bool Player :: updateCrashing() else expNextFrame = true; return crashed; } -void Player :: setMovementInfo( double up, double down, double maxUp, double maxDown ) +void Player :: setMovementInfo( double up, double grav, double maxUp, double maxDown ) { - thrustUp = up; - thrustDown = down; + thrust = up; + gravity = grav; maxUpSpeed = maxUp; maxDownSpeed = maxDown; } + +void Player :: incValue( int valueType ) +{ + switch( valueType ) + { + case PLAYER_THRUST: + thrust += 0.1; + break; + case PLAYER_GRAVITY: + gravity += 0.1; + break; + case PLAYER_MAX_SPEED_UP: + maxUpSpeed += 0.1; + break; + case PLAYER_MAX_SPEED_DOWN: + maxDownSpeed += 0.1; + break; + } +} + +void Player :: decValue( int valueType ) +{ + switch( valueType ) + { + case PLAYER_THRUST: + thrust -= 0.1; + break; + case PLAYER_GRAVITY: + gravity -= 0.1; + break; + case PLAYER_MAX_SPEED_UP: + maxUpSpeed -= 0.1; + break; + case PLAYER_MAX_SPEED_DOWN: + maxDownSpeed -= 0.1; + break; + } +} + +void Player :: setValue( int valueType, double val ) +{ + switch( valueType ) + { + case PLAYER_THRUST: + thrust = val; + break; + case PLAYER_GRAVITY: + gravity = val; + break; + case PLAYER_MAX_SPEED_UP: + maxUpSpeed = val; + break; + case PLAYER_MAX_SPEED_DOWN: + maxDownSpeed = val; + break; + } +} + +double Player :: getValue( int valueType ) +{ + double val; + switch( valueType ) + { + case PLAYER_THRUST: + val = thrust; + break; + case PLAYER_GRAVITY: + val = gravity; + break; + case PLAYER_MAX_SPEED_UP: + val = maxUpSpeed; + break; + case PLAYER_MAX_SPEED_DOWN: + val = maxDownSpeed; + break; + } + + return val; +} + +string Player :: getValueTypeString( int valueType ) +{ + string val; + switch( valueType ) + { + case PLAYER_THRUST: + val = "thrust"; + break; + case PLAYER_GRAVITY: + val = "gravity"; + break; + case PLAYER_MAX_SPEED_UP: + val = "maxupspeed"; + break; + case PLAYER_MAX_SPEED_DOWN: + val = "maxdownspeed"; + break; + } + + return val; +} + +string Player :: getValueString( int valueType ) +{ + char val[50]; + switch( valueType ) + { + case PLAYER_THRUST: + sprintf( val, "Thrust - %lf", thrust ); + break; + case PLAYER_GRAVITY: + sprintf( val, "Gravity - %lf", gravity ); + break; + case PLAYER_MAX_SPEED_UP: + sprintf( val, "Max Speed Up - %lf", maxUpSpeed ); + break; + case PLAYER_MAX_SPEED_DOWN: + sprintf( val, "Max Speed Down - %lf", maxDownSpeed ); + break; + } + + string ret = val; + return ret; +} + diff --git a/noncore/games/sfcave-sdl/player.h b/noncore/games/sfcave-sdl/player.h index e4c904a..595c25b 100644 --- a/noncore/games/sfcave-sdl/player.h +++ b/noncore/games/sfcave-sdl/player.h @@ -19,13 +19,19 @@ public: void moveTrails(); Rect getPos() { return pos; } int getX() { return pos.x(); } int getY() { return pos.y(); } int getHeight() { return pos.h(); } bool updateCrashing(); - void setMovementInfo( double up, double down, double maxUp, double maxDown ); + void setMovementInfo( double up, double grav, double maxUp, double maxDown ); + void incValue( int valType ); + void decValue( int valType ); + double getValue( int valueType ); + string getValueString( int valueType ); + string getValueTypeString( int valueType ); + void setValue( int valueType, double val ); private: AnimatedImage *explosion; int sWidth; int sHeight; @@ -33,16 +39,16 @@ private: bool expNextFrame; bool allFaded; bool crashing; bool crashed; int crashLineLength; Rect pos; - double thrust; + double currentThrust; - double thrustUp; - double thrustDown; + double thrust; + double gravity; double maxUpSpeed; double maxDownSpeed; Rect trail[TRAILSIZE]; }; diff --git a/noncore/games/sfcave-sdl/settings.cpp b/noncore/games/sfcave-sdl/settings.cpp index 914c4ec..20cce4f 100644 --- a/noncore/games/sfcave-sdl/settings.cpp +++ b/noncore/games/sfcave-sdl/settings.cpp @@ -2,32 +2,27 @@ #include <stdlib.h> #include <sys/stat.h> #include <vector> #include "settings.h" +// Defined in util.h +string getHomeDir(); #define DEFAULT_DIR "." #define DEFAULT_FILE "Settings.cfg" #define MAX_LINE_SIZE 2048 Settings::Settings( char * env_file, char * env_dir ) { // Store the correct environment directory if (env_dir == NULL) { - char * homeDir = getenv( "HOME" );; - - if ( homeDir ) - { - envFile.append(homeDir); + envFile = getHomeDir(); envFile.append("/"); - } - else - printf( "Environment var HOME not set!\n" ); envFile.append(DEFAULT_DIR); } else envFile.append(env_dir); @@ -39,21 +34,14 @@ Settings::Settings( char * env_file, char * env_dir ) else envFile.append(env_file); } Settings::Settings() { - char * homeDir = getenv("HOME"); - - if ( homeDir) - { - envFile.append(homeDir); + envFile = getHomeDir(); envFile.append("/"); - } - else - printf( "Environment var HOME not set!\n" ); envFile.append(DEFAULT_DIR); envFile.append("/"); envFile.append(DEFAULT_FILE); } @@ -107,12 +95,24 @@ bool Settings::readSetting(const string key_str,unsigned long& result) return true; } else return false; } +bool Settings::readSetting(const string key_str,double& result) +{ + string Buffer; + if (readSetting(key_str,Buffer)) + { + result = atof( Buffer.c_str() ); + return true; + } + else + return false; +} + bool Settings::readSetting(const string key_str,bool& result) { string Buffer; if (readSetting(key_str,Buffer)) { result = (Buffer == "true"); @@ -156,12 +156,20 @@ bool Settings::readSetting(const string key_str,string& results) void Settings::writeSetting(const string key_str,const bool value) { value ? writeSetting(key_str,string("true")) :writeSetting(key_str,string("false")); } +void Settings::writeSetting(const string key_str,const double value) +{ + char Buffer[30]; + + sprintf(Buffer,"%lf",value); + writeSetting(key_str,string(Buffer)); +} + void Settings::writeSetting(const string key_str,const int value) { char Buffer[30]; sprintf(Buffer,"%i",value); writeSetting(key_str,string(Buffer)); @@ -192,47 +200,40 @@ void Settings::writeSetting(const string key_str,const unsigned long value) } void Settings::writeSetting(const string key_str,const string value) { // This function will write a value for the key key_str. If the key_str // already exists then it will be overwritten. - - std::vector<string> FileEntries; FILE *fd=NULL,*ftemp=NULL; - char * dir_str; - char * dir_ptr; char buf[MAX_LINE_SIZE]; - char tempname[12]; - - dir_str = strdup(envFile.c_str()); - printf( "dir = %s, file - %s\n", dir_str, envFile.c_str() ); - if (dir_str) - { - // remove file from the directory string - dir_ptr = strrchr(dir_str, (int)'/'); - if (dir_ptr) - { - *dir_ptr = 0; - // make the directory path if it does not exist -// mkdir(dir_str, 777 ); + string tmp = getHomeDir() + "/tmpsfcave.dat"; // if file exists we need to save contents - if ((fd = fopen(envFile.c_str(), "r")) != NULL) + fd = fopen( envFile.c_str(), "r" ); + ftemp = fopen( tmp.c_str(), "w" ); + if ( fd != NULL && ftemp != NULL ) { while (fgets(buf, MAX_LINE_SIZE-1, fd)) - FileEntries.push_back(string(buf)); + { + if ( strncmp( buf, key_str.c_str(), key_str.size() ) != 0 ) + fprintf( ftemp, "%s", buf ); + } fclose(fd); } - char *home = getenv( "HOME" ); - string tmp; - if ( home ) - tmp = home + string( "/" ) + "tmpsfcave.dat"; - else - tmp = "./tmpsfcave.dat"; + if ( ftemp != NULL ) + { + fprintf(ftemp, "%s\t%s\n", key_str.c_str(),value.c_str()); + fclose( ftemp ); + + remove(envFile.c_str()); + rename( tmp.c_str(), envFile.c_str() ); + } +/* + string tmp = getHomeDir() + "/tmpsfcave.dat"; strcpy(tempname,tmp.c_str() ); printf( "tmp - %s\n", tempname ); if ((ftemp = fopen(tempname,"w")) != NULL) { char *key1,*key2; char buff1[80],buff2[80]; @@ -251,23 +252,20 @@ void Settings::writeSetting(const string key_str,const string value) } } fprintf(ftemp, "%s\t%s\n", key_str.c_str(),value.c_str()); fflush(ftemp); fclose(ftemp); - - remove(envFile.c_str()); - - rename( tempname, envFile.c_str() ); } else printf( "Can't open file %s\n", envFile.c_str() ); } delete dir_str; } +*/ } void Settings::deleteFile(void) { remove(envFile.c_str()); } diff --git a/noncore/games/sfcave-sdl/settings.h b/noncore/games/sfcave-sdl/settings.h index 5e828ed..a3af999 100644 --- a/noncore/games/sfcave-sdl/settings.h +++ b/noncore/games/sfcave-sdl/settings.h @@ -29,19 +29,21 @@ public: bool readSetting(const string key_str,string& results); bool readSetting(const string key_str,int& result); bool readSetting(const string key_str,unsigned int& result); bool readSetting(const string key_str,long int& result); bool readSetting(const string key_str,unsigned long& result); + bool readSetting(const string key_str,double & result); bool readSetting(const string key_str,bool& result); void writeSetting(const string key_str,const string value); void writeSetting(const string key_str,const int value); void writeSetting(const string key_str,const unsigned int result); void writeSetting(const string key_str,const long int result); void writeSetting(const string key_str,const unsigned long result); + void writeSetting(const string key_str,const double value); void writeSetting(const string key_str,const bool value); void deleteFile(void); private: diff --git a/noncore/games/sfcave-sdl/sfcave.cpp b/noncore/games/sfcave-sdl/sfcave.cpp index 8d376a1..dbd788c 100644 --- a/noncore/games/sfcave-sdl/sfcave.cpp +++ b/noncore/games/sfcave-sdl/sfcave.cpp @@ -23,15 +23,15 @@ #include "sfcave_game.h" #include "gates_game.h" #include "fly_game.h" void start( int argc, char *argv[] ) { - FontHandler::init(); - SFCave app( argc, argv ); - FontHandler::cleanUp(); + SFCave *app = new SFCave( argc, argv ); + app->mainEventLoop(); + delete app; } #ifdef __cplusplus extern "C" #endif int main(int argc, char *argv[]) @@ -40,234 +40,232 @@ int main(int argc, char *argv[]) return 0; } SFCave :: SFCave( int argc, char *argv[] ) { + setupOK = false; + + // Load settings string diff = loadSetting( "GameDifficulty", "Easy" ); string game = loadSetting( "GameType", "SFCave" ); musicPath = loadSetting( "MusicPath", SOUND_PATH ); - printf( "musicPath %s\n", musicPath.c_str() ); musicType = loadSetting( "MusicType", "mod,ogg" ); + bool soundOn = loadBoolSetting( "SoundOn", true ); + bool musicOn = loadBoolSetting( "MusicOn", true ); if ( musicPath[musicPath.size()-1] != '/' ) musicPath += "/"; + printf( "musicPath %s\n", musicPath.c_str() ); // Init main SDL Library initSDL( argc, argv ); + // Init font handler + if ( !FontHandler::init() ) + { + printf( "Unable to initialise fonts!\n" ); + return; + } + // Init SoundHandler if ( !SoundHandler :: init() ) printf("Unable to open audio!\n"); + SoundHandler :: setSoundsOn( soundOn ); + SoundHandler :: setMusicOn( musicOn ); + currentGame = Game::createGame( this, WIDTH, HEIGHT, game, diff ); if ( !currentGame ) currentGame = new SFCaveGame( this, WIDTH, HEIGHT, 0 ); currentGame->setSeed(-1); + + // Create menu menu = new Menu( this ); + // Create help screen help = new Help( this ); maxFPS = 50; showFps = false; - mainEventLoop(); - SoundHandler :: cleanUp(); - SDL_Quit(); + setupOK = true; } SFCave :: ~SFCave() { if ( currentGame ) delete currentGame; if ( menu ) delete menu; - SDL_FreeSurface( screen ); -} - + if ( help ) + delete help; -void SFCave :: drawGameScreen( ) -{ - //ClearScreen(screen, "Titletext"); + SDL_FreeSurface( screen ); + FontHandler::cleanUp(); + SoundHandler :: cleanUp(); + SDL_Quit(); } + void SFCave :: initSDL( int argc, char *argv[] ) { const SDL_VideoInfo *info; Uint8 video_bpp; Uint32 videoflags; - - - /* Initialize SDL */ + // Initialize SDL if ( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError()); exit(1); } - atexit(SDL_Quit); - /* Alpha blending doesn't work well at 8-bit color */ video_bpp = 16; - if ( !SDL_VideoModeOK(WIDTH, HEIGHT, 16, SDL_DOUBLEBUF) ) + if ( !SDL_VideoModeOK(WIDTH, HEIGHT, video_bpp, SDL_DOUBLEBUF) ) printf( "No double buffering\n" ); - videoflags = SDL_HWSURFACE | SDL_SRCALPHA;//|| SDL_DOUBLEBUF;// | SDL_SRCALPHA | SDL_RESIZABLE; - while ( argc > 1 ) { + videoflags = SDL_HWSURFACE | SDL_SRCALPHA; + while ( argc > 1 ) + { --argc; - if ( strcmp(argv[argc-1], "-bpp") == 0 ) { + if ( strcmp(argv[argc-1], "-bpp") == 0 ) + { video_bpp = atoi(argv[argc]); --argc; - } else - if ( strcmp(argv[argc], "-hw") == 0 ) { + } + else if ( strcmp(argv[argc], "-hw") == 0 ) + { videoflags |= SDL_HWSURFACE; - } else - if ( strcmp(argv[argc], "-warp") == 0 ) { + } + else if ( strcmp(argv[argc], "-warp") == 0 ) + { videoflags |= SDL_HWPALETTE; - } else - if ( strcmp(argv[argc], "-fullscreen") == 0 ) { + } + else if ( strcmp(argv[argc], "-fullscreen") == 0 ) + { videoflags |= SDL_FULLSCREEN; - } else { + } + else if ( strcmp(argv[argc], "-h") == 0 ) + { fprintf(stderr, "Usage: %s [-bpp N] [-warp] [-hw] [-fullscreen]\n", argv[0]); exit(1); } } - /* Set 240x320 video mode */ - if ( (screen=SDL_SetVideoMode(WIDTH,HEIGHT,video_bpp,videoflags)) == NULL ) { - fprintf(stderr, "Couldn't set %ix%i video mode: %s\n",WIDTH,HEIGHT,SDL_GetError()); + // Set 240x320 video mode + if ( (screen = SDL_SetVideoMode( WIDTH,HEIGHT,video_bpp,videoflags )) == NULL ) + { + printf( "Couldn't set %ix%i video mode: %s\n",WIDTH,HEIGHT,SDL_GetError() ); exit(2); } - /* Use alpha blending */ - SDL_SetAlpha(screen, SDL_RLEACCEL, 0); + // Use alpha blending + //SDL_SetAlpha(screen, SDL_RLEACCEL, 0); - /* Set title for window */ + // Set title for window SDL_WM_SetCaption("SFCave","SFCave"); } void SFCave :: mainEventLoop() { - SDL_Event event; - int done; + if ( !setupOK ) + return; - /* Wait for a keystroke */ - done = 0; + // Wait for a keystroke + finish = false; state = 0; state = STATE_CRASHED; changeState( STATE_MENU ); - int FPS = 0; - bool limitFPS = true; + FPS = 0; actualFPS = 0; - long time1 = 0; - long start; - long end; -// long nrTimes = 0; - struct timeb tp; - while ( !done ) + time1 = 0; + + limitFPS = true; + while ( !finish ) { // calc FPS - ftime( &tp ); - start =(tp.time%10000)*10000 + tp.millitm; -// printf( "start = %ld, time1 - %d, st-tm - %d, tp.time - %ld\n", start, time1, start-time1, (tp.time%1000)*1000 ); - if ( start - time1 >= 1000 ) - { - actualFPS = FPS; -// printf( "%d FPS = %d\n", nrTimes++, actualFPS ); - FPS = 0; - time1 = start; - } - else - FPS ++; + calcFPS(); SDL_FillRect( screen, 0, 0 ); + + handleGameState( ); + + SDL_Flip( screen ); + + if ( limitFPS ) + FPSDelay(); + else + SDL_Delay( 5 ); + + handleEvents(); + } +} + + +void SFCave :: handleGameState() +{ switch( state ) { case STATE_MENU: SDL_FillRect( screen, 0, 0 ); menu->draw( screen ); break; case STATE_HELP: SDL_FillRect( screen, 0, 0 ); help->update(); help->draw( screen ); break; case STATE_NEWGAME: - printf( "STATE_NEWGAME\n" ); currentGame->setReplay( false ); currentGame->init(); changeState( STATE_PLAYING ); break; case STATE_REPLAY: - printf( "STATE_NEWGAME\n" ); currentGame->setReplay( true ); currentGame->init(); changeState( STATE_PLAYING ); break; case STATE_PLAYING: case STATE_CRASHING: - currentGame->update( state ); - currentGame->draw( screen ); - break; - case STATE_CRASHED: currentGame->update( state ); currentGame->draw( screen ); - - // Display Game Over message break; case STATE_QUIT: - done = 1; + finish = true; break; } +} - /* Show */ -// if ( state != STATE_CRASHED ) - SDL_Flip( screen ); -// SDL_UpdateRect(screen, 0, 0, 0, 0); - - if ( limitFPS ) +void SFCave :: handleEvents() { - /* Slow down polling - limit to x FPS*/ - ftime( &tp ); - end = abs((tp.time%10000)*10000 + tp.millitm); - if ( end-start < (1000/maxFPS) ) - { -// printf( "end - %ld, timetaken for frame = %ld, sleeping for %ld %d\n", end, end-start, (1000/maxFPS)-(end-start), actualFPS ); - if ( (1000/maxFPS)-(end-start) > 500 ) - { - // Should never happen but in case it does sleep for 5 seconds - printf( "WARNING WILL ROBINSON! delay = %ld - start %ld, end %ld\n", (1000/maxFPS)-(end-start), start, end ); - SDL_Delay( 5 ); - } - else - SDL_Delay((1000/maxFPS)-(end-start) ); - } - } - else - SDL_Delay( 5 ); + SDL_Event event; - /* Check for events */ + // Check for events while ( SDL_PollEvent(&event) ) { switch (event.type) { case SDL_KEYDOWN: case SDL_KEYUP: + { // Escape keypress quits the app - if ( event.key.keysym.sym != SDLK_ESCAPE ) + if ( event.key.keysym.sym == SDLK_ESCAPE ) { -// printf( "Key Pressed was %d %s\n", event.key.keysym.sym, SDL_GetKeyName( event.key.keysym.sym ) ); + finish = true; + break; + } if ( state == STATE_MENU ) { int rc = menu->handleKeys( event.key ); if ( rc != -1 ) handleMenuSelect( rc ); @@ -301,60 +299,37 @@ void SFCave :: mainEventLoop() } else { switch ( event.key.keysym.sym ) { case SDLK_f: - printf( "showFPS - %d\n", showFps ); if ( event.type == SDL_KEYDOWN ) showFps = !showFps; break; case SDLK_l: if ( event.type == SDL_KEYDOWN ) limitFPS = !limitFPS; break; - case SDLK_p: - if ( event.type == SDL_KEYDOWN ) - { - maxFPS ++; - printf( "maxFPS - %d\n", maxFPS ); - } - break; - - case SDLK_o: - if ( event.type == SDL_KEYDOWN ) - { - maxFPS --; - printf( "maxFPS - %d\n", maxFPS ); - } - break; - - case SDLK_n: - currentGame->getTerrain()->offset++; - break; - default: currentGame->handleKeys( event.key ); break; } } break; } - case SDL_QUIT: - done = 1; + finish = true; break; default: break; } } } -} void SFCave :: changeState( int s ) { if ( state != s ) currentGame->stateChanged( state, s ); @@ -362,22 +337,21 @@ void SFCave :: changeState( int s ) help->init(); if ( state == STATE_CRASHED && s == STATE_MENU ) { SoundHandler :: stopMusic( true ); string musicFile = chooseRandomFile( musicPath, musicType ); - printf("playing music %s\n", musicFile.c_str() ); SoundHandler :: setMusicVolume( 128 ); SoundHandler :: playMusic( musicFile ); } else if ( state == STATE_MENU && (s == STATE_NEWGAME || s == STATE_REPLAY) ) { SoundHandler :: stopMusic( ); // Start the in game music - string musicFile = SOUND_PATH "ingame.mod"; + string musicFile = INGAME_MUSIC; SoundHandler :: playMusic( musicFile ); SoundHandler :: setMusicVolume( 25 ); } state = s; } @@ -405,35 +379,25 @@ void SFCave :: handleMenuSelect( int menuId ) else setMenuStatusText( "No replay available yet" ); break; case MENU_LOAD_REPLAY: { -#ifdef QWS - QString replayFile = getenv( "HOME" ); -#else - QString replayFile = "."; -#endif - replayFile += string( "/" ) + currentGame->getGameName() + ".replay"; + string replayFile = getHomeDir() + "/" + currentGame->getGameName() + ".replay"; currentGame->loadReplay( replayFile ); break; } case MENU_SAVE_REPLAY: { if ( currentGame->isReplayAvailable() ) { -#ifdef QWS - QString replayFile = getenv( "HOME" ); -#else - QString replayFile = "."; -#endif - replayFile += string( "/" ) + currentGame->getGameName() + ".replay"; + string replayFile = getHomeDir() + "/" + currentGame->getGameName() + ".replay"; currentGame->saveReplay( replayFile ); } else setMenuStatusText( "No replay available yet" ); @@ -491,26 +455,75 @@ void SFCave :: handleMenuSelect( int menuId ) case MENU_DIFFICULTY_HARD: currentGame->setDifficulty( MENU_DIFFICULTY_HARD ); saveSetting( "GameDifficulty", "Hard" ); break; + case MENU_DIFFICULTY_CUSTOM: + currentGame->setDifficulty( MENU_DIFFICULTY_CUSTOM ); + saveSetting( "GameDifficulty", "Custom" ); + break; + case MENU_SOUND_ON: SoundHandler :: setSoundsOn( true ); + saveSetting( "SoundOn", "true" ); break; case MENU_SOUND_OFF: SoundHandler :: setSoundsOn( false ); + saveSetting( "SoundOn", "false" ); break; case MENU_MUSIC_ON: SoundHandler :: setMusicOn( true ); + saveSetting( "MusicOn", "true" ); break; case MENU_MUSIC_OFF: SoundHandler :: setMusicOn( false ); + saveSetting( "MusicOn", "false" ); + break; + + case MENU_CUSTOM_THRUST: + customPlayerMenuVal = PLAYER_THRUST; + origValue = currentGame->getPlayer()->getValue( customPlayerMenuVal ); + setMenuStatusText( currentGame->getPlayer()->getValueString( customPlayerMenuVal ) ); + break; + case MENU_CUSTOM_GRAVITY: + customPlayerMenuVal = PLAYER_GRAVITY; + origValue = currentGame->getPlayer()->getValue( customPlayerMenuVal ); + setMenuStatusText( currentGame->getPlayer()->getValueString( customPlayerMenuVal ) ); + break; + case MENU_CUSTOM_MAXSPEEDUP: + customPlayerMenuVal = PLAYER_MAX_SPEED_UP; + origValue = currentGame->getPlayer()->getValue( customPlayerMenuVal ); + setMenuStatusText( currentGame->getPlayer()->getValueString( customPlayerMenuVal ) ); + break; + case MENU_CUSTOM_MAXSPEEDDOWN: + customPlayerMenuVal = PLAYER_MAX_SPEED_DOWN; + origValue = currentGame->getPlayer()->getValue( customPlayerMenuVal ); + setMenuStatusText( currentGame->getPlayer()->getValueString( customPlayerMenuVal ) ); + break; + case MENU_CUSTOM_INCREASE: + currentGame->getPlayer()->incValue( customPlayerMenuVal ); + setMenuStatusText( currentGame->getPlayer()->getValueString( customPlayerMenuVal ) ); + break; + case MENU_CUSTOM_DECREASE: + currentGame->getPlayer()->decValue( customPlayerMenuVal ); + setMenuStatusText( currentGame->getPlayer()->getValueString( customPlayerMenuVal ) ); + break; + case MENU_CUSTOM_SAVE: + { + // save settings + string key = currentGame->getGameName() + "_custom_player_" + currentGame->getPlayer()->getValueTypeString( customPlayerMenuVal ); + saveSetting( key, currentGame->getPlayer()->getValue( customPlayerMenuVal ) ); + + break; + } + case MENU_CUSTOM_CANCEL: + currentGame->getPlayer()->setValue( customPlayerMenuVal, origValue ); break; default: break; } } @@ -530,17 +543,91 @@ void SFCave :: saveSetting( string key, string val ) void SFCave :: saveSetting( string key, int val ) { Settings cfg( "sfcave-sdl" ); cfg.writeSetting( key, val ); } +void SFCave :: saveSetting( string key, long val ) +{ + Settings cfg( "sfcave-sdl" ); + cfg.writeSetting( key, val ); +} + +void SFCave :: saveSetting( string key, double val ) +{ + Settings cfg( "sfcave-sdl" ); + cfg.writeSetting( key, val ); +} + string SFCave :: loadSetting( string key, string defaultVal ) { string val; Settings cfg( "sfcave-sdl" ); cfg.readSetting( key, val ); if ( val == "" ) val = defaultVal; return val; } + +bool SFCave :: loadBoolSetting( string key, bool defaultVal ) +{ + bool val = defaultVal; + Settings cfg( "sfcave-sdl" ); + cfg.readSetting( key, val ); + + return val; +} + +int SFCave :: loadIntSetting( string key, int defaultVal ) +{ + int val = defaultVal; + Settings cfg( "sfcave-sdl" ); + cfg.readSetting( key, val ); + + return val; +} + +double SFCave :: loadDoubleSetting( string key, double defaultVal ) +{ + double val = defaultVal; + Settings cfg( "sfcave-sdl" ); + cfg.readSetting( key, val ); + + return val; +} + + +void SFCave :: calcFPS() +{ + struct timeb tp; + ftime( &tp ); + start =(tp.time%10000)*10000 + tp.millitm; + if ( start - time1 >= 1000 ) + { + actualFPS = FPS; + FPS = 0; + time1 = start; + } + else + FPS ++; +} + +void SFCave :: FPSDelay() +{ + struct timeb tp; + // Slow down polling - limit to x FPS + ftime( &tp ); + end = abs((tp.time%10000)*10000 + tp.millitm); + if ( end-start < (1000/maxFPS) ) + { + if ( (1000/maxFPS)-(end-start) > 500 ) + { + // Should never happen but in case it does sleep for 5 seconds + printf( "WARNING WILL ROBINSON! delay = %ld - start %ld, end %ld\n", (1000/maxFPS)-(end-start), start, end ); + SDL_Delay( 5 ); + } + else + SDL_Delay((1000/maxFPS)-(end-start) ); + } +} diff --git a/noncore/games/sfcave-sdl/sfcave.h b/noncore/games/sfcave-sdl/sfcave.h index 96c2334..c707919 100644 --- a/noncore/games/sfcave-sdl/sfcave.h +++ b/noncore/games/sfcave-sdl/sfcave.h @@ -12,13 +12,12 @@ class Help; class SFCave { public: SFCave( int argc, char *argv[] ); ~SFCave(); - void drawGameScreen(); void initSDL( int argc, char *argv[] ); void mainEventLoop(); void setCrashed( bool val ); void changeState( int s ); int getState() { return state; } @@ -27,24 +26,47 @@ public: bool showFPS() { return showFps; } void setMenuStatusText( string statusText ); void saveSetting( string key, string val ); void saveSetting( string key, int val ); + void saveSetting( string key, long val ); + void saveSetting( string key, double val ); string loadSetting( string key, string defaultVal = "" ); + bool loadBoolSetting( string key, bool defaultVal); + int loadIntSetting( string key, int defaultVal ); + double loadDoubleSetting( string key, double defaultVal ); + private: SDL_Surface *screen; + bool setupOK; Game *currentGame; Menu *menu; Help *help; int state; - int maxFPS; - int actualFPS; bool showFps; string musicPath; string musicType; + bool finish; + + bool limitFPS; + int maxFPS; + int actualFPS; + int FPS; + long time1; + long start; + long end; + + // This is used when the user is setting the custom + // values in the menu + int customPlayerMenuVal; + double origValue; void handleMenuSelect( int menuId ); + void handleGameState(); + void handleEvents(); + void calcFPS(); + void FPSDelay(); }; #endif diff --git a/noncore/games/sfcave-sdl/sfcave_game.cpp b/noncore/games/sfcave-sdl/sfcave_game.cpp index 72c5ce3..1b00e14 100644 --- a/noncore/games/sfcave-sdl/sfcave_game.cpp +++ b/noncore/games/sfcave-sdl/sfcave_game.cpp @@ -36,12 +36,25 @@ void SFCaveGame :: init() case MENU_DIFFICULTY_NORMAL: blockDistance = 40; break; case MENU_DIFFICULTY_HARD: blockDistance = 30; break; + case MENU_DIFFICULTY_CUSTOM: + { + // Read custom difficulty settings for this game + blockDistance = parent->loadIntSetting( "SFCave_custom_blockdistance", 50 ); + + double thrust = parent->loadDoubleSetting( "SFCave_custom_player_thrust", 0.4 ); + double gravity = parent->loadDoubleSetting( "SFCave_custom_player_gravity", 0.6 ); + double maxUp = parent->loadDoubleSetting( "SFCave_custom_player_maxupspeed", 4.0 ); + double maxDown = parent->loadDoubleSetting( "SFCave_custom_player_maxdownspeed", 5.0 ); + player->setMovementInfo( thrust, gravity, maxUp, maxDown ); + + break; + } } for ( int i = 0 ; i < BLOCKSIZE ; ++i ) blocks[i].y( -1 ); } @@ -65,13 +78,12 @@ void SFCaveGame :: update( int state ) blockHeight -= 5; } } if ( checkCollisions() ) { -// printf( "Crashed!\n" ); parent->changeState( STATE_CRASHING ); return; } if ( nrFrames % blockDistance == 0 ) addBlock(); diff --git a/noncore/games/sfcave-sdl/sound.cpp b/noncore/games/sfcave-sdl/sound.cpp index 5fda859..855f2e6 100644 --- a/noncore/games/sfcave-sdl/sound.cpp +++ b/noncore/games/sfcave-sdl/sound.cpp @@ -28,20 +28,23 @@ bool SoundHandler :: init( ) sounds[SND_EXPLOSION] = Mix_LoadWAV( SOUND_PATH "explosion.wav");
sounds[SND_THRUST] = Mix_LoadWAV( SOUND_PATH "thrust.wav");
music = 0;
soundOn = true;
+ musicOn = true;
return true;
}
void SoundHandler :: cleanUp()
{
// Free audio sounds
+ if ( sounds[SND_EXPLOSION] )
Mix_FreeChunk( sounds[SND_EXPLOSION] );
+ if ( sounds[SND_THRUST] )
Mix_FreeChunk( sounds[SND_THRUST] );
if ( music )
Mix_FreeMusic( music );
Mix_CloseAudio();
@@ -49,13 +52,13 @@ void SoundHandler :: cleanUp() int SoundHandler :: playSound( int soundNr, int channel, int nrLoops, int playBeforeFinished )
{
if ( !soundOn )
return -1;
- if ( soundNr >= NR_SOUNDS )
+ if ( soundNr >= NR_SOUNDS || !sounds[soundNr] )
return -1;
Mix_Chunk *chunk = sounds[soundNr];
if( channel == -1 || !Mix_Playing( channel ) )
channel = Mix_PlayChannel(-1, sounds[soundNr], nrLoops);
@@ -98,13 +101,13 @@ void SoundHandler :: playMusic( string musicFile ) playMusic();
}
void SoundHandler :: playMusic( bool fade )
{
- if ( !soundOn )
+ if ( !musicOn )
return;
if ( music )
{
Mix_VolumeMusic( MIX_MAX_VOLUME );
Mix_RewindMusic();
diff --git a/noncore/games/sfcave-sdl/starfield.cpp b/noncore/games/sfcave-sdl/starfield.cpp index c1f2d73..82edfc1 100644 --- a/noncore/games/sfcave-sdl/starfield.cpp +++ b/noncore/games/sfcave-sdl/starfield.cpp @@ -218,6 +218,78 @@ void StarField :: draw( SDL_Surface *screen, int w, int h ) //*** NOTE : if the velocity of the stars never changes then the values such as 'pos_x[i] + vel_x[i]' could be precalculated for each star ***
}
SDL_UnlockSurface( screen );
}
}
+
+
+
+// Test
+#ifdef DEBUG_STARS
+SDL_Surface *screen;
+StarField *stars;
+
+void go()
+{
+ /* Initialize SDL */
+ if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
+ {
+ fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
+ exit(1);
+ }
+ atexit(SDL_Quit);
+
+ int videoflags = SDL_SWSURFACE ;
+
+ if ( (screen=SDL_SetVideoMode(240, 320,32,videoflags)) == NULL )
+ {
+ fprintf(stderr, "Couldn't set %ix%i video mode: %s\n",240,320,SDL_GetError());
+ exit(2);
+ }
+
+ stars = new StarField( false, 200 );
+
+ bool done = false;
+ while ( !done )
+ {
+ SDL_FillRect( screen, 0, 0 );
+ stars->draw( screen );
+ stars->move( );
+
+ SDL_Flip( screen );
+
+ SDL_Delay( 10 );
+
+ SDL_Event event;
+ while ( SDL_PollEvent(&event) )
+ {
+ switch (event.type)
+ {
+ case SDL_KEYDOWN:
+ // Escape keypress quits the app
+ if ( event.key.keysym.sym != SDLK_ESCAPE )
+ {
+ break;
+ }
+ case SDL_QUIT:
+ done = 1;
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+
+#ifdef __cplusplus
+extern "C"
+#endif
+int main( int argc, char *argv[] )
+{
+ go();
+}
+
+#endif
diff --git a/noncore/games/sfcave-sdl/terrain.cpp b/noncore/games/sfcave-sdl/terrain.cpp index c001a56..b243f45 100644 --- a/noncore/games/sfcave-sdl/terrain.cpp +++ b/noncore/games/sfcave-sdl/terrain.cpp @@ -44,12 +44,13 @@ void Terrain :: initTerrain() mapTop[0] = (int)(nextInt(50)) + 5; mapBottom[0] = sHeight - (maxHeight - mapTop[0]); for ( int i = 1 ; i < MAPSIZE ; ++i ) setPoint( i ); SDL_FillRect( terrainSurface, 0, 0 ); + // Draw Terrain into surface Sint16 px[5]; Sint16 py[5]; for ( int i = 0 ; i < MAPSIZE ; ++i ) { @@ -88,13 +89,12 @@ void Terrain :: moveTerrain( int amountToMove ) { stars->move(); offset += amountToMove; speed = offset/segSize; -// printf( "offset - %d, speed - %d\n", offset, speed ); if ( offset >= segSize ) { for ( int i = 0 ; i < (MAPSIZE)-speed ; ++i ) { mapTop[i] = mapTop[i+speed]; mapBottom[i] = mapBottom[i+speed]; @@ -192,43 +192,27 @@ void Terrain :: drawTerrain( SDL_Surface *screen ) SDL_Rect dst; dst.x = offset; dst.y = 0; dst.w = sWidth; dst.h = sHeight; -// dst.h = maxHeight; SDL_Rect dst2; dst2.x = 0; dst2.y = 0; SDL_BlitSurface(terrainSurface, &dst, screen, &dst2 ); stars->draw( screen ); - -// dst.y = sHeight - maxHeight; -// dst2.y = sHeight - maxHeight; -// SDL_BlitSurface(terrainSurface, &dst, screen, &dst2 ); - -/* - for ( int i = 0 ; i < MAPSIZE ; ++i ) - { - int x1 = (i*segSize) - (offset*speed); - int x2 = ((i+1)*segSize)-(offset*speed); - if ( x2 >= sWidth ) - x2 = sWidth-1; - aalineRGBA( screen, x1, mapTop[i], x2, mapTop[i+1], 0, 220, 0, 255 ); - aalineRGBA( screen, x1, mapBottom[i], x2, mapBottom[i+1], 0, 220, 0, 255 ); - } -*/ } bool Terrain :: checkCollision( int x, int y, int h ) { if ( y < 0 || y > sHeight ) return true; + // First get segment that matches x SDL_LockSurface( terrainSurface ); Uint32 c = getpixel( terrainSurface, x, y ); SDL_UnlockSurface( terrainSurface ); @@ -244,13 +228,13 @@ bool Terrain :: checkCollision( int x, int y, int h ) #ifdef DEBUG_TERRAIN SDL_Surface *screen; Terrain *terrain; void go() { - /* Initialize SDL */ + // Initialize SDL if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError()); exit(1); } atexit(SDL_Quit); diff --git a/noncore/games/sfcave-sdl/util.cpp b/noncore/games/sfcave-sdl/util.cpp index 86738ad..f73e256 100644 --- a/noncore/games/sfcave-sdl/util.cpp +++ b/noncore/games/sfcave-sdl/util.cpp @@ -32,13 +32,13 @@ Uint32 getpixel(SDL_Surface *surface, int x, int y) default:
return 0; /* shouldn't happen, but avoids warnings */
}
}
-const char *chooseRandomFile( string path, string fileType )
+string chooseRandomFile( string path, string fileType )
{
vector<string> files;
DIR *d = opendir( path.c_str() );
if ( !d )
return "";
@@ -47,18 +47,29 @@ const char *chooseRandomFile( string path, string fileType ) {
string file = string( path ) + item->d_name;
// Rip extension from file
int pos = file.find( ".", 1 ) + 1;
string tmp = file.substr( pos );
- printf( "pos = %d, tmp =%s\n", pos, tmp.c_str() );
if ( tmp.size() > 0 && fileType.find( tmp ) != -1 )
{
- printf( "Matching <%s> - %s with <%s>\n", file.substr( pos ).c_str(), file.c_str(), fileType.c_str() );
files.push_back( file );
}
item = readdir( d );
}
closedir( d );
- return files[nextInt( files.size() )].c_str();
+ return files[nextInt( files.size() )];
+}
+
+
+string getHomeDir()
+{
+ string home;
+#ifdef QWS
+ home = getenv( "HOME" );
+#else
+ home = ".";
+#endif
+
+ return home;
}
diff --git a/noncore/games/sfcave-sdl/util.h b/noncore/games/sfcave-sdl/util.h index fe3e9c0..e3aa31a 100644 --- a/noncore/games/sfcave-sdl/util.h +++ b/noncore/games/sfcave-sdl/util.h @@ -2,9 +2,9 @@ #define __UTIL_H
#include <string>
using namespace std;
Uint32 getpixel(SDL_Surface *surface, int x, int y);
-const char *chooseRandomFile( string path, string fileType );
-
+string chooseRandomFile( string path, string fileType );
+string getHomeDir();
#endif
|