diff --git a/source/code/BlockGame.cpp b/source/code/BlockGame.cpp index 3148b22..ba1c2af 100644 --- a/source/code/BlockGame.cpp +++ b/source/code/BlockGame.cpp @@ -1,27 +1,26 @@ /* - * BlockGame.cpp (this was cut from main.cpp for the overview) - * Copyright (C) 2005 Poul Sander - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * Poul Sander - * R�veh�jvej 36, V. 1111 - * 2800 Kgs. Lyngby - * DENMARK - * blockattack@poulsander.com - */ +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== +*/ + #include "BlockGame.hpp" @@ -29,1972 +28,2190 @@ //////////////////////////////////////////////////////////////////////////////// //The BloackGame class represents a board, score, time etc. for a single player/ //////////////////////////////////////////////////////////////////////////////// - Uint16 BlockGame::rand2() { - nextRandomNumber = nextRandomNumber*1103515245 + 12345; - return ((Uint16)(nextRandomNumber/65536)) % 32768; - } - - int BlockGame::firstUnusedChain() { - bool found=false; - int i = 0; - while (!found) { - if (!chainUsed[++i]) - found=true; - if (i>NUMBEROFCHAINS-2) - found=true; - } - return i; - } - - //Constructor - BlockGame::BlockGame() { - srand((int)time(NULL)); - nrFellDown = 0; - nrPushedPixel = 0; - garbageTarget = this; - nrStops=0; - //topx = tx; - //topy = ty; - cursorx = 2; - cursory = 3; - stop = 0; - pixels = 0; - score = 0; - bGameOver = false; - bDraw = false; - bReplaying=false; //No replay by default - #if NETWORK - bDisconnected=false; - bNetworkPlayer = false; - #endif - timetrial = false; - stageClear = false; - vsMode = false; - puzzleMode = false; - linesCleared = 0; - AI_Enabled = false; - AI_MoveSpeed=100; - hasWonTheGame = false; - combo=0; //counts - chain=0; - hangTicks = 0; - baseSpeed = 0.5; //All other speeds are relative to this - speed = baseSpeed; - speedLevel = 1; - ticks = 0; - gameStartedAt = ticks; - gameEndedAfter = 0; - pushedPixelAt = gameStartedAt; - nextGarbageNumber = 10; - handicap=0; - for (int i=0;i<7;i++) - for (int j=0;j<30;j++) { - board[i][j] = -1; - } - for (int i=0;iNUMBEROFCHAINS-2) + found=true; + } + return i; +} + +//Constructor +BlockGame::BlockGame() +{ + srand((int)time(NULL)); + nrFellDown = 0; + nrPushedPixel = 0; + garbageTarget = this; + nrStops=0; + //topx = tx; + //topy = ty; + cursorx = 2; + cursory = 3; + stop = 0; + pixels = 0; + score = 0; + bGameOver = false; + bDraw = false; + bReplaying=false; //No replay by default +#if NETWORK + bDisconnected=false; + bNetworkPlayer = false; +#endif + timetrial = false; + stageClear = false; + vsMode = false; + puzzleMode = false; + linesCleared = 0; + AI_Enabled = false; + AI_MoveSpeed=100; + hasWonTheGame = false; + combo=0; //counts + chain=0; + hangTicks = 0; + baseSpeed = 0.5; //All other speeds are relative to this + speed = baseSpeed; + speedLevel = 1; + ticks = 0; + gameStartedAt = ticks; + gameEndedAfter = 0; + pushedPixelAt = gameStartedAt; + nextGarbageNumber = 10; + handicap=0; + for (int i=0; i<7; i++) + for (int j=0; j<30; j++) + { + board[i][j] = -1; + } + for (int i=0; i=garbageStackSize) - return false; - garbageStack[garbageStackUsed][0]=width; - garbageStack[garbageStackUsed][1]=height; - garbageStack[garbageStackUsed][2]=type; - garbageStackUsed++; - return true; - } - - bool BlockGame::popGarbage(Uint8 *width, Uint8 *height, Uint8 *type) { - if (garbageStackUsed<1) - return false; - garbageStackUsed--; - *width=garbageStack[garbageStackUsed][0]; - *height=garbageStack[garbageStackUsed][1]; - *type=garbageStack[garbageStackUsed][2]; - return true; - } +void BlockGame::emptyGarbageStack() +{ + for (int i=0; i<10; i++) + for (int j=0; j<3; j++) + garbageStack[i][j] = 0; + garbageStackUsed = 0; +} + +bool BlockGame::pushGarbage(Uint8 width, Uint8 height, Uint8 type) +{ + if (garbageStackUsed>=garbageStackSize) + return false; + garbageStack[garbageStackUsed][0]=width; + garbageStack[garbageStackUsed][1]=height; + garbageStack[garbageStackUsed][2]=type; + garbageStackUsed++; + return true; +} + +bool BlockGame::popGarbage(Uint8 *width, Uint8 *height, Uint8 *type) +{ + if (garbageStackUsed<1) + return false; + garbageStackUsed--; + *width=garbageStack[garbageStackUsed][0]; + *height=garbageStack[garbageStackUsed][1]; + *type=garbageStack[garbageStackUsed][2]; + return true; +} + +#endif + + +//Instead of creating new object new game is called, to prevent memory leaks +void BlockGame::NewGame(int tx, int ty, unsigned int ticks) +{ + this->ticks = ticks; + stageButtonStatus = SBdontShow; + bReplaying = false; +#if NETWORK + bNetworkPlayer=false; + bDisconnected =false; #endif + nrFellDown = 0; + lastNrOfPlayers = 1; //At least one player :-) + nrPushedPixel = 0; + nrStops = 0; + topx = tx; + topy = ty; + cursorx = 2; + cursory = 3; + stop = 0; + pixels = 0; + score = 0; + bGameOver = false; + bDraw = false; + timetrial = false; + stageClear = false; + linesCleared = 0; + hasWonTheGame = false; + vsMode = false; + puzzleMode = false; + combo=0; + chain=0; + AI_Enabled = false; + baseSpeed= 0.5; + speed = baseSpeed; + speedLevel = 1; + gameStartedAt = ticks+3000; + pushedPixelAt = gameStartedAt; + nextGarbageNumber = 10; + handicap=0; + for (int i=0; i<7; i++) + for (int j=0; j<30; j++) + { + board[i][j] = -1; + } + for (int i=0; i -1) + { + NewGame(tx, ty,ticks); + stageClear = true; + Level = level; + Stats::getInstance()->addOne("PlayedStageLevel"+itoa2(level)); + stageClearLimit = 30+(Level%6)*10; + baseSpeed = 0.5/((double)(Level*0.5)+1.0); + speed = baseSpeed; + } +} +void BlockGame::NewPuzzleGame(int level, int tx, int ty, unsigned int ticks) +{ + if (level>-1) + { + NewGame(tx, ty,ticks); + puzzleMode = true; + Level = level; + MovesLeft = nrOfMovesAllowed[Level]; + for (int i=0; i<6; i++) + for (int j=0; j<12; j++) + { + board[i][j+1] = puzzleLevels[Level][i][j]; + } + baseSpeed = 100000; + speed = 100000; + + //Now push the blines up + for (int i=19; i>0; i--) + for (int j=0; j<6; j++) + { + board[j][i] = board[j][i-1]; + } + for (int j=0; j<6; j++) + { + board[j][0] = rand() % 6; + if (j > 0) + { + if (board[j][0] == board[j-1][0]) + board[j][0] = rand() % 6; + } + if (board[j][0] == board[j][1]) + board[j][0] = 6; + if (board[j][0] == board[j][1]) + board[j][0] = 6; - //Instead of creating new object new game is called, to prevent memory leaks - void BlockGame::NewGame(int tx, int ty, unsigned int ticks) { - this->ticks = ticks; - stageButtonStatus = SBdontShow; - bReplaying = false; - #if NETWORK - bNetworkPlayer=false; - bDisconnected =false; - #endif - nrFellDown = 0; - lastNrOfPlayers = 1; //At least one player :-) - nrPushedPixel = 0; - nrStops = 0; - topx = tx; - topy = ty; - cursorx = 2; - cursory = 3; - stop = 0; - pixels = 0; - score = 0; - bGameOver = false; - bDraw = false; - timetrial = false; - stageClear = false; - linesCleared = 0; - hasWonTheGame = false; - vsMode = false; - puzzleMode = false; - combo=0; - chain=0; - AI_Enabled = false; - baseSpeed= 0.5; - speed = baseSpeed; - speedLevel = 1; - gameStartedAt = ticks+3000; - pushedPixelAt = gameStartedAt; - nextGarbageNumber = 10; - handicap=0; - for (int i=0;i<7;i++) - for (int j=0;j<30;j++) { - board[i][j] = -1; - } - for (int i=0;i -1) { - NewGame(tx, ty,ticks); - stageClear = true; - Level = level; - Stats::getInstance()->addOne("PlayedStageLevel"+itoa2(level)); - stageClearLimit = 30+(Level%6)*10; - baseSpeed = 0.5/((double)(Level*0.5)+1.0); - speed = baseSpeed; - } - } - - void BlockGame::NewPuzzleGame(int level, int tx, int ty, unsigned int ticks) { - if (level>-1) { - NewGame(tx, ty,ticks); - puzzleMode = true; - Level = level; - MovesLeft = nrOfMovesAllowed[Level]; - for (int i=0;i<6;i++) - for (int j=0;j<12;j++) { - board[i][j+1] = puzzleLevels[Level][i][j]; - } - baseSpeed = 100000; - speed = 100000; - - //Now push the blines up - for (int i=19;i>0;i--) - for (int j=0;j<6;j++) { - board[j][i] = board[j][i-1]; - } - for (int j=0;j<6;j++) { - board[j][0] = rand() % 6; - if (j > 0) { - if (board[j][0] == board[j-1][0]) - board[j][0] = rand() % 6; - } - if (board[j][0] == board[j][1]) - board[j][0] = 6; - if (board[j][0] == board[j][1]) - board[j][0] = 6; - - } - } - } - - //Replay the current level - void BlockGame::retryLevel(unsigned int ticks) - { - if(puzzleMode) - NewPuzzleGame(Level,topx,topy,ticks); - else - if(stageClear) - NewStageGame(Level,topx,topy,ticks); - } - - //Play the next level - void BlockGame::nextLevel(unsigned int ticks) - { - if(puzzleMode) - { - if(LeveladdOne("VSgamesStarted"); - } - - //Starts new Vs Game (two Player) - void BlockGame::NewVsGame(int tx, int ty, BlockGame *target, bool AI,unsigned int ticks) { - NewGame(tx, ty,ticks); - vsMode = true; - AI_Enabled = AI; - if(!AI) - Stats::getInstance()->addOne("VSgamesStarted"); - else - strcpy(name,"CPU\0"); - putStartBlocks(); - garbageTarget = target; - } - //Go in Demonstration mode, no movement - void BlockGame::Demonstration(bool toggle) { - speed=0; - baseSpeed = 0; - } - //We want to play the replay (must have been loaded beforehand) - void BlockGame::playReplay(int tx, int ty, unsigned int ticks) { - NewGame(tx, ty,ticks); - gameStartedAt = ticks; - bReplaying = true; //We are playing, no calculations - #if NETWORK - bNetworkPlayer = false; //Take input from replay file - #endif - } + } + } +} + +//Replay the current level +void BlockGame::retryLevel(unsigned int ticks) +{ + if(puzzleMode) + NewPuzzleGame(Level,topx,topy,ticks); + else if(stageClear) + NewStageGame(Level,topx,topy,ticks); +} + +//Play the next level +void BlockGame::nextLevel(unsigned int ticks) +{ + if(puzzleMode) + { + if(LeveladdOne("VSgamesStarted"); +} + +//Starts new Vs Game (two Player) +void BlockGame::NewVsGame(int tx, int ty, BlockGame *target, bool AI,unsigned int ticks) +{ + NewGame(tx, ty,ticks); + vsMode = true; + AI_Enabled = AI; + if(!AI) + Stats::getInstance()->addOne("VSgamesStarted"); + else + strcpy(name,"CPU\0"); + putStartBlocks(); + garbageTarget = target; +} +//Go in Demonstration mode, no movement +void BlockGame::Demonstration(bool toggle) +{ + speed=0; + baseSpeed = 0; +} +//We want to play the replay (must have been loaded beforehand) +void BlockGame::playReplay(int tx, int ty, unsigned int ticks) +{ + NewGame(tx, ty,ticks); + gameStartedAt = ticks; + bReplaying = true; //We are playing, no calculations +#if NETWORK + bNetworkPlayer = false; //Take input from replay file +#endif +} #if NETWORK - //network play - void BlockGame::playNetwork(int tx, int ty,unsigned int ticks) { - NewGame(tx, ty,ticks); - gameStartedAt = ticks; - bReplaying = false; //We are playing, no calculations - bNetworkPlayer = true; //Don't Take input from replay file - emptyGarbageStack(); - } +//network play +void BlockGame::playNetwork(int tx, int ty,unsigned int ticks) +{ + NewGame(tx, ty,ticks); + gameStartedAt = ticks; + bReplaying = false; //We are playing, no calculations + bNetworkPlayer = true; //Don't Take input from replay file + emptyGarbageStack(); +} #endif - //Prints "winner" and ends game - void BlockGame::setPlayerWon() { - if (!bGameOver) - { - gameEndedAfter = ticks-gameStartedAt; //We game ends now! - if(!AI_Enabled && !bReplaying) +//Prints "winner" and ends game +void BlockGame::setPlayerWon() +{ + if (!bGameOver) + { + gameEndedAfter = ticks-gameStartedAt; //We game ends now! + if(!AI_Enabled && !bReplaying) { TimeHandler::addTime("playTime",TimeHandler::ms2ct(gameEndedAfter)); } - } - theReplay.setFinalFrame(getPackage(), 1); - bGameOver = true; - hasWonTheGame = true; - showGame = false; - if (SoundEnabled)Mix_PlayChannel(1, applause, 0); - if(!AI_Enabled && !bReplaying) - { - Stats::getInstance()->addOne("totalWins"); - if(garbageTarget->AI_Enabled && !(garbageTarget->bReplaying)) - { - //We have defeated an AI - Stats::getInstance()->addOne("defeatedAI"+itoa(garbageTarget->getAIlevel())); - } - } - if(AI_Enabled && !(garbageTarget->AI_Enabled) && garbageTarget->bReplaying==false) - { - //The AI have defeated a human player - Stats::getInstance()->addOne("defeatedByAI"+itoa(getAIlevel())); - } - } - - //void SetGameOver(); - - #if NETWORK - //Sets disconnected: - void BlockGame::setDisconnect() { - bDisconnected = true; - SetGameOver(); - } - #endif - - //Prints "draw" and ends the game - void BlockGame::setDraw() { - bGameOver = true; + } + theReplay.setFinalFrame(getPackage(), 1); + bGameOver = true; + hasWonTheGame = true; + showGame = false; + if (SoundEnabled)Mix_PlayChannel(1, applause, 0); + if(!AI_Enabled && !bReplaying) + { + Stats::getInstance()->addOne("totalWins"); + if(garbageTarget->AI_Enabled && !(garbageTarget->bReplaying)) + { + //We have defeated an AI + Stats::getInstance()->addOne("defeatedAI"+itoa(garbageTarget->getAIlevel())); + } + } + if(AI_Enabled && !(garbageTarget->AI_Enabled) && garbageTarget->bReplaying==false) + { + //The AI have defeated a human player + Stats::getInstance()->addOne("defeatedByAI"+itoa(getAIlevel())); + } +} + +//void SetGameOver(); + +#if NETWORK +//Sets disconnected: +void BlockGame::setDisconnect() +{ + bDisconnected = true; + SetGameOver(); +} +#endif + +//Prints "draw" and ends the game +void BlockGame::setDraw() +{ + bGameOver = true; if(!AI_Enabled && !bReplaying) { TimeHandler::addTime("playTime",TimeHandler::ms2ct(gameEndedAfter)); } - theReplay.setFinalFrame(getPackage(), 3); - hasWonTheGame = false; - bDraw = true; - showGame = false; - Mix_HaltChannel(1); - if(!AI_Enabled && !bReplaying) - Stats::getInstance()->addOne("totalDraws"); - } - - //Function to get a boardpackage - boardPackage BlockGame::getPackage() { - boardPackage bp; - if(ticks= 10000000) //Higher than this means combos (garbage is static, but the stack is static but nothing to do about it) - return true; //They are static - return false; //Return false if no static object found - } - - /* - * Generates some blocks so the user don't see a board without blocks - */ - //void putStartBlocks(Uint32); - - void BlockGame::putStartBlocks() { - putStartBlocks(time(0)); - } - - void BlockGame::putStartBlocks(Uint32 n) { - for (int i=0;i<7;i++) - for (int j=0;j<30;j++) { - board[i][j] = -1; - } - nextRandomNumber = n; - int choice = rand2()%3; //Pick a random layout - switch (choice) { - case 0: - //row 0: - board[0][0]=1; - board[1][0]=0; - board[2][0]=4; - board[3][0]=3; - board[4][0]=3; - board[5][0]=5; - //row 1: - board[0][1]=1; - board[1][1]=4; - board[2][1]=2; - board[3][1]=0; - board[4][1]=4; - board[5][1]=5; - //row 2: - board[0][2]=2; - board[1][2]=3; - board[2][2]=0; - board[3][2]=4; - board[4][2]=1; - board[5][2]=1; - //row 3: - board[0][3]=3; - board[1][3]=2; - board[2][3]=3; - board[3][3]=1; - board[4][3]=0; - board[5][3]=4; - //row 4: - board[0][4]=2; - board[1][4]=3; - board[2][4]=3; - board[3][4]=1; - board[4][4]=4; - board[5][4]=0; - //row 5: - board[0][5]=-1; - board[1][5]=5; - board[2][5]=5; - board[3][5]=-1; - board[4][5]=1; - board[5][5]=-1; - break; - case 1: - //row 0: - board[0][0]=3; - board[1][0]=5; - board[2][0]=0; - board[3][0]=0; - board[4][0]=4; - board[5][0]=2; - //row 1: - board[0][1]=3; - board[1][1]=5; - board[2][1]=-1; - board[3][1]=5; - board[4][1]=4; - board[5][1]=2; - //row 2: - board[0][2]=2; - board[1][2]=-1; - board[2][2]=-1; - board[3][2]=4; - board[4][2]=0; - board[5][2]=3; - //row 3: - board[0][3]=2; - board[5][3]=3; - break; - default: - //row 0: - board[0][0]=4; - board[1][0]=5; - board[2][0]=2; - board[3][0]=0; - board[4][0]=1; - board[5][0]=5; - //row 1: - board[0][1]=4; - board[1][1]=5; - board[2][1]=2; - board[3][1]=1; - board[4][1]=0; - board[5][1]=2; - //row 2: - board[0][2]=2; - board[1][2]=4; - board[2][2]=-1; - board[3][2]=0; - board[4][2]=1; - board[5][2]=5; - //row 3: - board[0][3]=4; - board[1][3]=2; - board[2][3]=-1; - board[3][3]=1; - board[4][3]=0; - board[5][3]=2; - //row 4: - board[0][4]=4; - board[1][4]=2; - board[2][4]=-1; - board[3][4]=0; - board[4][4]=1; - board[5][4]=-1; - break; - }; - } - - //decreases hang for all hanging blocks and wait for waiting blocks - void BlockGame::ReduceStuff() { - Uint32 howMuchHang = (ticks - FRAMELENGTH*hangTicks)/FRAMELENGTH; - if (howMuchHang>0) { - for (int i=0; i<7; i++) - for (int j=0; j<30; j++) { - if ((board[i][j]/BLOCKHANG)%10==1) { - int hangNumber = (board[i][j]/10)%100; - if (hangNumber<=howMuchHang) { - board[i][j]-=BLOCKHANG; - board[i][j]-=hangNumber*10; - } - else { - board[i][j]-=10*howMuchHang; - } - } - if ((board[i][j]/BLOCKWAIT)%10==1) { - int hangNumber = (board[i][j]/10)%100; - if (hangNumber<=howMuchHang) { - //The blocks must be cleared - board[i][j]-=hangNumber*10; - } - else { - board[i][j]-=10*howMuchHang; - } - } - } - } - hangTicks+=howMuchHang; - } - - //Creates garbage using a given wide and height - bool BlockGame::CreateGarbage(int wide, int height) { + theReplay.setFinalFrame(getPackage(), 3); + hasWonTheGame = false; + bDraw = true; + showGame = false; + Mix_HaltChannel(1); + if(!AI_Enabled && !bReplaying) + Stats::getInstance()->addOne("totalDraws"); +} + +//Function to get a boardpackage +boardPackage BlockGame::getPackage() +{ + boardPackage bp; + if(ticks= 10000000) //Higher than this means combos (garbage is static, but the stack is static but nothing to do about it) + return true; //They are static + return false; //Return false if no static object found +} + +/* + * Generates some blocks so the user don't see a board without blocks + */ +//void putStartBlocks(Uint32); + +void BlockGame::putStartBlocks() +{ + putStartBlocks(time(0)); +} + +void BlockGame::putStartBlocks(Uint32 n) +{ + for (int i=0; i<7; i++) + for (int j=0; j<30; j++) + { + board[i][j] = -1; + } + nextRandomNumber = n; + int choice = rand2()%3; //Pick a random layout + switch (choice) + { + case 0: + //row 0: + board[0][0]=1; + board[1][0]=0; + board[2][0]=4; + board[3][0]=3; + board[4][0]=3; + board[5][0]=5; + //row 1: + board[0][1]=1; + board[1][1]=4; + board[2][1]=2; + board[3][1]=0; + board[4][1]=4; + board[5][1]=5; + //row 2: + board[0][2]=2; + board[1][2]=3; + board[2][2]=0; + board[3][2]=4; + board[4][2]=1; + board[5][2]=1; + //row 3: + board[0][3]=3; + board[1][3]=2; + board[2][3]=3; + board[3][3]=1; + board[4][3]=0; + board[5][3]=4; + //row 4: + board[0][4]=2; + board[1][4]=3; + board[2][4]=3; + board[3][4]=1; + board[4][4]=4; + board[5][4]=0; + //row 5: + board[0][5]=-1; + board[1][5]=5; + board[2][5]=5; + board[3][5]=-1; + board[4][5]=1; + board[5][5]=-1; + break; + case 1: + //row 0: + board[0][0]=3; + board[1][0]=5; + board[2][0]=0; + board[3][0]=0; + board[4][0]=4; + board[5][0]=2; + //row 1: + board[0][1]=3; + board[1][1]=5; + board[2][1]=-1; + board[3][1]=5; + board[4][1]=4; + board[5][1]=2; + //row 2: + board[0][2]=2; + board[1][2]=-1; + board[2][2]=-1; + board[3][2]=4; + board[4][2]=0; + board[5][2]=3; + //row 3: + board[0][3]=2; + board[5][3]=3; + break; + default: + //row 0: + board[0][0]=4; + board[1][0]=5; + board[2][0]=2; + board[3][0]=0; + board[4][0]=1; + board[5][0]=5; + //row 1: + board[0][1]=4; + board[1][1]=5; + board[2][1]=2; + board[3][1]=1; + board[4][1]=0; + board[5][1]=2; + //row 2: + board[0][2]=2; + board[1][2]=4; + board[2][2]=-1; + board[3][2]=0; + board[4][2]=1; + board[5][2]=5; + //row 3: + board[0][3]=4; + board[1][3]=2; + board[2][3]=-1; + board[3][3]=1; + board[4][3]=0; + board[5][3]=2; + //row 4: + board[0][4]=4; + board[1][4]=2; + board[2][4]=-1; + board[3][4]=0; + board[4][4]=1; + board[5][4]=-1; + break; + }; +} + +//decreases hang for all hanging blocks and wait for waiting blocks +void BlockGame::ReduceStuff() +{ + Uint32 howMuchHang = (ticks - FRAMELENGTH*hangTicks)/FRAMELENGTH; + if (howMuchHang>0) + { + for (int i=0; i<7; i++) + for (int j=0; j<30; j++) + { + if ((board[i][j]/BLOCKHANG)%10==1) + { + int hangNumber = (board[i][j]/10)%100; + if (hangNumber<=howMuchHang) + { + board[i][j]-=BLOCKHANG; + board[i][j]-=hangNumber*10; + } + else + { + board[i][j]-=10*howMuchHang; + } + } + if ((board[i][j]/BLOCKWAIT)%10==1) + { + int hangNumber = (board[i][j]/10)%100; + if (hangNumber<=howMuchHang) + { + //The blocks must be cleared + board[i][j]-=hangNumber*10; + } + else + { + board[i][j]-=10*howMuchHang; + } + } + } + } + hangTicks+=howMuchHang; +} + +//Creates garbage using a given wide and height +bool BlockGame::CreateGarbage(int wide, int height) +{ #if NETWORK - if (bNetworkPlayer) { - pushGarbage(wide, height, 0); - } - else + if (bNetworkPlayer) + { + pushGarbage(wide, height, 0); + } + else #endif - { - if (wide>6) wide = 6; - if (height>12) height = 12; - int startPosition = 12; - while ((!(LineEmpty(startPosition))) || (startPosition == 29)) - startPosition++; - if (startPosition == 29) return false; //failed to place blocks - if (29-startPosition999999) nextGarbageNumber = 10; - //bGarbageFallLeft = !(bGarbageFallLeft); - return true; - } - } - - //Creates garbage using a given wide and height - bool BlockGame::CreateGreyGarbage() { + { + if (wide>6) wide = 6; + if (height>12) height = 12; + int startPosition = 12; + while ((!(LineEmpty(startPosition))) || (startPosition == 29)) + startPosition++; + if (startPosition == 29) return false; //failed to place blocks + if (29-startPosition999999) nextGarbageNumber = 10; + //bGarbageFallLeft = !(bGarbageFallLeft); + return true; + } +} + +//Creates garbage using a given wide and height +bool BlockGame::CreateGreyGarbage() +{ #if NETWORK - if (bNetworkPlayer) { - pushGarbage(6, 1, 1); - } - else + if (bNetworkPlayer) + { + pushGarbage(6, 1, 1); + } + else #endif - { - int startPosition = 12; - while ((!(LineEmpty(startPosition))) || (startPosition == 29)) - startPosition++; - if (startPosition == 29) return false; //failed to place blocks - if (29-startPosition<1) return false; //not enough space - int start, end; - { - start=0; - end=6; - } - for (int i = startPosition; i 999999) nextGarbageNumber = 10; - return true; - } - } - - - //Clears garbage, must take one the lower left corner! - int BlockGame::GarbageClearer(int x, int y, int number, bool aLineToClear, int chain) { - if ((board[x][y])%1000000 != number) return -1; - if (aLineToClear) { - board[x][y] = rand() % 6; - board[x][y] += 10*HANGTIME+BLOCKHANG+CHAINPLACE*chain; - } - garbageToBeCleared[x][y] = false; - GarbageClearer(x+1, y, number, aLineToClear, chain); - GarbageClearer(x, y+1, number, false, chain); - return 1; - } - - //Marks garbage that must be cleared - int BlockGame::GarbageMarker(int x, int y) { - if ((x>6)||(x<0)||(y<0)||(y>29)) return -1; - if (((board[x][y])/1000000 == 1)&&(garbageToBeCleared[x][y] == false)) { - garbageToBeCleared[x][y] = true; - //Float fill - GarbageMarker(x-1, y); - GarbageMarker(x+1, y); - GarbageMarker(x, y-1); - GarbageMarker(x, y+1); - } - return 1; - } - - int BlockGame::FirstGarbageMarker(int x, int y) { - if ((x>6)||(x<0)||(y<0)||(y>29)) return -1; - if (((board[x][y])/1000000 == 2)&&(garbageToBeCleared[x][y] == false)) { - for (int i=0;i<6;i++) - garbageToBeCleared[i][y] = true; - } - else - if (((board[x][y])/1000000 == 1)&&(garbageToBeCleared[x][y] == false)) { - garbageToBeCleared[x][y] = true; - //Float fill - GarbageMarker(x-1, y); - GarbageMarker(x+1, y); - GarbageMarker(x, y-1); - GarbageMarker(x, y+1); - } - return 1; - } - - //Clear Blocks if 3 or more is alligned (naive implemented) - void BlockGame::ClearBlocks() { - - bool toBeCleared[7][30]; //true if blok must be removed - - int previus=-1; //the last block checked - int combo=0; - for (int i=0;i<30;i++) - for (int j=0;j<7;j++) { - toBeCleared[j][i] = false; - garbageToBeCleared[j][i] = false; - } - for (int i=0;i<7;i++) { - bool faaling = false; - for (int j=0;j<30;j++) { - if ((faaling)&&(board[i][j]>-1)&&(board[i][j]%10000000<7)) { - board[i][j]+=BLOCKFALL; - } - if ((!faaling)&&((board[i][j]/BLOCKFALL)%10==1)) - board[i][j]-=BLOCKFALL; - if (!((board[i][j]>-1)&&(board[i][j]%10000000<7))) - faaling=true; - if (((board[i][j]/1000000)%10==1)||((board[i][j]/1000000)%10==2)||((board[i][j]/BLOCKHANG)%10==1)||((board[i][j]/BLOCKWAIT)%10==1)) - faaling = false; - } - } - - - for (int j=0;j<7;j++) { - previus = -1; - combo=0; - - for (int i=1;i<30;i++) { - if ((board[j][i]>-1)&&(board[j][i]%10000000<7)) { - if (board[j][i]%10000000 == previus) { - combo++; - } - else { - if (combo>2) - for (int k = i-combo; k2) - for (int k = i-combo; k-1)&&(board[j][i]%10000000<7))) { - if (board[j][i]%10000000 == previus) { - combo++; - } - else { - if (combo>2) - for (int k = j-combo; k2) - for (int k = j-combo; k2) && (board[j][i]%10000000==6)) - garbageTarget->CreateGreyGarbage(); - if ((board[j][i]>-1)&&(board[j][i]%10000000<7)) - board[j][i]+=BLOCKWAIT+10*FALLTIME; - - if (chainSize[board[j][i]/10000000]>chainSize[chain]) - chain=board[j][i]/10000000; - combo++; - stop+=140*combo; - score +=10; - if (combo>3) - score+=3*combo; //More points if more cleared simontanously - } - score+=chainSize[chain]*100; - if (chain==0) { - chain=firstUnusedChain(); - chainSize[chain]=0; - chainUsed[chain]=true; - } - chainSize[chain]++; - for (int i=0;i<30;i++) - for (int j=0;j<6;j++) { - //if(board[j][i]/10==(BLOCKWAIT+10*FALLTIME)/10) - if (toBeCleared[j][i]) { - board[j][i]=(board[j][i]%10000000)+chain*10000000; - } - } - - { //This is here we add text to screen! - bool dead = false; - for (int i=29;i>=0;i--) - for (int j=0;j<6;j++) - if (toBeCleared[j][i]) { - if (!dead) { - dead=true; - string tempS = itoa(chainSize[chain]); - if (chainSize[chain]>1) - theTextManeger.addText(topx-10+j*bsize, topy+12*bsize-i*bsize, tempS, 1000); - } - } - } //This was there text was added - - if (vsMode) - switch (combo) { - case 0: - case 1: - case 2: - case 3: - break; - case 4: - garbageTarget->CreateGarbage(3, 1); - break; - case 5: - garbageTarget->CreateGarbage(4, 1); - break; - case 6: - garbageTarget->CreateGarbage(5, 1); - break; - case 7: - garbageTarget->CreateGarbage(6, 1); - break; - case 8: - garbageTarget->CreateGarbage(4, 1); - garbageTarget->CreateGarbage(4, 1); - break; - case 9: - garbageTarget->CreateGarbage(5, 1); - garbageTarget->CreateGarbage(4, 1); - break; - case 10: - garbageTarget->CreateGarbage(5, 1); - garbageTarget->CreateGarbage(5, 1); - break; - case 11: - garbageTarget->CreateGarbage(6, 1); - garbageTarget->CreateGarbage(5, 1); - break; - case 12: - garbageTarget->CreateGarbage(6, 1); - garbageTarget->CreateGarbage(6, 1); - break; - case 13: - garbageTarget->CreateGarbage(5, 1); - garbageTarget->CreateGarbage(5, 1); - garbageTarget->CreateGarbage(4, 1); - break; - default: - garbageTarget->CreateGarbage(5, 1); - garbageTarget->CreateGarbage(5, 1); - garbageTarget->CreateGarbage(4, 1); - break; - } - for (int i=0;i<30;i++) - for (int j=0;j<6;j++) - if (garbageToBeCleared[j][i]) { - GarbageClearer(j, i, board[j][i]%1000000, true, chain); //Clears the blocks and all blocks connected to it. - } - - chain=0; - - //Break chains (if a block is stable it is resetted to (chain == 0)): - for (int i=0;i<7;i++) { - bool faaling = false; //In the beginning we are NOT falling - for (int j=0;j<30;j++) { - if ((faaling)&&(board[i][j]>-1)&&(board[i][j]<7)) { - board[i][j]+=BLOCKFALL; - } - if ((!faaling)&&((board[i][j]/BLOCKFALL)%10==1)) - board[i][j]-=BLOCKFALL; - if ((!faaling)&&(board[i][j]>0)&&(board[i][j]/10000000!=0)&&((board[i][j]/BLOCKWAIT)%10!=1)&&((board[i][j]/BLOCKHANG)%10!=1)) { - if (chainSize[board[i][j]/10000000]>chainSize[chain]) - chain=board[i][j]/10000000; - board[i][j]=board[i][j]%10000000; - } - if (!((board[i][j]>-1)&&(board[i][j]<7))) - faaling=true; - if (((board[i][j]/1000000)%10==1)||((board[i][j]/BLOCKHANG)%10==1)||((board[i][j]/BLOCKWAIT)%10==1)) - faaling = false; - } - } - - //Create garbage as a result - //if((vsMode)&&(chainSize[chain]>1)) garbageTarget->CreateGarbage(6,chainSize[chain]-1); - - //Calculate chain - chain=0; - for (int i=0; i<6;i++) - for (int j=0; j<30;j++) { - if (chainSize[board[i][j]/10000000]>chain) - chain=chainSize[board[i][j]/10000000]; - } - - //Make space in table for more things - if (chain==0) - for (int i=0;i1)) garbageTarget->CreateGarbage(6, chainSize[i]-1); - if ((SoundEnabled)&&(chainSize[i]>4))Mix_PlayChannel(1, applause, 0); - if(chainSize[i]>1 && !puzzleMode && !AI_Enabled) - Stats::getInstance()->addOne((string)"chainX"+itoa(chainSize[i])); - chainUsed[i]=false; - } - } //ClearBlocks - - //prints "Game Over" and ends game - void BlockGame::SetGameOver() { - if (!bGameOver) { - gameEndedAfter = ticks-gameStartedAt; //We game ends now! + { + int startPosition = 12; + while ((!(LineEmpty(startPosition))) || (startPosition == 29)) + startPosition++; + if (startPosition == 29) return false; //failed to place blocks + if (29-startPosition<1) return false; //not enough space + int start, end; + { + start=0; + end=6; + } + for (int i = startPosition; i 999999) nextGarbageNumber = 10; + return true; + } +} + + +//Clears garbage, must take one the lower left corner! +int BlockGame::GarbageClearer(int x, int y, int number, bool aLineToClear, int chain) +{ + if ((board[x][y])%1000000 != number) return -1; + if (aLineToClear) + { + board[x][y] = rand() % 6; + board[x][y] += 10*HANGTIME+BLOCKHANG+CHAINPLACE*chain; + } + garbageToBeCleared[x][y] = false; + GarbageClearer(x+1, y, number, aLineToClear, chain); + GarbageClearer(x, y+1, number, false, chain); + return 1; +} + +//Marks garbage that must be cleared +int BlockGame::GarbageMarker(int x, int y) +{ + if ((x>6)||(x<0)||(y<0)||(y>29)) return -1; + if (((board[x][y])/1000000 == 1)&&(garbageToBeCleared[x][y] == false)) + { + garbageToBeCleared[x][y] = true; + //Float fill + GarbageMarker(x-1, y); + GarbageMarker(x+1, y); + GarbageMarker(x, y-1); + GarbageMarker(x, y+1); + } + return 1; +} + +int BlockGame::FirstGarbageMarker(int x, int y) +{ + if ((x>6)||(x<0)||(y<0)||(y>29)) return -1; + if (((board[x][y])/1000000 == 2)&&(garbageToBeCleared[x][y] == false)) + { + for (int i=0; i<6; i++) + garbageToBeCleared[i][y] = true; + } + else if (((board[x][y])/1000000 == 1)&&(garbageToBeCleared[x][y] == false)) + { + garbageToBeCleared[x][y] = true; + //Float fill + GarbageMarker(x-1, y); + GarbageMarker(x+1, y); + GarbageMarker(x, y-1); + GarbageMarker(x, y+1); + } + return 1; +} + +//Clear Blocks if 3 or more is alligned (naive implemented) +void BlockGame::ClearBlocks() +{ + + bool toBeCleared[7][30]; //true if blok must be removed + + int previus=-1; //the last block checked + int combo=0; + for (int i=0; i<30; i++) + for (int j=0; j<7; j++) + { + toBeCleared[j][i] = false; + garbageToBeCleared[j][i] = false; + } + for (int i=0; i<7; i++) + { + bool faaling = false; + for (int j=0; j<30; j++) + { + if ((faaling)&&(board[i][j]>-1)&&(board[i][j]%10000000<7)) + { + board[i][j]+=BLOCKFALL; + } + if ((!faaling)&&((board[i][j]/BLOCKFALL)%10==1)) + board[i][j]-=BLOCKFALL; + if (!((board[i][j]>-1)&&(board[i][j]%10000000<7))) + faaling=true; + if (((board[i][j]/1000000)%10==1)||((board[i][j]/1000000)%10==2)||((board[i][j]/BLOCKHANG)%10==1)||((board[i][j]/BLOCKWAIT)%10==1)) + faaling = false; + } + } + + + for (int j=0; j<7; j++) + { + previus = -1; + combo=0; + + for (int i=1; i<30; i++) + { + if ((board[j][i]>-1)&&(board[j][i]%10000000<7)) + { + if (board[j][i]%10000000 == previus) + { + combo++; + } + else + { + if (combo>2) + for (int k = i-combo; k2) + for (int k = i-combo; k-1)&&(board[j][i]%10000000<7))) + { + if (board[j][i]%10000000 == previus) + { + combo++; + } + else + { + if (combo>2) + for (int k = j-combo; k2) + for (int k = j-combo; k2) && (board[j][i]%10000000==6)) + garbageTarget->CreateGreyGarbage(); + if ((board[j][i]>-1)&&(board[j][i]%10000000<7)) + board[j][i]+=BLOCKWAIT+10*FALLTIME; + + if (chainSize[board[j][i]/10000000]>chainSize[chain]) + chain=board[j][i]/10000000; + combo++; + stop+=140*combo; + score +=10; + if (combo>3) + score+=3*combo; //More points if more cleared simontanously + } + score+=chainSize[chain]*100; + if (chain==0) + { + chain=firstUnusedChain(); + chainSize[chain]=0; + chainUsed[chain]=true; + } + chainSize[chain]++; + for (int i=0; i<30; i++) + for (int j=0; j<6; j++) + { + //if(board[j][i]/10==(BLOCKWAIT+10*FALLTIME)/10) + if (toBeCleared[j][i]) + { + board[j][i]=(board[j][i]%10000000)+chain*10000000; + } + } + + { + //This is here we add text to screen! + bool dead = false; + for (int i=29; i>=0; i--) + for (int j=0; j<6; j++) + if (toBeCleared[j][i]) + { + if (!dead) + { + dead=true; + string tempS = itoa(chainSize[chain]); + if (chainSize[chain]>1) + theTextManeger.addText(topx-10+j*bsize, topy+12*bsize-i*bsize, tempS, 1000); + } + } + } //This was there text was added + + if (vsMode) + switch (combo) + { + case 0: + case 1: + case 2: + case 3: + break; + case 4: + garbageTarget->CreateGarbage(3, 1); + break; + case 5: + garbageTarget->CreateGarbage(4, 1); + break; + case 6: + garbageTarget->CreateGarbage(5, 1); + break; + case 7: + garbageTarget->CreateGarbage(6, 1); + break; + case 8: + garbageTarget->CreateGarbage(4, 1); + garbageTarget->CreateGarbage(4, 1); + break; + case 9: + garbageTarget->CreateGarbage(5, 1); + garbageTarget->CreateGarbage(4, 1); + break; + case 10: + garbageTarget->CreateGarbage(5, 1); + garbageTarget->CreateGarbage(5, 1); + break; + case 11: + garbageTarget->CreateGarbage(6, 1); + garbageTarget->CreateGarbage(5, 1); + break; + case 12: + garbageTarget->CreateGarbage(6, 1); + garbageTarget->CreateGarbage(6, 1); + break; + case 13: + garbageTarget->CreateGarbage(5, 1); + garbageTarget->CreateGarbage(5, 1); + garbageTarget->CreateGarbage(4, 1); + break; + default: + garbageTarget->CreateGarbage(5, 1); + garbageTarget->CreateGarbage(5, 1); + garbageTarget->CreateGarbage(4, 1); + break; + } + for (int i=0; i<30; i++) + for (int j=0; j<6; j++) + if (garbageToBeCleared[j][i]) + { + GarbageClearer(j, i, board[j][i]%1000000, true, chain); //Clears the blocks and all blocks connected to it. + } + + chain=0; + + //Break chains (if a block is stable it is resetted to (chain == 0)): + for (int i=0; i<7; i++) + { + bool faaling = false; //In the beginning we are NOT falling + for (int j=0; j<30; j++) + { + if ((faaling)&&(board[i][j]>-1)&&(board[i][j]<7)) + { + board[i][j]+=BLOCKFALL; + } + if ((!faaling)&&((board[i][j]/BLOCKFALL)%10==1)) + board[i][j]-=BLOCKFALL; + if ((!faaling)&&(board[i][j]>0)&&(board[i][j]/10000000!=0)&&((board[i][j]/BLOCKWAIT)%10!=1)&&((board[i][j]/BLOCKHANG)%10!=1)) + { + if (chainSize[board[i][j]/10000000]>chainSize[chain]) + chain=board[i][j]/10000000; + board[i][j]=board[i][j]%10000000; + } + if (!((board[i][j]>-1)&&(board[i][j]<7))) + faaling=true; + if (((board[i][j]/1000000)%10==1)||((board[i][j]/BLOCKHANG)%10==1)||((board[i][j]/BLOCKWAIT)%10==1)) + faaling = false; + } + } + + //Create garbage as a result + //if((vsMode)&&(chainSize[chain]>1)) garbageTarget->CreateGarbage(6,chainSize[chain]-1); + + //Calculate chain + chain=0; + for (int i=0; i<6; i++) + for (int j=0; j<30; j++) + { + if (chainSize[board[i][j]/10000000]>chain) + chain=chainSize[board[i][j]/10000000]; + } + + //Make space in table for more things + if (chain==0) + for (int i=0; i1)) garbageTarget->CreateGarbage(6, chainSize[i]-1); + if ((SoundEnabled)&&(chainSize[i]>4))Mix_PlayChannel(1, applause, 0); + if(chainSize[i]>1 && !puzzleMode && !AI_Enabled) + Stats::getInstance()->addOne((string)"chainX"+itoa(chainSize[i])); + chainUsed[i]=false; + } +} //ClearBlocks + +//prints "Game Over" and ends game +void BlockGame::SetGameOver() +{ + if (!bGameOver) + { + gameEndedAfter = ticks-gameStartedAt; //We game ends now! if(!AI_Enabled && !bReplaying) { TimeHandler::addTime("playTime",TimeHandler::ms2ct(gameEndedAfter)); } } - if(bReplaying) - { - bReplaying = false; - } - else - { - strncpy(theReplay.name,name,30); - } - theReplay.setFinalFrame(getPackage(), 0); - bGameOver = true; - showGame = false; - if(stageClear) - stageButtonStatus = SBstageClear; - } - - bool BlockGame::GetAIenabled() { - return AI_Enabled; - } - - - //Moves all peaces a spot down if possible - int BlockGame::FallBlock(int x, int y, int number) { - if (y == 0) return -1; - if (x>0) - if (board[x-1][y] == number) - return -1; - int i=x; - bool canFall = true; - //checks a line of a garbage block and see if something is under it - while ((board[i][y] == number)&&(canFall)&&(i<6)) { - if (board[i][y-1] != -1) canFall = false; - i++; - } - if (canFall) { - //cout << "Now falling" << endl; - for (int j = x;j12) ||(((pixels==bsize)||(pixels==0)) && (cursory<11)))) - cursory++; - if ((way == 'S') && (cursory>0)) - cursory--; - if ((way == 'W') && (cursorx>0)) - cursorx--; - if ((way == 'E') && (cursorx<4)) - cursorx++; - } - } - - //switches the two blocks at the cursor position, unless game over - void BlockGame::SwitchAtCursor() { - if ((board[cursorx][cursory+1]<7) && (board[cursorx+1][cursory+1]<7) && (!bGameOver) && ((!puzzleMode)||(MovesLeft>0)) && (gameStartedAt0)) MovesLeft--; - } - - //Generates a new line and moves the field one block up (restart puzzle mode) - void BlockGame::PushLine() { - //If not game over, not high tower and not puzzle mode - if ((!bGameOver) && TowerHeight<13 && (!puzzleMode) && (gameStartedAt0;i--) - for (int j=0;j<6;j++) { - board[j][i] = board[j][i-1]; - } - for (int j=0;j<6;j++) { - board[j][0] = rand2() % 4; - if (j > 0) { - if (board[j][0] == board[j-1][0]) - board[j][0] = rand2() % 6; - } - if (board[j][0] == board[j][1]) - board[j][0] = rand2() % 6; - if (board[j][0] == board[j][1]) - board[j][0] = rand2() % 6; - while ((j>0)&&(board[j][0]==board[j-1][0])) - board[j][0] = rand2() % 6; - } - score+=1; - MoveCursor('N'); - if (vsMode) { - if (rand2()%6==1) - board[rand2()%6][0]=6; - } - pixels = 0; - stop=0; - pushedPixelAt = ticks; - linesCleared++; - AI_LineOffset++; - nrPushedPixel=(int)((double)(pushedPixelAt-gameStartedAt)/(1000.0*speed)); - - if(!AI_Enabled && !bReplaying) - { - Stats::getInstance()->addOne("linesPushed"); - } - } //if !bGameOver - - //Restart Puzzle mode - if (puzzleMode && !bGameOver) { - //Reloads level - MovesLeft = nrOfMovesAllowed[Level]; - for (int i=0;i<6;i++) - for (int j=0;j<12;j++) { - board[i][j+1] = puzzleLevels[Level][i][j]; - } - score=0; - bGameOver=false; - showGame = true; - } - - if ((TowerHeight>12) && (!puzzleMode)&&(!bGameOver)&&(chain==0)) { - if ((!vsMode)&&(theTopScoresEndless.isHighScore(score))&&(!AI_Enabled)) { - if (SoundEnabled)Mix_PlayChannel(1, applause, 0); - theTopScoresEndless.addScore(name, score); - cout << "New high score!" << endl; - } - SetGameOver(); - } - - - }//PushLine - - //Pushes a single pixel, so it appears to scrool - void BlockGame::PushPixels() { - nrPushedPixel++; - if ((pixels < bsize) && TowerHeight<13) { - pixels++; - } - else - PushLine(); - if (pixels>bsize) - pixels=0; - } - - - //See how high the tower is, saved in integer TowerHeight - void BlockGame::FindTowerHeight() { - /* - * Old implementation, used until I find the bug in the other. - * This function has a bug in stage clear! if an empty line appears. - */ - prevTowerHeight = TowerHeight; - bool found = false; - TowerHeight = 0; - while (!found) { - found = true; - for (int j=0;j<6;j++) - if (board[j][TowerHeight] != -1) - found = false; - TowerHeight++; - } - TowerHeight--; - } + if(bReplaying) + { + bReplaying = false; + } + else + { + strncpy(theReplay.name,name,30); + } + theReplay.setFinalFrame(getPackage(), 0); + bGameOver = true; + showGame = false; + if(stageClear) + stageButtonStatus = SBstageClear; +} + +bool BlockGame::GetAIenabled() +{ + return AI_Enabled; +} + + +//Moves all peaces a spot down if possible +int BlockGame::FallBlock(int x, int y, int number) +{ + if (y == 0) return -1; + if (x>0) + if (board[x-1][y] == number) + return -1; + int i=x; + bool canFall = true; + //checks a line of a garbage block and see if something is under it + while ((board[i][y] == number)&&(canFall)&&(i<6)) + { + if (board[i][y-1] != -1) canFall = false; + i++; + } + if (canFall) + { + //cout << "Now falling" << endl; + for (int j = x; j12) ||(((pixels==bsize)||(pixels==0)) && (cursory<11)))) + cursory++; + if ((way == 'S') && (cursory>0)) + cursory--; + if ((way == 'W') && (cursorx>0)) + cursorx--; + if ((way == 'E') && (cursorx<4)) + cursorx++; + } +} + +//switches the two blocks at the cursor position, unless game over +void BlockGame::SwitchAtCursor() +{ + if ((board[cursorx][cursory+1]<7) && (board[cursorx+1][cursory+1]<7) && (!bGameOver) && ((!puzzleMode)||(MovesLeft>0)) && (gameStartedAt0)) MovesLeft--; +} + +//Generates a new line and moves the field one block up (restart puzzle mode) +void BlockGame::PushLine() +{ + //If not game over, not high tower and not puzzle mode + if ((!bGameOver) && TowerHeight<13 && (!puzzleMode) && (gameStartedAt0; i--) + for (int j=0; j<6; j++) + { + board[j][i] = board[j][i-1]; + } + for (int j=0; j<6; j++) + { + board[j][0] = rand2() % 4; + if (j > 0) + { + if (board[j][0] == board[j-1][0]) + board[j][0] = rand2() % 6; + } + if (board[j][0] == board[j][1]) + board[j][0] = rand2() % 6; + if (board[j][0] == board[j][1]) + board[j][0] = rand2() % 6; + while ((j>0)&&(board[j][0]==board[j-1][0])) + board[j][0] = rand2() % 6; + } + score+=1; + MoveCursor('N'); + if (vsMode) + { + if (rand2()%6==1) + board[rand2()%6][0]=6; + } + pixels = 0; + stop=0; + pushedPixelAt = ticks; + linesCleared++; + AI_LineOffset++; + nrPushedPixel=(int)((double)(pushedPixelAt-gameStartedAt)/(1000.0*speed)); + + if(!AI_Enabled && !bReplaying) + { + Stats::getInstance()->addOne("linesPushed"); + } + } //if !bGameOver + + //Restart Puzzle mode + if (puzzleMode && !bGameOver) + { + //Reloads level + MovesLeft = nrOfMovesAllowed[Level]; + for (int i=0; i<6; i++) + for (int j=0; j<12; j++) + { + board[i][j+1] = puzzleLevels[Level][i][j]; + } + score=0; + bGameOver=false; + showGame = true; + } + + if ((TowerHeight>12) && (!puzzleMode)&&(!bGameOver)&&(chain==0)) + { + if ((!vsMode)&&(theTopScoresEndless.isHighScore(score))&&(!AI_Enabled)) + { + if (SoundEnabled)Mix_PlayChannel(1, applause, 0); + theTopScoresEndless.addScore(name, score); + cout << "New high score!" << endl; + } + SetGameOver(); + } + + +}//PushLine + +//Pushes a single pixel, so it appears to scrool +void BlockGame::PushPixels() +{ + nrPushedPixel++; + if ((pixels < bsize) && TowerHeight<13) + { + pixels++; + } + else + PushLine(); + if (pixels>bsize) + pixels=0; +} + + +//See how high the tower is, saved in integer TowerHeight +void BlockGame::FindTowerHeight() +{ + /* + * Old implementation, used until I find the bug in the other. + * This function has a bug in stage clear! if an empty line appears. + */ + prevTowerHeight = TowerHeight; + bool found = false; + TowerHeight = 0; + while (!found) + { + found = true; + for (int j=0; j<6; j++) + if (board[j][TowerHeight] != -1) + found = false; + TowerHeight++; + } + TowerHeight--; +} /////////////////////////////////////////////////////////////////////////// /////////////////////////// AI starts here! /////////////////////////////// /////////////////////////////////////////////////////////////////////////// - //First the helpet functions: - int BlockGame::nrOfType(int line, int type) { - // cout << "Start_ nrOfType" << endl; - int counter = 0; - for (int i=0; i<6; i++) - if (board[i][line]==type)counter++; - return counter; - } - - - //See if a combo can be made in this line - int BlockGame::horiInLine(int line) { - //cout << "Start_ hori in line" << endl; - int nrOfType[7] = {0, 0, 0, 0, 0, 0, 0}; - int iTemp; - int max = 0; - for (int i=0; i<6; i++) { - iTemp = board[i][line]; - if ((iTemp>-1)&&(iTemp<7)) - nrOfType[iTemp]++; - } - for (int j=0; j<7; j++) { - if (nrOfType[j]>max) { - max = nrOfType[j]; - AIcolorToClear = j; - } - } - return max; - } - - bool BlockGame::horiClearPossible() { - //cout << "Start_ horiclear possible" << endl; - int i=13; - bool solutionFound = false; - do{ - if (horiInLine(i)>2) { - AI_LineOffset = 0; - AIlineToClear = i; - solutionFound = true; - } - i--; - }while ((!solutionFound)&&(i>0)); - return solutionFound; - } - - //the Line Has Unmoveable Objects witch might stall the AI - bool BlockGame::lineHasGarbage(int line) { - for (int i=0;i<6;i++) - if (board[i][line]>1000000) - return true; - return false; - } - - //Types 0..6 in line - int BlockGame::nrOfRealTypes(int line) { - //cout << "Start_ nrOfReal" << endl; - int counter = 0; - for (int i=0; i<6; i++) - if ((board[i][line]>-1)&&(board[i][line]<7))counter++; - return counter; - } - - //See if there is a tower - bool BlockGame::ThereIsATower() { - //cout << "Start_ there is a tower" << endl; - bool bThereIsATower = false; //Unless proven otherwise! - bool topReached = false; //If we have reached the top - int lineNumber = 0; - bool emptySpacesFound = false; - do { - if ((emptySpacesFound) && (nrOfRealTypes(lineNumber)>0)&&(nrOfType(lineNumber, -1)>0)) { - AIlineToClear = lineNumber; - if (lineHasGarbage(lineNumber)) - return false; - else - bThereIsATower = true; - } - else - emptySpacesFound=false; - if ((!emptySpacesFound)&&(nrOfType(lineNumber, -1)>0)) - emptySpacesFound = true; - if (lineNumber<12) - lineNumber++; - else - topReached = true; - }while ((!bThereIsATower)&&(!topReached)); - //if(bThereIsATower) - //cout << "There is actually a tower" << endl; - return bThereIsATower; - } - - double BlockGame::firstInLine1(int line) { - for (int i=0;i<6;i++) - if ((board[i][line]>-1)&&(board[i][line]<7)) - return (double)i; - return 3.0; - } - - //returns the first coordinate of the block of type - double BlockGame::firstInLine(int line, int type) { - for (int i=0;i<6;i++) - if (board[i][line]==type) - return (double)i; - return 3.0; - } - - //There in the line shall we move - int BlockGame::closestTo(int line, int place) { - if ((int)firstInLine1(line)>place) - return (int)firstInLine1(line)-1; - for (int i=place;i>=0;i--) { - if ((board[i][line]>-1)&&(board[i][line]<7)) - return i; - } - AIstatus=0; - return place; - } - - //The AI will remove a tower - void BlockGame::AI_ClearTower() { - // cout << "AI: ClearTower, line: " << AIlineToClear << endl; - int place = (int)firstInLine(AIlineToClear-1, -1); //Find an empty field to frop a brick into - int xplace = closestTo(AIlineToClear, place); //Find the brick to drop in it - if (cursory+1AIlineToClear) - MoveCursor('S'); - else - if (cursorxxplace) - MoveCursor('W'); - else - SwitchAtCursor(); - if (!ThereIsATower()) - AIstatus = 0; - } - - //The AI will try to clear block horisontally - void BlockGame::AI_ClearHori() { - // cout << "AI: ClearHori"; - int lowestLine = AIlineToClear; - //AIcolorToClear - bool found =true; - /*for(int i; (i<12)&&(!found);i++) - * { - * if(horiInLine(i)>2) - * { - * int lowestLine = i; - * found = true; - * } - * }*/ - for (int i=0;i<7;i++) { - if (nrOfType(lowestLine, i)>2) - AIcolorToClear = i; - } - if (found) { - if (cursory>lowestLine-1) - MoveCursor('S'); - else if (cursory2) { - int left=0, right=0; - if (board[0][lowestLine]==AIcolorToClear) left++; - if (board[1][lowestLine]==AIcolorToClear) left++; - if (board[2][lowestLine]==AIcolorToClear) left++; - if (board[3][lowestLine]==AIcolorToClear) right++; - if (board[4][lowestLine]==AIcolorToClear) right++; - if (board[5][lowestLine]==AIcolorToClear) right++; - int xplace = 0; - if (leftleft"; - int count=0; - for (int i=0;(i<4)&&(count<1);i++) - if ((board[i][lowestLine]==AIcolorToClear)&&((i==0)||(board[i+1][lowestLine]!=AIcolorToClear))) { - count++; - xplace = i; - } - } - else { - // cout << ", left>=right"; - int count=0; - for (int i=3;(i<=5)&&(count<1);i++) - if ((board[i][lowestLine]==AIcolorToClear)&&(board[i-1][lowestLine]!=AIcolorToClear)) { - count++; - xplace = --i; - } - } - //cout << ", xplace: " << xplace; - if (cursorxxplace) - MoveCursor('W'); - else - if (cursorx==xplace) - SwitchAtCursor(); - else - AIstatus = 0; - } - else - AIstatus = 0; - } - else - AIstatus = 0; - //cout << endl; //for debugging - } - - //Test if vertical clear is possible - bool BlockGame::veriClearPossible() { - bool found=false; - int colors[7] = {0, 0, 0, 0, 0, 0, 0}; - for (int i=12;(i>0)&&(!found);i--) { - for (int j=0;j<7;j++) { - if (nrOfType(i, j)==0) - colors[j]=0; - else - if (++colors[j]>2) { - AIcolorToClear = j; - AIlineToClear = i; - found=true; - } - - } - } - return found; - } - - - - //There in the line shall we move - int BlockGame::closestTo(int line, int type, int place) { - if ((int)firstInLine(line, type)>place) - return (int)firstInLine(line, type)-1; - for (int i=place;i>=0;i--) { - if (board[i][line]==type) - return i; - } - AIstatus=0; - return place; - } - - //The AI will try to clear blocks vertically - void BlockGame::AI_ClearVertical() { - // cout << "AI: ClearVeri"; - //First we find the place there we will align the bricks - int placeToCenter = (int)(firstInLine(AIlineToClear, AIcolorToClear)/3.0+firstInLine(AIlineToClear+1, AIcolorToClear)/3.0+firstInLine(AIlineToClear+2, AIcolorToClear)/3.0); - int unlimitedLoop=0; - while (((board[placeToCenter][AIlineToClear]>1000000)||(board[placeToCenter][AIlineToClear+1]>1000000)||(board[placeToCenter][AIlineToClear+2]>1000000))&&(unlimitedLoop<10)) { - unlimitedLoop++; - placeToCenter++; - if (placeToCenter>5) - placeToCenter=0; - } - if(unlimitedLoop>9) { - AIstatus = 0; - } - //cout << ", ptc: " << placeToCenter << ", line: " << AIlineToClear << ", cy: " << cursory; - if (cursory+1>AIlineToClear+2) { - // cout << ", cursory>line+2"; - MoveCursor('S'); - } - if (cursory+1closestTo(AIlineToClear, AIcolorToClear, placeToCenter)) - MoveCursor('W'); - else - if (cursorxclosestTo(AIlineToClear+1, AIcolorToClear, placeToCenter)) - MoveCursor('W'); - else - if (cursorxclosestTo(AIlineToClear+2, AIcolorToClear, placeToCenter)) - MoveCursor('W'); - else - if (cursorx-1)&&(iTemp<7)) + nrOfType[iTemp]++; + } + for (int j=0; j<7; j++) + { + if (nrOfType[j]>max) + { + max = nrOfType[j]; + AIcolorToClear = j; + } + } + return max; +} + +bool BlockGame::horiClearPossible() +{ + //cout << "Start_ horiclear possible" << endl; + int i=13; + bool solutionFound = false; + do + { + if (horiInLine(i)>2) + { + AI_LineOffset = 0; + AIlineToClear = i; + solutionFound = true; + } + i--; + } + while ((!solutionFound)&&(i>0)); + return solutionFound; +} + +//the Line Has Unmoveable Objects witch might stall the AI +bool BlockGame::lineHasGarbage(int line) +{ + for (int i=0; i<6; i++) + if (board[i][line]>1000000) + return true; + return false; +} + +//Types 0..6 in line +int BlockGame::nrOfRealTypes(int line) +{ + //cout << "Start_ nrOfReal" << endl; + int counter = 0; + for (int i=0; i<6; i++) + if ((board[i][line]>-1)&&(board[i][line]<7))counter++; + return counter; +} + +//See if there is a tower +bool BlockGame::ThereIsATower() +{ + //cout << "Start_ there is a tower" << endl; + bool bThereIsATower = false; //Unless proven otherwise! + bool topReached = false; //If we have reached the top + int lineNumber = 0; + bool emptySpacesFound = false; + do + { + if ((emptySpacesFound) && (nrOfRealTypes(lineNumber)>0)&&(nrOfType(lineNumber, -1)>0)) + { + AIlineToClear = lineNumber; + if (lineHasGarbage(lineNumber)) + return false; + else + bThereIsATower = true; + } + else + emptySpacesFound=false; + if ((!emptySpacesFound)&&(nrOfType(lineNumber, -1)>0)) + emptySpacesFound = true; + if (lineNumber<12) + lineNumber++; + else + topReached = true; + } + while ((!bThereIsATower)&&(!topReached)); + //if(bThereIsATower) + //cout << "There is actually a tower" << endl; + return bThereIsATower; +} + +double BlockGame::firstInLine1(int line) +{ + for (int i=0; i<6; i++) + if ((board[i][line]>-1)&&(board[i][line]<7)) + return (double)i; + return 3.0; +} + +//returns the first coordinate of the block of type +double BlockGame::firstInLine(int line, int type) +{ + for (int i=0; i<6; i++) + if (board[i][line]==type) + return (double)i; + return 3.0; +} + +//There in the line shall we move +int BlockGame::closestTo(int line, int place) +{ + if ((int)firstInLine1(line)>place) + return (int)firstInLine1(line)-1; + for (int i=place; i>=0; i--) + { + if ((board[i][line]>-1)&&(board[i][line]<7)) + return i; + } + AIstatus=0; + return place; +} + +//The AI will remove a tower +void BlockGame::AI_ClearTower() +{ + // cout << "AI: ClearTower, line: " << AIlineToClear << endl; + int place = (int)firstInLine(AIlineToClear-1, -1); //Find an empty field to frop a brick into + int xplace = closestTo(AIlineToClear, place); //Find the brick to drop in it + if (cursory+1AIlineToClear) + MoveCursor('S'); + else if (cursorxxplace) + MoveCursor('W'); + else + SwitchAtCursor(); + if (!ThereIsATower()) + AIstatus = 0; +} + +//The AI will try to clear block horisontally +void BlockGame::AI_ClearHori() +{ + // cout << "AI: ClearHori"; + int lowestLine = AIlineToClear; + //AIcolorToClear + bool found =true; + /*for(int i; (i<12)&&(!found);i++) + * { + * if(horiInLine(i)>2) + * { + * int lowestLine = i; + * found = true; + * } + * }*/ + for (int i=0; i<7; i++) + { + if (nrOfType(lowestLine, i)>2) + AIcolorToClear = i; + } + if (found) + { + if (cursory>lowestLine-1) + MoveCursor('S'); + else if (cursory2) + { + int left=0, right=0; + if (board[0][lowestLine]==AIcolorToClear) left++; + if (board[1][lowestLine]==AIcolorToClear) left++; + if (board[2][lowestLine]==AIcolorToClear) left++; + if (board[3][lowestLine]==AIcolorToClear) right++; + if (board[4][lowestLine]==AIcolorToClear) right++; + if (board[5][lowestLine]==AIcolorToClear) right++; + int xplace = 0; + if (leftleft"; + int count=0; + for (int i=0; (i<4)&&(count<1); i++) + if ((board[i][lowestLine]==AIcolorToClear)&&((i==0)||(board[i+1][lowestLine]!=AIcolorToClear))) + { + count++; + xplace = i; + } + } + else + { + // cout << ", left>=right"; + int count=0; + for (int i=3; (i<=5)&&(count<1); i++) + if ((board[i][lowestLine]==AIcolorToClear)&&(board[i-1][lowestLine]!=AIcolorToClear)) + { + count++; + xplace = --i; + } + } + //cout << ", xplace: " << xplace; + if (cursorxxplace) + MoveCursor('W'); + else if (cursorx==xplace) + SwitchAtCursor(); + else + AIstatus = 0; + } + else + AIstatus = 0; + } + else + AIstatus = 0; + //cout << endl; //for debugging +} + +//Test if vertical clear is possible +bool BlockGame::veriClearPossible() +{ + bool found=false; + int colors[7] = {0, 0, 0, 0, 0, 0, 0}; + for (int i=12; (i>0)&&(!found); i--) + { + for (int j=0; j<7; j++) + { + if (nrOfType(i, j)==0) + colors[j]=0; + else if (++colors[j]>2) + { + AIcolorToClear = j; + AIlineToClear = i; + found=true; + } + + } + } + return found; +} + + + +//There in the line shall we move +int BlockGame::closestTo(int line, int type, int place) +{ + if ((int)firstInLine(line, type)>place) + return (int)firstInLine(line, type)-1; + for (int i=place; i>=0; i--) + { + if (board[i][line]==type) + return i; + } + AIstatus=0; + return place; +} + +//The AI will try to clear blocks vertically +void BlockGame::AI_ClearVertical() +{ + // cout << "AI: ClearVeri"; + //First we find the place there we will align the bricks + int placeToCenter = (int)(firstInLine(AIlineToClear, AIcolorToClear)/3.0+firstInLine(AIlineToClear+1, AIcolorToClear)/3.0+firstInLine(AIlineToClear+2, AIcolorToClear)/3.0); + int unlimitedLoop=0; + while (((board[placeToCenter][AIlineToClear]>1000000)||(board[placeToCenter][AIlineToClear+1]>1000000)||(board[placeToCenter][AIlineToClear+2]>1000000))&&(unlimitedLoop<10)) + { + unlimitedLoop++; + placeToCenter++; + if (placeToCenter>5) + placeToCenter=0; + } + if(unlimitedLoop>9) + { + AIstatus = 0; + } + //cout << ", ptc: " << placeToCenter << ", line: " << AIlineToClear << ", cy: " << cursory; + if (cursory+1>AIlineToClear+2) + { + // cout << ", cursory>line+2"; + MoveCursor('S'); + } + if (cursory+1closestTo(AIlineToClear, AIcolorToClear, placeToCenter)) + MoveCursor('W'); + else if (cursorxclosestTo(AIlineToClear+1, AIcolorToClear, placeToCenter)) + MoveCursor('W'); + else if (cursorxclosestTo(AIlineToClear+2, AIcolorToClear, placeToCenter)) + MoveCursor('W'); + else if (cursorxstageClearLimit) && (stageClear) && (!bGameOver)) { - stageCleared[Level] = true; - if(stageScores[Level](&tempBool), sizeof(bool)); - } - for (int i=0;i(&tempUInt32), sizeof(Uint32)); - } - for (int i=0;i(&tempUInt32), sizeof(Uint32)); - } - outfile.close(); - } - setPlayerWon(); - stageButtonStatus = SBstageClear; - } - if ((TowerHeight>12)&&(prevTowerHeight<13)&&(!puzzleMode)) { - //if (SoundEnabled) Mix_PlayChannel(1, heartBeat, 0); - stop+=1000; - } - - if ((TowerHeight>12)&&(!puzzleMode)&&(!bGameOver)) { - bNearDeath = true; - } - - while (nowTime>nrStops*40+gameStartedAt) //Increase stops, till we reach nowTime - { - if (stop>0) { - stop = stop-20; - if (stop<=0) nrPushedPixel=(int)((nowTime-gameStartedAt)/(1000.0*speed)); - } - if (stop<0) - stop = 0; - nrStops++; - } - //If we have static content, we don't raise at all! - if (hasStaticContent()) - stop++; - if ((puzzleMode)&&(!bGameOver)&&BoardEmpty()) { - if (!singlePuzzle) { - if(puzzleCleared[Level]==false) - Stats::getInstance()->addOne("puzzlesSolved"); - puzzleCleared[Level] = true; - ofstream outfile; - stageButtonStatus = SBpuzzleMode; - outfile.open(puzzleSavePath.c_str(), ios::binary |ios::trunc); - if (!outfile) { - cout << "Error writing to file: " << puzzleSavePath << endl; - } - else { - for (int i=0;i(&tempBool), sizeof(bool)); - } - outfile.close(); - } - } - setPlayerWon(); - } - - //increse speed: - if ((nowTime>gameStartedAt+20000*speedLevel)&&(speedLevel <99)&&(!bGameOver)) - { - speed = (baseSpeed*0.9)/((double)speedLevel*0.5); - speedLevel++; - nrPushedPixel=(int)((double)(nowTime-gameStartedAt)/(1000.0*speed)); - } - - - //To prevent the stack from raising a lot then we stop a chain (doesn't work anymore) - if (chain>0) - stop+=1; - //Raises the stack - if ((nowTime>gameStartedAt+nrPushedPixel*1000*speed) && (!bGameOver)&&(!stop)) - while ((nowTime>gameStartedAt+nrPushedPixel*1000*speed)&&(!(puzzleMode))) - PushPixels(); - if (!bGameOver)ClearBlocks(); - - /************************************************************* - Ai stuff - **************************************************************/ - if (bGameOver) { - AIstatus = 0; //Enusres that AI is resetted - } - else - if (AI_Enabled) - if (lastAImove+AI_MoveSpeedgameStartedAt+nrFellDown*140) && (!bGameOver)) FallDown(); - if ((nowTimegameStartedAt+2*60*1000)) { - SetGameOver(); - if(!NoSound && SoundEnabled)Mix_PlayChannel(1,counterFinalChunk,0); - if ((theTopScoresTimeTrial.isHighScore(score))&&(!AI_Enabled)) { - theTopScoresTimeTrial.addScore(name, score); - //new highscore - //Also check if it is better than the best result so far. - string checkFilename = getPathToSaveFiles() + "/bestTTresult"; - ifstream inFile(checkFilename.c_str()); - Uint32 bestResult = 3000; //Never accept a best result under 3000 - if(inFile) - { - inFile >> bestResult; - inFile.close(); - } - if(score>bestResult) - { - string bestFile = getPathToSaveFiles() + "/bestTT"; - theReplay.saveReplay(bestFile); - ofstream outFile(checkFilename.c_str(),ios::trunc); - if(outFile) - outFile << score; - } - } - } - } - if ((!bGameOver)&&(!bReplaying)&&(nowTime>gameStartedAt)) - { - //cout << nowTime << " bigger than " << gameStartedAt << endl; - theReplay.setFrameSecTo(nowTime-gameStartedAt, getPackage()); - } - } - - void BlockGame::Update(int newtick) { - ticks = newtick; - Update(); - } +//Updates evrything, if not called nothing happends +void BlockGame::Update() +{ + Uint32 tempUInt32; + Uint32 nowTime = ticks; //We remember the time, so it doesn't change during this call + if (bReplaying) + { + setBoard(theReplay.getFrameSec((Uint32)(nowTime-gameStartedAt))); + strncpy(name,theReplay.name,30); + if (theReplay.isFinnished((Uint32)(nowTime-gameStartedAt))) + switch (theReplay.getFinalStatus()) + { + case 1: //Winner + bGameOver = true; + hasWonTheGame = true; + break; + case 2: //Looser + case 4: //GameOver + bGameOver = true; + break; + case 3: //draw + bGameOver =true; + bDraw = true; + break; + default: + bGameOver = true; + //Nothing + break; + }; + } +#if NETWORK + if ((!bReplaying)&&(!bNetworkPlayer)) + { +#else + if (!bReplaying) + { +#endif + FindTowerHeight(); + if ((linesCleared-TowerHeight>stageClearLimit) && (stageClear) && (!bGameOver)) + { + stageCleared[Level] = true; + if(stageScores[Level](&tempBool), sizeof(bool)); + } + for (int i=0; i(&tempUInt32), sizeof(Uint32)); + } + for (int i=0; i(&tempUInt32), sizeof(Uint32)); + } + outfile.close(); + } + setPlayerWon(); + stageButtonStatus = SBstageClear; + } + if ((TowerHeight>12)&&(prevTowerHeight<13)&&(!puzzleMode)) + { + //if (SoundEnabled) Mix_PlayChannel(1, heartBeat, 0); + stop+=1000; + } + + if ((TowerHeight>12)&&(!puzzleMode)&&(!bGameOver)) + { + bNearDeath = true; + } + + while (nowTime>nrStops*40+gameStartedAt) //Increase stops, till we reach nowTime + { + if (stop>0) + { + stop = stop-20; + if (stop<=0) nrPushedPixel=(int)((nowTime-gameStartedAt)/(1000.0*speed)); + } + if (stop<0) + stop = 0; + nrStops++; + } + //If we have static content, we don't raise at all! + if (hasStaticContent()) + stop++; + if ((puzzleMode)&&(!bGameOver)&&BoardEmpty()) + { + if (!singlePuzzle) + { + if(puzzleCleared[Level]==false) + Stats::getInstance()->addOne("puzzlesSolved"); + puzzleCleared[Level] = true; + ofstream outfile; + stageButtonStatus = SBpuzzleMode; + outfile.open(puzzleSavePath.c_str(), ios::binary |ios::trunc); + if (!outfile) + { + cout << "Error writing to file: " << puzzleSavePath << endl; + } + else + { + for (int i=0; i(&tempBool), sizeof(bool)); + } + outfile.close(); + } + } + setPlayerWon(); + } + + //increse speed: + if ((nowTime>gameStartedAt+20000*speedLevel)&&(speedLevel <99)&&(!bGameOver)) + { + speed = (baseSpeed*0.9)/((double)speedLevel*0.5); + speedLevel++; + nrPushedPixel=(int)((double)(nowTime-gameStartedAt)/(1000.0*speed)); + } + + + //To prevent the stack from raising a lot then we stop a chain (doesn't work anymore) + if (chain>0) + stop+=1; + //Raises the stack + if ((nowTime>gameStartedAt+nrPushedPixel*1000*speed) && (!bGameOver)&&(!stop)) + while ((nowTime>gameStartedAt+nrPushedPixel*1000*speed)&&(!(puzzleMode))) + PushPixels(); + if (!bGameOver)ClearBlocks(); + + /************************************************************* + Ai stuff + **************************************************************/ + if (bGameOver) + { + AIstatus = 0; //Enusres that AI is resetted + } + else if (AI_Enabled) + if (lastAImove+AI_MoveSpeedgameStartedAt+nrFellDown*140) && (!bGameOver)) FallDown(); + if ((nowTimegameStartedAt+2*60*1000)) + { + SetGameOver(); + if(!NoSound && SoundEnabled)Mix_PlayChannel(1,counterFinalChunk,0); + if ((theTopScoresTimeTrial.isHighScore(score))&&(!AI_Enabled)) + { + theTopScoresTimeTrial.addScore(name, score); + //new highscore + //Also check if it is better than the best result so far. + string checkFilename = getPathToSaveFiles() + "/bestTTresult"; + ifstream inFile(checkFilename.c_str()); + Uint32 bestResult = 3000; //Never accept a best result under 3000 + if(inFile) + { + inFile >> bestResult; + inFile.close(); + } + if(score>bestResult) + { + string bestFile = getPathToSaveFiles() + "/bestTT"; + theReplay.saveReplay(bestFile); + ofstream outFile(checkFilename.c_str(),ios::trunc); + if(outFile) + outFile << score; + } + } + } + } + if ((!bGameOver)&&(!bReplaying)&&(nowTime>gameStartedAt)) + { + //cout << nowTime << " bigger than " << gameStartedAt << endl; + theReplay.setFrameSecTo(nowTime-gameStartedAt, getPackage()); + } +} + +void BlockGame::Update(int newtick) +{ + ticks = newtick; + Update(); +} //////////////////////////////////////////////////////////////////////////////// ///////////////////////// BlockAttack class end //////////////////////////////// //////////////////////////////////////////////////////////////////////////////// diff --git a/source/code/BlockGame.hpp b/source/code/BlockGame.hpp index 5847267..c0d393b 100644 --- a/source/code/BlockGame.hpp +++ b/source/code/BlockGame.hpp @@ -1,27 +1,25 @@ /* - * BlockGame.hpp (this was cut from main.cpp for the overview) - * Copyright (C) 2005 Poul Sander - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * Poul Sander - * R�veh�jvej 36, V. 1111 - * 2800 Kgs. Lyngby - * DENMARK - * blockattack@poulsander.com - */ +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== +*/ #ifndef BLOCKGAME_HPP #define BLOCKGAME_HPP 1 @@ -48,258 +46,259 @@ //////////////////////////////////////////////////////////////////////////////// //The BloackGame class represents a board, score, time etc. for a single player/ //////////////////////////////////////////////////////////////////////////////// -class BlockGame { +class BlockGame +{ private: - int prevTowerHeight; - bool bGarbageFallLeft; + int prevTowerHeight; + bool bGarbageFallLeft; - Uint32 nextGarbageNumber; - Uint32 pushedPixelAt; - Uint32 nrPushedPixel, nrFellDown, nrStops; - bool garbageToBeCleared[7][30]; - Uint32 lastAImove; + Uint32 nextGarbageNumber; + Uint32 pushedPixelAt; + Uint32 nrPushedPixel, nrFellDown, nrStops; + bool garbageToBeCleared[7][30]; + Uint32 lastAImove; - Sint16 AI_LineOffset; //how many lines have changed since command - Uint32 hangTicks; //How many times have hang been decreased? - //int the two following index 0 may NOT be used (what the fuck did I meen?) - Uint8 chainSize[NUMBEROFCHAINS]; //Contains the chains - bool chainUsed[NUMBEROFCHAINS]; //True if the chain is used + Sint16 AI_LineOffset; //how many lines have changed since command + Uint32 hangTicks; //How many times have hang been decreased? + //int the two following index 0 may NOT be used (what the fuck did I meen?) + Uint8 chainSize[NUMBEROFCHAINS]; //Contains the chains + bool chainUsed[NUMBEROFCHAINS]; //True if the chain is used - Uint32 nextRandomNumber; + Uint32 nextRandomNumber; - Uint16 rand2(); - int firstUnusedChain(); + Uint16 rand2(); + int firstUnusedChain(); //public: protected: - int lastCounter; - string strHolder; - bool bDraw; - bool bReplaying; //true if we are watching a replay - #if NETWORK - bool bNetworkPlayer; //must recieve packages from the net - bool bDisconnected; //The player has disconnected - #endif - unsigned int ticks; - Uint32 gameStartedAt; - Uint32 gameEndedAfter; //How long did the game last? - int linesCleared; - int TowerHeight; - BlockGame *garbageTarget; - Sint32 board[7][30]; - int stop; - int speedLevel; - int pixels; - int MovesLeft; - bool timetrial, stageClear, vsMode, puzzleMode; - int Level; //Only used in stageClear and puzzle (not implemented) - int stageClearLimit; //stores number of lines user must clear to win - int topx, topy; - int combo; - int chain; - int cursorx; //stores cursor position - int cursory; // -||- - double speed, baseSpeed; //factor for speed. Lower value = faster gameplay - Uint32 score; - bool bGameOver; - bool hasWonTheGame; - int AI_MoveSpeed; //How often will the computer move? milliseconds - bool AI_Enabled; - - Uint32 handicap; - - - int AIlineToClear; - - short AIstatus; //Status flags: - //0: nothing, 2: clear tower, 3: clear horisontal, 4: clear vertical - //1: make more lines, 5: make 2 lines, 6: make 1 line + int lastCounter; + string strHolder; + bool bDraw; + bool bReplaying; //true if we are watching a replay +#if NETWORK + bool bNetworkPlayer; //must recieve packages from the net + bool bDisconnected; //The player has disconnected +#endif + unsigned int ticks; + Uint32 gameStartedAt; + Uint32 gameEndedAfter; //How long did the game last? + int linesCleared; + int TowerHeight; + BlockGame *garbageTarget; + Sint32 board[7][30]; + int stop; + int speedLevel; + int pixels; + int MovesLeft; + bool timetrial, stageClear, vsMode, puzzleMode; + int Level; //Only used in stageClear and puzzle (not implemented) + int stageClearLimit; //stores number of lines user must clear to win + int topx, topy; + int combo; + int chain; + int cursorx; //stores cursor position + int cursory; // -||- + double speed, baseSpeed; //factor for speed. Lower value = faster gameplay + Uint32 score; + bool bGameOver; + bool hasWonTheGame; + int AI_MoveSpeed; //How often will the computer move? milliseconds + bool AI_Enabled; + + Uint32 handicap; + + + int AIlineToClear; + + short AIstatus; //Status flags: + //0: nothing, 2: clear tower, 3: clear horisontal, 4: clear vertical + //1: make more lines, 5: make 2 lines, 6: make 1 line public: - - char name[30]; - Replay theReplay; //Stores the replay - - //Constructor - BlockGame(); - - //Deconstructor, never really used... game used to crash when called, cause of the way sBoard was created - //It should work now and can be used if we want to assign more players in network games that we need to free later - ~BlockGame(); - - void setGameSpeed(Uint8 globalSpeedLevel); - void setHandicap(Uint8 globalHandicap); - //Set the move speed of the AI based on the aiLevel parameter - //Also enables AI - void setAIlevel(Uint8 aiLevel); - Uint8 getAIlevel(); - - int GetScore(); - int GetHandicap(); - bool isGameOver(); - int GetTopX(); - int GetTopY(); - unsigned int GetGameStartedAt(); - unsigned int GetGameEndedAt(); - bool isTimeTrial(); - bool isStageClear(); - bool isVsMode(); - bool isPuzzleMode(); - int GetLinesCleared(); - int GetStageClearLimit(); - int GetChains(); - int GetPixels(); - int GetSpeedLevel(); - int GetTowerHeight(); - int GetCursorX(); - int GetCursorY(); - void MoveCursorTo(int x, int y); - bool GetIsWinner(); + + char name[30]; + Replay theReplay; //Stores the replay + + //Constructor + BlockGame(); + + //Deconstructor, never really used... game used to crash when called, cause of the way sBoard was created + //It should work now and can be used if we want to assign more players in network games that we need to free later + ~BlockGame(); + + void setGameSpeed(Uint8 globalSpeedLevel); + void setHandicap(Uint8 globalHandicap); + //Set the move speed of the AI based on the aiLevel parameter + //Also enables AI + void setAIlevel(Uint8 aiLevel); + Uint8 getAIlevel(); + + int GetScore(); + int GetHandicap(); + bool isGameOver(); + int GetTopX(); + int GetTopY(); + unsigned int GetGameStartedAt(); + unsigned int GetGameEndedAt(); + bool isTimeTrial(); + bool isStageClear(); + bool isVsMode(); + bool isPuzzleMode(); + int GetLinesCleared(); + int GetStageClearLimit(); + int GetChains(); + int GetPixels(); + int GetSpeedLevel(); + int GetTowerHeight(); + int GetCursorX(); + int GetCursorY(); + void MoveCursorTo(int x, int y); + bool GetIsWinner(); private: #if NETWORK #define garbageStackSize 10 - Uint8 garbageStack[garbageStackSize][3]; //A garbage stack with space for 10 garbage blocks. 0=x,1=y,2=type - int garbageStackUsed; + Uint8 garbageStack[garbageStackSize][3]; //A garbage stack with space for 10 garbage blocks. 0=x,1=y,2=type + int garbageStackUsed; - void emptyGarbageStack(); - bool pushGarbage(Uint8 width, Uint8 height, Uint8 type); + void emptyGarbageStack(); + bool pushGarbage(Uint8 width, Uint8 height, Uint8 type); public: - bool popGarbage(Uint8 *width, Uint8 *height, Uint8 *type); + bool popGarbage(Uint8 *width, Uint8 *height, Uint8 *type); private: #endif public: - //Instead of creating new object new game is called, to prevent memory leaks - void NewGame(int tx, int ty, unsigned int ticks); - void NewTimeTrialGame(int x,int y, unsigned int ticks); - //Starts a new stage game, takes level as input! - void NewStageGame(int level, int tx, int ty,unsigned int ticks); - void NewPuzzleGame(int level, int tx, int ty, unsigned int ticks); - //Replay the current level - void retryLevel(unsigned int ticks); - //Play the next level - void nextLevel(unsigned int ticks); - //Starts new Vs Game (two Player) - void NewVsGame(int tx, int ty, BlockGame *target,unsigned int ticks); - //Starts new Vs Game (two Player) - void NewVsGame(int tx, int ty, BlockGame *target, bool AI,unsigned int ticks); + //Instead of creating new object new game is called, to prevent memory leaks + void NewGame(int tx, int ty, unsigned int ticks); + void NewTimeTrialGame(int x,int y, unsigned int ticks); + //Starts a new stage game, takes level as input! + void NewStageGame(int level, int tx, int ty,unsigned int ticks); + void NewPuzzleGame(int level, int tx, int ty, unsigned int ticks); + //Replay the current level + void retryLevel(unsigned int ticks); + //Play the next level + void nextLevel(unsigned int ticks); + //Starts new Vs Game (two Player) + void NewVsGame(int tx, int ty, BlockGame *target,unsigned int ticks); + //Starts new Vs Game (two Player) + void NewVsGame(int tx, int ty, BlockGame *target, bool AI,unsigned int ticks); private: - //Go in Demonstration mode, no movement - void Demonstration(bool toggle); + //Go in Demonstration mode, no movement + void Demonstration(bool toggle); public: - //We want to play the replay (must have been loaded beforehand) - void playReplay(int tx, int ty, unsigned int ticks); + //We want to play the replay (must have been loaded beforehand) + void playReplay(int tx, int ty, unsigned int ticks); +#if NETWORK + //network play + void playNetwork(int tx, int ty,unsigned int ticks); +#endif + //Prints "winner" and ends game + void setPlayerWon(); + //void SetGameOver(); + #if NETWORK - //network play - void playNetwork(int tx, int ty,unsigned int ticks); + //Sets disconnected: + void setDisconnect(); #endif - //Prints "winner" and ends game - void setPlayerWon(); - //void SetGameOver(); - - #if NETWORK - //Sets disconnected: - void setDisconnect(); - #endif - //Prints "draw" and ends the game - void setDraw(); - //Function to get a boardpackage - boardPackage getPackage(); - //Takes a package and sets the board like it - void setBoard(boardPackage bp); + //Prints "draw" and ends the game + void setDraw(); + //Function to get a boardpackage + boardPackage getPackage(); + //Takes a package and sets the board like it + void setBoard(boardPackage bp); private: - //Test if LineNr is an empty line, returns false otherwise. - bool LineEmpty(int lineNr); - //Test if the entire board is empty (used for Puzzles) - bool BoardEmpty(); - //Anything that the user can't move? In that case Game Over cannot occur - bool hasStaticContent(); - void putStartBlocks(); + //Test if LineNr is an empty line, returns false otherwise. + bool LineEmpty(int lineNr); + //Test if the entire board is empty (used for Puzzles) + bool BoardEmpty(); + //Anything that the user can't move? In that case Game Over cannot occur + bool hasStaticContent(); + void putStartBlocks(); public: - void putStartBlocks(Uint32 n); + void putStartBlocks(Uint32 n); private: - //decreases hang for all hanging blocks and wait for waiting blocks - void ReduceStuff(); + //decreases hang for all hanging blocks and wait for waiting blocks + void ReduceStuff(); public: - //Creates garbage using a given wide and height - bool CreateGarbage(int wide, int height); - //Creates garbage using a given wide and height - bool CreateGreyGarbage(); + //Creates garbage using a given wide and height + bool CreateGarbage(int wide, int height); + //Creates garbage using a given wide and height + bool CreateGreyGarbage(); private: - //Clears garbage, must take one the lower left corner! - int GarbageClearer(int x, int y, int number, bool aLineToClear, int chain); - //Marks garbage that must be cleared - int GarbageMarker(int x, int y); - int FirstGarbageMarker(int x, int y); - //Clear Blocks if 3 or more is alligned (naive implemented) - void ClearBlocks(); + //Clears garbage, must take one the lower left corner! + int GarbageClearer(int x, int y, int number, bool aLineToClear, int chain); + //Marks garbage that must be cleared + int GarbageMarker(int x, int y); + int FirstGarbageMarker(int x, int y); + //Clear Blocks if 3 or more is alligned (naive implemented) + void ClearBlocks(); public: - //prints "Game Over" and ends game - void SetGameOver(); - bool GetAIenabled(); + //prints "Game Over" and ends game + void SetGameOver(); + bool GetAIenabled(); private: - //Moves all peaces a spot down if possible - int FallBlock(int x, int y, int number); - //Makes all Garbage fall one spot - void GarbageFall(); - //Makes the blocks fall (it doesn't test time, this must be done before hand) - void FallDown(); + //Moves all peaces a spot down if possible + int FallBlock(int x, int y, int number); + //Makes all Garbage fall one spot + void GarbageFall(); + //Makes the blocks fall (it doesn't test time, this must be done before hand) + void FallDown(); public: - //Moves the cursor, receaves N,S,E or W as a char an moves as desired - void MoveCursor(char way); - //switches the two blocks at the cursor position, unless game over - void SwitchAtCursor(); - //Generates a new line and moves the field one block up (restart puzzle mode) - void PushLine(); + //Moves the cursor, receaves N,S,E or W as a char an moves as desired + void MoveCursor(char way); + //switches the two blocks at the cursor position, unless game over + void SwitchAtCursor(); + //Generates a new line and moves the field one block up (restart puzzle mode) + void PushLine(); private: - //Pushes a single pixel, so it appears to scrool - void PushPixels(); - //See how high the tower is, saved in integer TowerHeight - void FindTowerHeight(); + //Pushes a single pixel, so it appears to scrool + void PushPixels(); + //See how high the tower is, saved in integer TowerHeight + void FindTowerHeight(); /////////////////////////////////////////////////////////////////////////// /////////////////////////// AI starts here! /////////////////////////////// /////////////////////////////////////////////////////////////////////////// - //First the helpet functions: - int nrOfType(int line, int type); - int AIcolorToClear; - //See if a combo can be made in this line - int horiInLine(int line); - bool horiClearPossible(); - //the Line Has Unmoveable Objects witch might stall the AI - bool lineHasGarbage(int line); - //Types 0..6 in line - int nrOfRealTypes(int line); - //See if there is a tower - bool ThereIsATower(); - double firstInLine1(int line); - //returns the first coordinate of the block of type - double firstInLine(int line, int type); - //There in the line shall we move - int closestTo(int line, int place); - //The AI will remove a tower - void AI_ClearTower(); - //The AI will try to clear block horisontally - void AI_ClearHori(); - //Test if vertical clear is possible - bool veriClearPossible(); - //There in the line shall we move - int closestTo(int line, int type, int place); - //The AI will try to clear blocks vertically - void AI_ClearVertical(); - bool firstLineCreated; - void AI_Move(); + //First the helpet functions: + int nrOfType(int line, int type); + int AIcolorToClear; + //See if a combo can be made in this line + int horiInLine(int line); + bool horiClearPossible(); + //the Line Has Unmoveable Objects witch might stall the AI + bool lineHasGarbage(int line); + //Types 0..6 in line + int nrOfRealTypes(int line); + //See if there is a tower + bool ThereIsATower(); + double firstInLine1(int line); + //returns the first coordinate of the block of type + double firstInLine(int line, int type); + //There in the line shall we move + int closestTo(int line, int place); + //The AI will remove a tower + void AI_ClearTower(); + //The AI will try to clear block horisontally + void AI_ClearHori(); + //Test if vertical clear is possible + bool veriClearPossible(); + //There in the line shall we move + int closestTo(int line, int type, int place); + //The AI will try to clear blocks vertically + void AI_ClearVertical(); + bool firstLineCreated; + void AI_Move(); ////////////////////////////////////////////////////////////////////////// ///////////////////////////// AI ends here! ////////////////////////////// ////////////////////////////////////////////////////////////////////////// private: - //Updates evrything, if not called nothing happends - void Update(); + //Updates evrything, if not called nothing happends + void Update(); public: - void Update(int newtick); + void Update(int newtick); }; //////////////////////////////////////////////////////////////////////////////// ///////////////////////// BlockAttack class end //////////////////////////////// diff --git a/source/code/CppSdlException.cpp b/source/code/CppSdlException.cpp index fbec9e6..c7bb2c0 100644 --- a/source/code/CppSdlException.cpp +++ b/source/code/CppSdlException.cpp @@ -1,36 +1,43 @@ -/* +/* * File: CppSdlException.cpp * Author: poul - * + * * Created on 7. november 2010, 13:19 */ #include "CppSdlException.hpp" -namespace CppSdl { +namespace CppSdl +{ -CppSdlException::CppSdlException(Subsystem subsystem,long errorNumber, std::string msg) { - _errorNumber = errorNumber; - _message = msg; - _subsystem = subsystem; +CppSdlException::CppSdlException(Subsystem subsystem,long errorNumber, std::string msg) +{ + _errorNumber = errorNumber; + _message = msg; + _subsystem = subsystem; } -CppSdlException::CppSdlException(const CppSdlException& orig) { +CppSdlException::CppSdlException(const CppSdlException& orig) +{ } -CppSdlException::~CppSdlException() throw() { +CppSdlException::~CppSdlException() throw() +{ } -const char* CppSdlException::what() const throw() { - return _message.c_str(); +const char* CppSdlException::what() const throw() +{ + return _message.c_str(); } -long CppSdlException::GetErrorNumber() { - return _errorNumber; +long CppSdlException::GetErrorNumber() +{ + return _errorNumber; } -Subsystem CppSdlException::GetSubSystem() { - return _subsystem; +Subsystem CppSdlException::GetSubSystem() +{ + return _subsystem; } } diff --git a/source/code/CppSdlException.hpp b/source/code/CppSdlException.hpp index acc7715..ebf35e2 100644 --- a/source/code/CppSdlException.hpp +++ b/source/code/CppSdlException.hpp @@ -1,9 +1,25 @@ -/* - * File: CppSdlException.hpp - * Author: poul - * - * Created on 7. november 2010, 13:19 - */ +/* +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== +*/ #ifndef _CPPSDLEXCEPTION_HPP #define _CPPSDLEXCEPTION_HPP @@ -18,26 +34,28 @@ enum Subsystem {OTHER,IMAGE,TILE,SPRITE,LAYER,SCREEN }; -namespace CppSdl { -class CppSdlException : std::exception{ +namespace CppSdl +{ +class CppSdlException : std::exception +{ public: - //CppSdlException(); - /** - * Constructor for making a fully CppSdl compliant expection - * @param subsystem Can be: OTHER,IMAGE,TILE,SPRITE,LAYER,SCREEN - * @param errorNumber 1=Data error, 2=Invalid, 3=Missingfile, 4=null pointer - * @param msg Human readable error message. - */ - CppSdlException(Subsystem subsystem, long errorNumber, std::string msg); - CppSdlException(const CppSdlException& orig); - virtual ~CppSdlException() throw(); - virtual const char* what() const throw(); - long GetErrorNumber(); - Subsystem GetSubSystem(); + //CppSdlException(); + /** + * Constructor for making a fully CppSdl compliant expection + * @param subsystem Can be: OTHER,IMAGE,TILE,SPRITE,LAYER,SCREEN + * @param errorNumber 1=Data error, 2=Invalid, 3=Missingfile, 4=null pointer + * @param msg Human readable error message. + */ + CppSdlException(Subsystem subsystem, long errorNumber, std::string msg); + CppSdlException(const CppSdlException& orig); + virtual ~CppSdlException() throw(); + virtual const char* what() const throw(); + long GetErrorNumber(); + Subsystem GetSubSystem(); private: - std::string _message; - long _errorNumber; - Subsystem _subsystem; + std::string _message; + long _errorNumber; + Subsystem _subsystem; }; diff --git a/source/code/CppSdlImageHolder.cpp b/source/code/CppSdlImageHolder.cpp index 46b0916..1b93032 100644 --- a/source/code/CppSdlImageHolder.cpp +++ b/source/code/CppSdlImageHolder.cpp @@ -1,187 +1,202 @@ -/* +/* * File: CppSdlImageHolder.cpp * Author: poul - * + * * Created on 29. september 2010, 19:46 */ #include "CppSdlImageHolder.hpp" #include "SDL_image.h" -namespace CppSdl { - -CppSdlImageHolder::CppSdlImageHolder() { - data = NULL; - counter = new int; - (*counter)=1; -} - -CppSdlImageHolder::CppSdlImageHolder(std::string filename) { - data = IMG_Load(filename.c_str()); - if(!data) - { - //Here we should throw an exception - CppSdlException e(IMAGE,CPPSDL_ERROR_MISSINGFILE,"Could not read file \""+filename+"\""); - throw e; - } - SDL_GetClipRect(data,&area); - OptimizeForBlit(); - counter = new int; - *counter=1; -} - -CppSdlImageHolder::CppSdlImageHolder(const CppSdlImageHolder& orig) { - //Just take the data from the original. This is technically wrong but adds a little performance. - data = orig.data; - area = orig.area; - if(orig.counter) { - counter = orig.counter; - (*counter)++; - } -} - -CppSdlImageHolder& CppSdlImageHolder::operator =(const CppSdlImageHolder& rhs) { - // Check for self-assignment! - if (this == &rhs) // Same object? - return *this; // Yes, so skip assignment, and just return *this. - MakeNull(); - data = rhs.data; - area = rhs.area; - if(rhs.counter) { - counter = rhs.counter; - (*counter)++; - } - return *this; -} - -CppSdlImageHolder::CppSdlImageHolder(char* rawdata, int datasize) { - SDL_RWops *rw = SDL_RWFromMem (rawdata, datasize); - - //The above might fail and return null. - if(!rw) - { - CppSdlException e(IMAGE,CPPSDL_ERROR_NULLPOINTER, "Could not read raw data"); - throw e; - } - - data = IMG_Load_RW(rw,true); //the second argument tells the function to free RWops - - if(!data) - { - CppSdlException e(IMAGE,CPPSDL_ERROR_DATA,"Could not convert raw data to image"); - throw e; - } - - SDL_GetClipRect(data,&area); - OptimizeForBlit(); - counter = new int; - *counter = 1; -} - -CppSdlImageHolder::~CppSdlImageHolder() { - if(!counter) - return; //There are no counter, so already freed - MakeNull(); - if(*counter == 0) { - delete counter; - counter = NULL; - } +namespace CppSdl +{ + +CppSdlImageHolder::CppSdlImageHolder() +{ + data = NULL; + counter = new int; + (*counter)=1; +} + +CppSdlImageHolder::CppSdlImageHolder(std::string filename) +{ + data = IMG_Load(filename.c_str()); + if(!data) + { + //Here we should throw an exception + CppSdlException e(IMAGE,CPPSDL_ERROR_MISSINGFILE,"Could not read file \""+filename+"\""); + throw e; + } + SDL_GetClipRect(data,&area); + OptimizeForBlit(); + counter = new int; + *counter=1; +} + +CppSdlImageHolder::CppSdlImageHolder(const CppSdlImageHolder& orig) +{ + //Just take the data from the original. This is technically wrong but adds a little performance. + data = orig.data; + area = orig.area; + if(orig.counter) + { + counter = orig.counter; + (*counter)++; + } +} + +CppSdlImageHolder& CppSdlImageHolder::operator =(const CppSdlImageHolder& rhs) +{ + // Check for self-assignment! + if (this == &rhs) // Same object? + return *this; // Yes, so skip assignment, and just return *this. + MakeNull(); + data = rhs.data; + area = rhs.area; + if(rhs.counter) + { + counter = rhs.counter; + (*counter)++; + } + return *this; +} + +CppSdlImageHolder::CppSdlImageHolder(char* rawdata, int datasize) +{ + SDL_RWops *rw = SDL_RWFromMem (rawdata, datasize); + + //The above might fail and return null. + if(!rw) + { + CppSdlException e(IMAGE,CPPSDL_ERROR_NULLPOINTER, "Could not read raw data"); + throw e; + } + + data = IMG_Load_RW(rw,true); //the second argument tells the function to free RWops + + if(!data) + { + CppSdlException e(IMAGE,CPPSDL_ERROR_DATA,"Could not convert raw data to image"); + throw e; + } + + SDL_GetClipRect(data,&area); + OptimizeForBlit(); + counter = new int; + *counter = 1; +} + +CppSdlImageHolder::~CppSdlImageHolder() +{ + if(!counter) + return; //There are no counter, so already freed + MakeNull(); + if(*counter == 0) + { + delete counter; + counter = NULL; + } } SDL_Surface* CppSdlImageHolder::GetRawDataInsecure() { - Initialized(); - return data; + Initialized(); + return data; } Uint32 CppSdlImageHolder::GetWidth() { - if(IsNull()) - return 0; - return area.w; + if(IsNull()) + return 0; + return area.w; } Uint32 CppSdlImageHolder::GetHeight() { - if(IsNull()) - return 0; - return area.h; + if(IsNull()) + return 0; + return area.h; } void CppSdlImageHolder::Cut(Uint32 x, Uint32 y, Sint32 w = -1, Sint32 h = -1) { - Initialized(); - if(w<0) - { - w = GetWidth() - x; - } - if(h<0) - { - h = GetHeight() - y; - } - if(x+w>GetWidth()) - { - //throw exception - } - if(y+h>GetHeight()) - { - //throw exception - } - if(x<0 || x>GetWidth()) - { - //throw exception - } - if(y<0 || y>GetHeight()) - { - //throw exception - } - area.x += x; - area.y += y; - area.w = w; - area.h = h; -} - -void CppSdlImageHolder::PaintTo(SDL_Surface* target, int x, int y) { - static SDL_Rect dest; //static for reuse - if(IsNull()) - return; - dest.x = x; - dest.y = y; - SDL_BlitSurface(data,&area, target,&dest); -} - -void CppSdlImageHolder::OptimizeForBlit(bool allowAlpha) { - static SDL_Surface *tmp; - Initialized(); - if(allowAlpha) - tmp = SDL_DisplayFormatAlpha(data); - else - tmp = SDL_DisplayFormat(data); - SDL_FreeSurface(data); - data = tmp; -} - -void CppSdlImageHolder::Initialized() { - if(data == NULL) - throw(CppSdlException(IMAGE,CPPSDL_ERROR_NULLPOINTER,"ImageHolder used uninitialized!")); -} - -bool CppSdlImageHolder::IsNull() { - if(data == NULL || counter == NULL) - return true; - else - return false; -} - -void CppSdlImageHolder::MakeNull() { - if(IsNull()) - return; - (*counter)--; - if(*counter == 0 && data != NULL) - { - SDL_FreeSurface(data); - data = NULL; - } + Initialized(); + if(w<0) + { + w = GetWidth() - x; + } + if(h<0) + { + h = GetHeight() - y; + } + if(x+w>GetWidth()) + { + //throw exception + } + if(y+h>GetHeight()) + { + //throw exception + } + if(x<0 || x>GetWidth()) + { + //throw exception + } + if(y<0 || y>GetHeight()) + { + //throw exception + } + area.x += x; + area.y += y; + area.w = w; + area.h = h; +} + +void CppSdlImageHolder::PaintTo(SDL_Surface* target, int x, int y) +{ + static SDL_Rect dest; //static for reuse + if(IsNull()) + return; + dest.x = x; + dest.y = y; + SDL_BlitSurface(data,&area, target,&dest); +} + +void CppSdlImageHolder::OptimizeForBlit(bool allowAlpha) +{ + static SDL_Surface *tmp; + Initialized(); + if(allowAlpha) + tmp = SDL_DisplayFormatAlpha(data); + else + tmp = SDL_DisplayFormat(data); + SDL_FreeSurface(data); + data = tmp; +} + +void CppSdlImageHolder::Initialized() +{ + if(data == NULL) + throw(CppSdlException(IMAGE,CPPSDL_ERROR_NULLPOINTER,"ImageHolder used uninitialized!")); +} + +bool CppSdlImageHolder::IsNull() +{ + if(data == NULL || counter == NULL) + return true; + else + return false; +} + +void CppSdlImageHolder::MakeNull() +{ + if(IsNull()) + return; + (*counter)--; + if(*counter == 0 && data != NULL) + { + SDL_FreeSurface(data); + data = NULL; + } } } diff --git a/source/code/CppSdlImageHolder.hpp b/source/code/CppSdlImageHolder.hpp index ad42bfb..bb94c7b 100644 --- a/source/code/CppSdlImageHolder.hpp +++ b/source/code/CppSdlImageHolder.hpp @@ -1,9 +1,25 @@ -/* - * File: CppSdlImageHolder.hpp - * Author: poul - * - * Created on 29. september 2010, 19:46 - */ +/* +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== +*/ #ifndef _CPPSDLIMAGEHOLDER_HPP #define _CPPSDLIMAGEHOLDER_HPP @@ -12,71 +28,73 @@ #include #include "CppSdlException.hpp" -namespace CppSdl { +namespace CppSdl +{ -class CppSdlImageHolder { +class CppSdlImageHolder +{ public: - /** - * Creates a nulled ImageHolder (without data) - */ - CppSdlImageHolder(); - /** - * Creates an image from a file - * @param filename to be loaded - */ - CppSdlImageHolder(std::string filename); - /** - * Creates a copy. The new copy shares raw data with the original but is otherwise independent. - * @param orig - */ - CppSdlImageHolder(const CppSdlImageHolder& orig); - CppSdlImageHolder(char *rawdata, int datasize); - virtual ~CppSdlImageHolder(); - /** - * This gives access direct access to the internal data. - * Careful, the data might be shared between multiple ImageHolders, - * chaing one will change them all. - * @return A pointer - */ - SDL_Surface *GetRawDataInsecure(); - CppSdlImageHolder & operator=(const CppSdlImageHolder &rhs); - void Cut(Uint32 x,Uint32 y,Sint32 w,Sint32 h); - /** - * The width of the image - * 0 if the image is nulled - * @return The width of the image in pizels - */ - Uint32 GetWidth(); - /** - * The height of the image - * 0 if the image is nulled - * @return The height of the image - */ - Uint32 GetHeight(); - /** - * Draws an image to surface at a given position. - * If the image is nulled nothing is drawn - * @param target Destination surface - * @param x horizontal placement on destination surface - * @param y vertical placement on destination surface - */ - void PaintTo(SDL_Surface *target, int x, int y); - void OptimizeForBlit(bool allowAlpha = true); - /** - * Tests if there are data in the object - * @return true if where are data in the object - */ - bool IsNull(); - /** - * Removes the data in the object. - * Once all ImageHolders pointing to the same data has been freed the internal data will be freed too - */ - void MakeNull(); + /** + * Creates a nulled ImageHolder (without data) + */ + CppSdlImageHolder(); + /** + * Creates an image from a file + * @param filename to be loaded + */ + CppSdlImageHolder(std::string filename); + /** + * Creates a copy. The new copy shares raw data with the original but is otherwise independent. + * @param orig + */ + CppSdlImageHolder(const CppSdlImageHolder& orig); + CppSdlImageHolder(char *rawdata, int datasize); + virtual ~CppSdlImageHolder(); + /** + * This gives access direct access to the internal data. + * Careful, the data might be shared between multiple ImageHolders, + * chaing one will change them all. + * @return A pointer + */ + SDL_Surface *GetRawDataInsecure(); + CppSdlImageHolder & operator=(const CppSdlImageHolder &rhs); + void Cut(Uint32 x,Uint32 y,Sint32 w,Sint32 h); + /** + * The width of the image + * 0 if the image is nulled + * @return The width of the image in pizels + */ + Uint32 GetWidth(); + /** + * The height of the image + * 0 if the image is nulled + * @return The height of the image + */ + Uint32 GetHeight(); + /** + * Draws an image to surface at a given position. + * If the image is nulled nothing is drawn + * @param target Destination surface + * @param x horizontal placement on destination surface + * @param y vertical placement on destination surface + */ + void PaintTo(SDL_Surface *target, int x, int y); + void OptimizeForBlit(bool allowAlpha = true); + /** + * Tests if there are data in the object + * @return true if where are data in the object + */ + bool IsNull(); + /** + * Removes the data in the object. + * Once all ImageHolders pointing to the same data has been freed the internal data will be freed too + */ + void MakeNull(); private: - void Initialized(); //throws an exception if *data is null - int *counter; - SDL_Rect area; - SDL_Surface *data; + void Initialized(); //throws an exception if *data is null + int *counter; + SDL_Rect area; + SDL_Surface *data; }; } diff --git a/source/code/Libs/NFont.cpp b/source/code/Libs/NFont.cpp index 55a04cd..4522600 100644 --- a/source/code/Libs/NFont.cpp +++ b/source/code/Libs/NFont.cpp @@ -5,9 +5,9 @@ by Jonathan Dearborn 2-4-10 License: The short: - Use it however you'd like, but keep the copyright and license notice + Use it however you'd like, but keep the copyright and license notice whenever these files or parts of them are distributed in uncompiled form. - + The long: Copyright (c) 2010 Jonathan Dearborn @@ -40,276 +40,278 @@ NFont::AnimData NFont::data; // Static setters void NFont::setAnimData(void* data) { - NFont::data.userVar = data; + NFont::data.userVar = data; } void NFont::setBuffer(unsigned int size) { - delete[] buffer; - if(size > 0) - buffer = new char[size]; - else - buffer = new char[1024]; + delete[] buffer; + if(size > 0) + buffer = new char[size]; + else + buffer = new char[1024]; } // Static functions char* NFont::copyString(const char* c) { - if(c == NULL) return NULL; + if(c == NULL) return NULL; - int count = 0; - for(; c[count] != '\0'; count++); + int count = 0; + for(; c[count] != '\0'; count++); - char* result = new char[count+1]; + char* result = new char[count+1]; - for(int i = 0; i < count; i++) - { - result[i] = c[i]; - } + for(int i = 0; i < count; i++) + { + result[i] = c[i]; + } - result[count] = '\0'; - return result; + result[count] = '\0'; + return result; } Uint32 NFont::getPixel(SDL_Surface *Surface, int x, int y) // No Alpha? { - Uint8* bits; - Uint32 bpp; - - if(x < 0 || x >= Surface->w) - return 0; // Best I could do for errors - - bpp = Surface->format->BytesPerPixel; - bits = ((Uint8*)Surface->pixels) + y*Surface->pitch + x*bpp; - - switch (bpp) - { - case 1: - return *((Uint8*)Surface->pixels + y * Surface->pitch + x); - break; - case 2: - return *((Uint16*)Surface->pixels + y * Surface->pitch/2 + x); - break; - case 3: - // Endian-correct, but slower - Uint8 r, g, b; - r = *((bits)+Surface->format->Rshift/8); - g = *((bits)+Surface->format->Gshift/8); - b = *((bits)+Surface->format->Bshift/8); - return SDL_MapRGB(Surface->format, r, g, b); - break; - case 4: - return *((Uint32*)Surface->pixels + y * Surface->pitch/4 + x); - break; - } - - return 0; // Best I could do for errors + Uint8* bits; + Uint32 bpp; + + if(x < 0 || x >= Surface->w) + return 0; // Best I could do for errors + + bpp = Surface->format->BytesPerPixel; + bits = ((Uint8*)Surface->pixels) + y*Surface->pitch + x*bpp; + + switch (bpp) + { + case 1: + return *((Uint8*)Surface->pixels + y * Surface->pitch + x); + break; + case 2: + return *((Uint16*)Surface->pixels + y * Surface->pitch/2 + x); + break; + case 3: + // Endian-correct, but slower + Uint8 r, g, b; + r = *((bits)+Surface->format->Rshift/8); + g = *((bits)+Surface->format->Gshift/8); + b = *((bits)+Surface->format->Bshift/8); + return SDL_MapRGB(Surface->format, r, g, b); + break; + case 4: + return *((Uint32*)Surface->pixels + y * Surface->pitch/4 + x); + break; + } + + return 0; // Best I could do for errors } SDL_Rect NFont::rectUnion(const SDL_Rect& A, const SDL_Rect& B) { - Sint16 x,x2,y,y2; - x = MIN(A.x, B.x); - y = MIN(A.y, B.y); - x2 = MAX(A.x+A.w, B.x+B.w); - y2 = MAX(A.y+A.h, B.y+B.h); - SDL_Rect result = {x, y, x2 - x, y2 - y}; - return result; + Sint16 x,x2,y,y2; + x = MIN(A.x, B.x); + y = MIN(A.y, B.y); + x2 = MAX(A.x+A.w, B.x+B.w); + y2 = MAX(A.y+A.h, B.y+B.h); + SDL_Rect result = {x, y, x2 - x, y2 - y}; + return result; } SDL_Surface* NFont::copySurface(SDL_Surface *Surface) { - return SDL_ConvertSurface(Surface, Surface->format, Surface->flags); + return SDL_ConvertSurface(Surface, Surface->format, Surface->flags); } SDL_Surface* NFont::verticalGradient(SDL_Surface* targetSurface, Uint32 top, Uint32 bottom, int heightAdjust) { - SDL_Surface* surface = targetSurface; - if(surface == NULL) - return NULL; - - Uint8 tr, tg, tb; - - SDL_GetRGB(top, surface->format, &tr, &tg, &tb); - - Uint8 br, bg, bb; - - SDL_GetRGB(bottom, surface->format, &br, &bg, &bb); - - bool useCK = (surface->flags & SDL_SRCALPHA) != SDL_SRCALPHA; // colorkey if no alpha - Uint32 colorkey = surface->format->colorkey; - - Uint8 r, g, b, a; - float ratio; - Uint32 color; - int temp; - - for (int x = 0, y = 0; y < surface->h; x++) - { - if (x >= surface->w) - { - x = 0; - y++; - - if (y >= surface->h) - break; - } - - ratio = (y - 2)/float(surface->h - heightAdjust); // the neg 3s are for full color at top and bottom - - if(!useCK) - { - color = getPixel(surface, x, y); - SDL_GetRGBA(color, surface->format, &r, &g, &b, &a); // just getting alpha - } - else - a = SDL_ALPHA_OPAQUE; - - // Get and clamp the new values - temp = int(tr*(1-ratio) + br*ratio); - r = temp < 0? 0 : temp > 255? 255 : temp; - - temp = int(tg*(1-ratio) + bg*ratio); - g = temp < 0? 0 : temp > 255? 255 : temp; - - temp = int(tb*(1-ratio) + bb*ratio); - b = temp < 0? 0 : temp > 255? 255 : temp; - - - color = SDL_MapRGBA(surface->format, r, g, b, a); - - - if(useCK) - { - if(getPixel(surface, x, y) == colorkey) - continue; - if(color == colorkey) - color == 0? color++ : color--; - } - - // make sure it isn't pink - if(color == SDL_MapRGBA(surface->format, 0xFF, 0, 0xFF, a)) - color--; - if(getPixel(surface, x, y) == SDL_MapRGBA(surface->format, 0xFF, 0, 0xFF, SDL_ALPHA_OPAQUE)) - continue; - - int bpp = surface->format->BytesPerPixel; - Uint8* bits = ((Uint8 *)surface->pixels) + y*surface->pitch + x*bpp; - - /* Set the pixel */ - switch(bpp) { - case 1: - *((Uint8 *)(bits)) = (Uint8)color; - break; - case 2: - *((Uint16 *)(bits)) = (Uint16)color; - break; - case 3: { /* Format/endian independent */ - r = (color >> surface->format->Rshift) & 0xFF; - g = (color >> surface->format->Gshift) & 0xFF; - b = (color >> surface->format->Bshift) & 0xFF; - *((bits)+surface->format->Rshift/8) = r; - *((bits)+surface->format->Gshift/8) = g; - *((bits)+surface->format->Bshift/8) = b; - } - break; - case 4: - *((Uint32 *)(bits)) = (Uint32)color; - break; - } - - } - return surface; + SDL_Surface* surface = targetSurface; + if(surface == NULL) + return NULL; + + Uint8 tr, tg, tb; + + SDL_GetRGB(top, surface->format, &tr, &tg, &tb); + + Uint8 br, bg, bb; + + SDL_GetRGB(bottom, surface->format, &br, &bg, &bb); + + bool useCK = (surface->flags & SDL_SRCALPHA) != SDL_SRCALPHA; // colorkey if no alpha + Uint32 colorkey = surface->format->colorkey; + + Uint8 r, g, b, a; + float ratio; + Uint32 color; + int temp; + + for (int x = 0, y = 0; y < surface->h; x++) + { + if (x >= surface->w) + { + x = 0; + y++; + + if (y >= surface->h) + break; + } + + ratio = (y - 2)/float(surface->h - heightAdjust); // the neg 3s are for full color at top and bottom + + if(!useCK) + { + color = getPixel(surface, x, y); + SDL_GetRGBA(color, surface->format, &r, &g, &b, &a); // just getting alpha + } + else + a = SDL_ALPHA_OPAQUE; + + // Get and clamp the new values + temp = int(tr*(1-ratio) + br*ratio); + r = temp < 0? 0 : temp > 255? 255 : temp; + + temp = int(tg*(1-ratio) + bg*ratio); + g = temp < 0? 0 : temp > 255? 255 : temp; + + temp = int(tb*(1-ratio) + bb*ratio); + b = temp < 0? 0 : temp > 255? 255 : temp; + + + color = SDL_MapRGBA(surface->format, r, g, b, a); + + + if(useCK) + { + if(getPixel(surface, x, y) == colorkey) + continue; + if(color == colorkey) + color == 0? color++ : color--; + } + + // make sure it isn't pink + if(color == SDL_MapRGBA(surface->format, 0xFF, 0, 0xFF, a)) + color--; + if(getPixel(surface, x, y) == SDL_MapRGBA(surface->format, 0xFF, 0, 0xFF, SDL_ALPHA_OPAQUE)) + continue; + + int bpp = surface->format->BytesPerPixel; + Uint8* bits = ((Uint8 *)surface->pixels) + y*surface->pitch + x*bpp; + + /* Set the pixel */ + switch(bpp) + { + case 1: + *((Uint8 *)(bits)) = (Uint8)color; + break; + case 2: + *((Uint16 *)(bits)) = (Uint16)color; + break; + case 3: /* Format/endian independent */ + { + r = (color >> surface->format->Rshift) & 0xFF; + g = (color >> surface->format->Gshift) & 0xFF; + b = (color >> surface->format->Bshift) & 0xFF; + *((bits)+surface->format->Rshift/8) = r; + *((bits)+surface->format->Gshift/8) = g; + *((bits)+surface->format->Bshift/8) = b; + } + break; + case 4: + *((Uint32 *)(bits)) = (Uint32)color; + break; + } + + } + return surface; } // Constructors NFont::NFont() { - init(); + init(); } NFont::NFont(SDL_Surface* src) { - init(); - load(src); + init(); + load(src); } NFont::NFont(SDL_Surface* dest, SDL_Surface* src) { - init(); - load(src); - setDest(dest); + init(); + load(src); + setDest(dest); } #ifdef NFONT_USE_TTF NFont::NFont(TTF_Font* ttf, SDL_Color fg) { - init(); - load(ttf, fg); + init(); + load(ttf, fg); } NFont::NFont(TTF_Font* ttf, SDL_Color fg, SDL_Color bg) { - init(); - load(ttf, fg, bg); + init(); + load(ttf, fg, bg); } NFont::NFont(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style) { - init(); - load(filename_ttf, pointSize, fg, style); + init(); + load(filename_ttf, pointSize, fg, style); } NFont::NFont(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_Color bg, int style) { - init(); - load(filename_ttf, pointSize, fg, bg, style); + init(); + load(filename_ttf, pointSize, fg, bg, style); } NFont::NFont(SDL_Surface* dest, TTF_Font* ttf, SDL_Color fg) { - init(); - load(ttf, fg); - setDest(dest); + init(); + load(ttf, fg); + setDest(dest); } NFont::NFont(SDL_Surface* dest, TTF_Font* ttf, SDL_Color fg, SDL_Color bg) { - init(); - load(ttf, fg, bg); - setDest(dest); + init(); + load(ttf, fg, bg); + setDest(dest); } NFont::NFont(SDL_Surface* dest, const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style) { - init(); - load(filename_ttf, pointSize, fg, style); - setDest(dest); + init(); + load(filename_ttf, pointSize, fg, style); + setDest(dest); } NFont::NFont(SDL_Surface* dest, const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_Color bg, int style) { - init(); - load(filename_ttf, pointSize, fg, bg, style); - setDest(dest); + init(); + load(filename_ttf, pointSize, fg, bg, style); + setDest(dest); } #endif void NFont::init() { - src = NULL; - dest = NULL; + src = NULL; + dest = NULL; + + maxPos = 0; - maxPos = 0; + height = 0; // ascent+descent - height = 0; // ascent+descent + maxWidth = 0; + baseline = 0; + ascent = 0; + descent = 0; - maxWidth = 0; - baseline = 0; - ascent = 0; - descent = 0; + lineSpacing = 0; + letterSpacing = 0; - lineSpacing = 0; - letterSpacing = 0; - - if(buffer == NULL) - buffer = new char[1024]; + if(buffer == NULL) + buffer = new char[1024]; } NFont::~NFont() @@ -319,257 +321,257 @@ NFont::~NFont() // Loading bool NFont::load(SDL_Surface* FontSurface) { - src = FontSurface; - if (src == NULL) - { - printf("\n ERROR: NFont given a NULL surface\n"); - return false; - } - - int x = 1, i = 0; - - // memset would be faster - for(int j = 0; j < 256; j++) - { - charWidth[j] = 0; - charPos[j] = 0; - } - - SDL_LockSurface(src); - - Uint32 pixel = SDL_MapRGB(src->format, 255, 0, 255); // pink pixel - - maxWidth = 0; - - // Get the character positions and widths - while (x < src->w) - { - if(getPixel(src, x, 0) != pixel) - { - charPos[i] = x; - charWidth[i] = x; - while(x < src->w && getPixel(src, x, 0) != pixel) - x++; - charWidth[i] = x - charWidth[i]; - if(charWidth[i] > maxWidth) - maxWidth = charWidth[i]; - i++; - } - - x++; - } - - maxPos = x - 1; - - - pixel = getPixel(src, 0, src->h - 1); - int j; - setBaseline(); - - // Get the max ascent - j = 1; - while(j < baseline && j < src->h) - { - x = 0; - while(x < src->w) - { - if(getPixel(src, x, j) != pixel) - { - ascent = baseline - j; - j = src->h; - break; - } - x++; - } - j++; - } - - // Get the max descent - j = src->h - 1; - while(j > 0 && j > baseline) - { - x = 0; - while(x < src->w) - { - if(getPixel(src, x, j) != pixel) - { - descent = j - baseline+1; - j = 0; - break; - } - x++; - } - j--; - } - - - height = ascent + descent; - - - if((src->flags & SDL_SRCALPHA) != SDL_SRCALPHA) - { - pixel = getPixel(src, 0, src->h - 1); - SDL_UnlockSurface(src); - SDL_SetColorKey(src, SDL_SRCCOLORKEY, pixel); - } - else - SDL_UnlockSurface(src); - - return true; + src = FontSurface; + if (src == NULL) + { + printf("\n ERROR: NFont given a NULL surface\n"); + return false; + } + + int x = 1, i = 0; + + // memset would be faster + for(int j = 0; j < 256; j++) + { + charWidth[j] = 0; + charPos[j] = 0; + } + + SDL_LockSurface(src); + + Uint32 pixel = SDL_MapRGB(src->format, 255, 0, 255); // pink pixel + + maxWidth = 0; + + // Get the character positions and widths + while (x < src->w) + { + if(getPixel(src, x, 0) != pixel) + { + charPos[i] = x; + charWidth[i] = x; + while(x < src->w && getPixel(src, x, 0) != pixel) + x++; + charWidth[i] = x - charWidth[i]; + if(charWidth[i] > maxWidth) + maxWidth = charWidth[i]; + i++; + } + + x++; + } + + maxPos = x - 1; + + + pixel = getPixel(src, 0, src->h - 1); + int j; + setBaseline(); + + // Get the max ascent + j = 1; + while(j < baseline && j < src->h) + { + x = 0; + while(x < src->w) + { + if(getPixel(src, x, j) != pixel) + { + ascent = baseline - j; + j = src->h; + break; + } + x++; + } + j++; + } + + // Get the max descent + j = src->h - 1; + while(j > 0 && j > baseline) + { + x = 0; + while(x < src->w) + { + if(getPixel(src, x, j) != pixel) + { + descent = j - baseline+1; + j = 0; + break; + } + x++; + } + j--; + } + + + height = ascent + descent; + + + if((src->flags & SDL_SRCALPHA) != SDL_SRCALPHA) + { + pixel = getPixel(src, 0, src->h - 1); + SDL_UnlockSurface(src); + SDL_SetColorKey(src, SDL_SRCCOLORKEY, pixel); + } + else + SDL_UnlockSurface(src); + + return true; } bool NFont::load(SDL_Surface* destSurface, SDL_Surface* FontSurface) { - setDest(destSurface); - return load(FontSurface); + setDest(destSurface); + return load(FontSurface); } #ifdef NFONT_USE_TTF bool NFont::load(TTF_Font* ttf, SDL_Color fg, SDL_Color bg) { - if(ttf == NULL) - return false; - SDL_Surface* surfs[127 - 33]; - int width = 0; - int height = 0; - - char buff[2]; - buff[1] = '\0'; - for(int i = 0; i < 127 - 33; i++) - { - buff[0] = i + 33; - surfs[i] = TTF_RenderText_Shaded(ttf, buff, fg, bg); - width += surfs[i]->w; - height = (height < surfs[i]->h)? surfs[i]->h : height; - } - - #if SDL_BYTEORDER == SDL_BIG_ENDIAN - SDL_Surface* result = SDL_CreateRGBSurface(SDL_SWSURFACE,width + 127 - 33 + 1,height,24, 0xFF0000, 0x00FF00, 0x0000FF, 0); - #else - SDL_Surface* result = SDL_CreateRGBSurface(SDL_SWSURFACE,width + 127 - 33 + 1,height,24, 0x0000FF, 0x00FF00, 0xFF0000, 0); - #endif - Uint32 pink = SDL_MapRGB(result->format, 255, 0, 255); - Uint32 bgcolor = SDL_MapRGB(result->format, bg.r, bg.g, bg.b); - - SDL_Rect pixel = {1, 0, 1, 1}; - SDL_Rect line = {1, 0, 1, result->h}; - - int x = 1; - SDL_Rect dest = {x, 0, 0, 0}; - for(int i = 0; i < 127 - 33; i++) - { - pixel.x = line.x = x-1; - SDL_FillRect(result, &line, bgcolor); - SDL_FillRect(result, &pixel, pink); - - SDL_BlitSurface(surfs[i], NULL, result, &dest); - - x += surfs[i]->w + 1; - dest.x = x; - - SDL_FreeSurface(surfs[i]); - } - pixel.x = line.x = x-1; - SDL_FillRect(result, &line, bgcolor); - SDL_FillRect(result, &pixel, pink); - - return load(result); + if(ttf == NULL) + return false; + SDL_Surface* surfs[127 - 33]; + int width = 0; + int height = 0; + + char buff[2]; + buff[1] = '\0'; + for(int i = 0; i < 127 - 33; i++) + { + buff[0] = i + 33; + surfs[i] = TTF_RenderText_Shaded(ttf, buff, fg, bg); + width += surfs[i]->w; + height = (height < surfs[i]->h)? surfs[i]->h : height; + } + +#if SDL_BYTEORDER == SDL_BIG_ENDIAN + SDL_Surface* result = SDL_CreateRGBSurface(SDL_SWSURFACE,width + 127 - 33 + 1,height,24, 0xFF0000, 0x00FF00, 0x0000FF, 0); +#else + SDL_Surface* result = SDL_CreateRGBSurface(SDL_SWSURFACE,width + 127 - 33 + 1,height,24, 0x0000FF, 0x00FF00, 0xFF0000, 0); +#endif + Uint32 pink = SDL_MapRGB(result->format, 255, 0, 255); + Uint32 bgcolor = SDL_MapRGB(result->format, bg.r, bg.g, bg.b); + + SDL_Rect pixel = {1, 0, 1, 1}; + SDL_Rect line = {1, 0, 1, result->h}; + + int x = 1; + SDL_Rect dest = {x, 0, 0, 0}; + for(int i = 0; i < 127 - 33; i++) + { + pixel.x = line.x = x-1; + SDL_FillRect(result, &line, bgcolor); + SDL_FillRect(result, &pixel, pink); + + SDL_BlitSurface(surfs[i], NULL, result, &dest); + + x += surfs[i]->w + 1; + dest.x = x; + + SDL_FreeSurface(surfs[i]); + } + pixel.x = line.x = x-1; + SDL_FillRect(result, &line, bgcolor); + SDL_FillRect(result, &pixel, pink); + + return load(result); } bool NFont::load(TTF_Font* ttf, SDL_Color fg) { - if(ttf == NULL) - return false; - SDL_Surface* surfs[127 - 33]; - int width = 0; - int height = 0; - - char buff[2]; - buff[1] = '\0'; - for(int i = 0; i < 127 - 33; i++) - { - buff[0] = i + 33; - surfs[i] = TTF_RenderText_Blended(ttf, buff, fg); - width += surfs[i]->w; - height = (height < surfs[i]->h)? surfs[i]->h : height; - } - - #if SDL_BYTEORDER == SDL_BIG_ENDIAN - SDL_Surface* result = SDL_CreateRGBSurface(SDL_SWSURFACE,width + 127 - 33 + 1,height,32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF); - #else - SDL_Surface* result = SDL_CreateRGBSurface(SDL_SWSURFACE,width + 127 - 33 + 1,height,32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000); - #endif - Uint32 pink = SDL_MapRGBA(result->format, 255, 0, 255, SDL_ALPHA_OPAQUE); - - SDL_SetAlpha(result, 0, SDL_ALPHA_OPAQUE); - - SDL_Rect pixel = {1, 0, 1, 1}; - - int x = 1; - SDL_Rect dest = {x, 0, 0, 0}; - for(int i = 0; i < 127 - 33; i++) - { - pixel.x = x-1; - SDL_FillRect(result, &pixel, pink); - - SDL_SetAlpha(surfs[i], 0, SDL_ALPHA_OPAQUE); - SDL_BlitSurface(surfs[i], NULL, result, &dest); - - x += surfs[i]->w + 1; - dest.x = x; - - SDL_FreeSurface(surfs[i]); - } - pixel.x = x-1; - SDL_FillRect(result, &pixel, pink); - - SDL_SetAlpha(result, SDL_SRCALPHA, SDL_ALPHA_OPAQUE); - - return load(result); + if(ttf == NULL) + return false; + SDL_Surface* surfs[127 - 33]; + int width = 0; + int height = 0; + + char buff[2]; + buff[1] = '\0'; + for(int i = 0; i < 127 - 33; i++) + { + buff[0] = i + 33; + surfs[i] = TTF_RenderText_Blended(ttf, buff, fg); + width += surfs[i]->w; + height = (height < surfs[i]->h)? surfs[i]->h : height; + } + +#if SDL_BYTEORDER == SDL_BIG_ENDIAN + SDL_Surface* result = SDL_CreateRGBSurface(SDL_SWSURFACE,width + 127 - 33 + 1,height,32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF); +#else + SDL_Surface* result = SDL_CreateRGBSurface(SDL_SWSURFACE,width + 127 - 33 + 1,height,32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000); +#endif + Uint32 pink = SDL_MapRGBA(result->format, 255, 0, 255, SDL_ALPHA_OPAQUE); + + SDL_SetAlpha(result, 0, SDL_ALPHA_OPAQUE); + + SDL_Rect pixel = {1, 0, 1, 1}; + + int x = 1; + SDL_Rect dest = {x, 0, 0, 0}; + for(int i = 0; i < 127 - 33; i++) + { + pixel.x = x-1; + SDL_FillRect(result, &pixel, pink); + + SDL_SetAlpha(surfs[i], 0, SDL_ALPHA_OPAQUE); + SDL_BlitSurface(surfs[i], NULL, result, &dest); + + x += surfs[i]->w + 1; + dest.x = x; + + SDL_FreeSurface(surfs[i]); + } + pixel.x = x-1; + SDL_FillRect(result, &pixel, pink); + + SDL_SetAlpha(result, SDL_SRCALPHA, SDL_ALPHA_OPAQUE); + + return load(result); } bool NFont::load(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style) { - if(!TTF_WasInit() && TTF_Init() < 0) - { - printf("Unable to initialize SDL_ttf: %s \n", TTF_GetError()); - return false; - } - - TTF_Font* ttf = TTF_OpenFont(filename_ttf, pointSize); - - if(ttf == NULL) - { - printf("Unable to load TrueType font: %s \n", TTF_GetError()); - return false; - } - TTF_SetFontStyle(ttf, style); - bool result = load(ttf, fg); - TTF_CloseFont(ttf); - return result; + if(!TTF_WasInit() && TTF_Init() < 0) + { + printf("Unable to initialize SDL_ttf: %s \n", TTF_GetError()); + return false; + } + + TTF_Font* ttf = TTF_OpenFont(filename_ttf, pointSize); + + if(ttf == NULL) + { + printf("Unable to load TrueType font: %s \n", TTF_GetError()); + return false; + } + TTF_SetFontStyle(ttf, style); + bool result = load(ttf, fg); + TTF_CloseFont(ttf); + return result; } bool NFont::load(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_Color bg, int style) { - if(!TTF_WasInit() && TTF_Init() < 0) - { - printf("Unable to initialize SDL_ttf: %s \n", TTF_GetError()); - return false; - } - - TTF_Font* ttf = TTF_OpenFont(filename_ttf, pointSize); - - if(ttf == NULL) - { - printf("Unable to load TrueType font: %s \n", TTF_GetError()); - return false; - } - TTF_SetFontStyle(ttf, style); - bool result = load(ttf, fg, bg); - TTF_CloseFont(ttf); - return result; + if(!TTF_WasInit() && TTF_Init() < 0) + { + printf("Unable to initialize SDL_ttf: %s \n", TTF_GetError()); + return false; + } + + TTF_Font* ttf = TTF_OpenFont(filename_ttf, pointSize); + + if(ttf == NULL) + { + printf("Unable to load TrueType font: %s \n", TTF_GetError()); + return false; + } + TTF_SetFontStyle(ttf, style); + bool result = load(ttf, fg, bg); + TTF_CloseFont(ttf); + return result; } #endif @@ -578,7 +580,7 @@ bool NFont::load(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_C void NFont::freeSurface() { - SDL_FreeSurface(src); + SDL_FreeSurface(src); } @@ -586,264 +588,264 @@ void NFont::freeSurface() // Drawing SDL_Rect NFont::drawToSurface(int x, int y, const char* text) const { - const char* c = text; - unsigned char num; - SDL_Rect srcRect, dstRect, copyS, copyD; - data.dirtyRect = makeRect(x, y, 0, 0); - - if(c == NULL || src == NULL || dest == NULL) - return data.dirtyRect; - - srcRect.y = baseline - ascent; - srcRect.h = dstRect.h = height; - dstRect.x = x; - dstRect.y = y; - - int newlineX = x; - - for(; *c != '\0'; c++) - { - if(*c == '\n') - { - dstRect.x = newlineX; - dstRect.y += height + lineSpacing; - continue; - } - - if (*c == ' ') - { - dstRect.x += charWidth[0] + letterSpacing; - continue; - } - unsigned char ctest = (unsigned char)(*c); - // Skip bad characters - if(ctest < 33 || (ctest > 126 && ctest < 161)) - continue; - if(dstRect.x >= dest->w) - continue; - if(dstRect.y >= dest->h) - continue; - - num = ctest - 33; // Get array index - if(num > 126) // shift the extended characters down to the correct index - num -= 34; - srcRect.x = charPos[num]; - srcRect.w = dstRect.w = charWidth[num]; - copyS = srcRect; - copyD = dstRect; - SDL_BlitSurface(src, &srcRect, dest, &dstRect); - if(data.dirtyRect.w == 0 || data.dirtyRect.h == 0) - data.dirtyRect = dstRect; - else - data.dirtyRect = rectUnion(data.dirtyRect, dstRect); - srcRect = copyS; - dstRect = copyD; - - dstRect.x += dstRect.w + letterSpacing; - } - - return data.dirtyRect; + const char* c = text; + unsigned char num; + SDL_Rect srcRect, dstRect, copyS, copyD; + data.dirtyRect = makeRect(x, y, 0, 0); + + if(c == NULL || src == NULL || dest == NULL) + return data.dirtyRect; + + srcRect.y = baseline - ascent; + srcRect.h = dstRect.h = height; + dstRect.x = x; + dstRect.y = y; + + int newlineX = x; + + for(; *c != '\0'; c++) + { + if(*c == '\n') + { + dstRect.x = newlineX; + dstRect.y += height + lineSpacing; + continue; + } + + if (*c == ' ') + { + dstRect.x += charWidth[0] + letterSpacing; + continue; + } + unsigned char ctest = (unsigned char)(*c); + // Skip bad characters + if(ctest < 33 || (ctest > 126 && ctest < 161)) + continue; + if(dstRect.x >= dest->w) + continue; + if(dstRect.y >= dest->h) + continue; + + num = ctest - 33; // Get array index + if(num > 126) // shift the extended characters down to the correct index + num -= 34; + srcRect.x = charPos[num]; + srcRect.w = dstRect.w = charWidth[num]; + copyS = srcRect; + copyD = dstRect; + SDL_BlitSurface(src, &srcRect, dest, &dstRect); + if(data.dirtyRect.w == 0 || data.dirtyRect.h == 0) + data.dirtyRect = dstRect; + else + data.dirtyRect = rectUnion(data.dirtyRect, dstRect); + srcRect = copyS; + dstRect = copyD; + + dstRect.x += dstRect.w + letterSpacing; + } + + return data.dirtyRect; } SDL_Rect NFont::drawToSurfacePos(int x, int y, NFont::AnimFn posFn) const { - data.font = this; - data.dest = dest; - data.src = src; - data.text = buffer; // Buffer for efficient drawing - data.height = height; - data.charPos = charPos; - data.charWidth = charWidth; - data.maxX = maxPos; - data.dirtyRect = makeRect(x,y,0,0); - - data.index = -1; - data.letterNum = 0; - data.wordNum = 1; - data.lineNum = 1; - data.startX = x; // used as reset value for line feed - data.startY = y; - - int preFnX = x; - int preFnY = y; - - const char* c = buffer; - unsigned char num; - SDL_Rect srcRect, dstRect, copyS, copyD; - - if(c == NULL || src == NULL || dest == NULL) - return makeRect(x,y,0,0); - - srcRect.y = baseline - ascent; - srcRect.h = dstRect.h = height; - dstRect.x = x; - dstRect.y = y; - - for(; *c != '\0'; c++) - { - data.index++; - data.letterNum++; - - if(*c == '\n') - { - data.letterNum = 1; - data.wordNum = 1; - data.lineNum++; - - x = data.startX; // carriage return - y += height + lineSpacing; - continue; - } - if (*c == ' ') - { - data.letterNum = 1; - data.wordNum++; - - x += charWidth[0] + letterSpacing; - continue; - } - unsigned char ctest = (unsigned char)(*c); - // Skip bad characters - if(ctest < 33 || (ctest > 126 && ctest < 161)) - continue; - //if(x >= dest->w) // This shouldn't be used with position control - // continue; - num = ctest - 33; - if(num > 126) // shift the extended characters down to the array index - num -= 34; - srcRect.x = charPos[num]; - srcRect.w = dstRect.w = charWidth[num]; - - preFnX = x; // Save real position - preFnY = y; - - // Use function pointer to get final x, y values - posFn(x, y, data); - - dstRect.x = x; - dstRect.y = y; - - copyS = srcRect; - copyD = dstRect; - SDL_BlitSurface(src, &srcRect, dest, &dstRect); - if(data.dirtyRect.w == 0 || data.dirtyRect.h == 0) - data.dirtyRect = dstRect; - else - data.dirtyRect = rectUnion(data.dirtyRect, dstRect); - srcRect = copyS; - dstRect = copyD; - - x = preFnX; // Restore real position - y = preFnY; - - x += dstRect.w + letterSpacing; - } - - return data.dirtyRect; + data.font = this; + data.dest = dest; + data.src = src; + data.text = buffer; // Buffer for efficient drawing + data.height = height; + data.charPos = charPos; + data.charWidth = charWidth; + data.maxX = maxPos; + data.dirtyRect = makeRect(x,y,0,0); + + data.index = -1; + data.letterNum = 0; + data.wordNum = 1; + data.lineNum = 1; + data.startX = x; // used as reset value for line feed + data.startY = y; + + int preFnX = x; + int preFnY = y; + + const char* c = buffer; + unsigned char num; + SDL_Rect srcRect, dstRect, copyS, copyD; + + if(c == NULL || src == NULL || dest == NULL) + return makeRect(x,y,0,0); + + srcRect.y = baseline - ascent; + srcRect.h = dstRect.h = height; + dstRect.x = x; + dstRect.y = y; + + for(; *c != '\0'; c++) + { + data.index++; + data.letterNum++; + + if(*c == '\n') + { + data.letterNum = 1; + data.wordNum = 1; + data.lineNum++; + + x = data.startX; // carriage return + y += height + lineSpacing; + continue; + } + if (*c == ' ') + { + data.letterNum = 1; + data.wordNum++; + + x += charWidth[0] + letterSpacing; + continue; + } + unsigned char ctest = (unsigned char)(*c); + // Skip bad characters + if(ctest < 33 || (ctest > 126 && ctest < 161)) + continue; + //if(x >= dest->w) // This shouldn't be used with position control + // continue; + num = ctest - 33; + if(num > 126) // shift the extended characters down to the array index + num -= 34; + srcRect.x = charPos[num]; + srcRect.w = dstRect.w = charWidth[num]; + + preFnX = x; // Save real position + preFnY = y; + + // Use function pointer to get final x, y values + posFn(x, y, data); + + dstRect.x = x; + dstRect.y = y; + + copyS = srcRect; + copyD = dstRect; + SDL_BlitSurface(src, &srcRect, dest, &dstRect); + if(data.dirtyRect.w == 0 || data.dirtyRect.h == 0) + data.dirtyRect = dstRect; + else + data.dirtyRect = rectUnion(data.dirtyRect, dstRect); + srcRect = copyS; + dstRect = copyD; + + x = preFnX; // Restore real position + y = preFnY; + + x += dstRect.w + letterSpacing; + } + + return data.dirtyRect; } SDL_Rect NFont::draw(int x, int y, const char* formatted_text, ...) const { - if(formatted_text == NULL) - return makeRect(x, y, 0, 0); + if(formatted_text == NULL) + return makeRect(x, y, 0, 0); - va_list lst; - va_start(lst, formatted_text); - vsprintf(buffer, formatted_text, lst); - va_end(lst); + va_list lst; + va_start(lst, formatted_text); + vsprintf(buffer, formatted_text, lst); + va_end(lst); - return drawToSurface(x, y, buffer); + return drawToSurface(x, y, buffer); } SDL_Rect NFont::drawCenter(int x, int y, const char* formatted_text, ...) const { - if(formatted_text == NULL) - return makeRect(x, y, 0, 0); - - va_list lst; - va_start(lst, formatted_text); - vsprintf(buffer, formatted_text, lst); - va_end(lst); - - char* str = copyString(buffer); - char* del = str; - - // Go through str, when you find a \n, replace it with \0 and print it - // then move down, back, and continue. - for(char* c = str; *c != '\0';) - { - if(*c == '\n') - { - *c = '\0'; - drawToSurface(x - getWidth("%s", str)/2, y, str); - *c = '\n'; - c++; - str = c; - y += height; - } - else - c++; - } - char s[strlen(str)+1]; - strcpy(s, str); - delete[] del; - - return drawToSurface(x - getWidth("%s", s)/2, y, s); + if(formatted_text == NULL) + return makeRect(x, y, 0, 0); + + va_list lst; + va_start(lst, formatted_text); + vsprintf(buffer, formatted_text, lst); + va_end(lst); + + char* str = copyString(buffer); + char* del = str; + + // Go through str, when you find a \n, replace it with \0 and print it + // then move down, back, and continue. + for(char* c = str; *c != '\0';) + { + if(*c == '\n') + { + *c = '\0'; + drawToSurface(x - getWidth("%s", str)/2, y, str); + *c = '\n'; + c++; + str = c; + y += height; + } + else + c++; + } + char s[strlen(str)+1]; + strcpy(s, str); + delete[] del; + + return drawToSurface(x - getWidth("%s", s)/2, y, s); } SDL_Rect NFont::drawRight(int x, int y, const char* formatted_text, ...) const { - if(formatted_text == NULL) - return makeRect(x, y, 0, 0); - - va_list lst; - va_start(lst, formatted_text); - vsprintf(buffer, formatted_text, lst); - va_end(lst); - - char* str = copyString(buffer); - char* del = str; - - for(char* c = str; *c != '\0';) - { - if(*c == '\n') - { - *c = '\0'; - drawToSurface(x - getWidth("%s", str), y, str); - *c = '\n'; - c++; - str = c; - y += height; - } - else - c++; - } - char s[strlen(str)+1]; - strcpy(s, str); - delete[] del; - - return drawToSurface(x - getWidth("%s", s), y, s); + if(formatted_text == NULL) + return makeRect(x, y, 0, 0); + + va_list lst; + va_start(lst, formatted_text); + vsprintf(buffer, formatted_text, lst); + va_end(lst); + + char* str = copyString(buffer); + char* del = str; + + for(char* c = str; *c != '\0';) + { + if(*c == '\n') + { + *c = '\0'; + drawToSurface(x - getWidth("%s", str), y, str); + *c = '\n'; + c++; + str = c; + y += height; + } + else + c++; + } + char s[strlen(str)+1]; + strcpy(s, str); + delete[] del; + + return drawToSurface(x - getWidth("%s", s), y, s); } SDL_Rect NFont::drawPos(int x, int y, NFont::AnimFn posFn, const char* text, ...) const { - va_list lst; - va_start(lst, text); - vsprintf(buffer, text, lst); - va_end(lst); + va_list lst; + va_start(lst, text); + vsprintf(buffer, text, lst); + va_end(lst); - return drawToSurfacePos(x, y, posFn); + return drawToSurfacePos(x, y, posFn); } SDL_Rect NFont::drawAll(int x, int y, NFont::AnimFn allFn, const char* text, ...) const { - va_list lst; - va_start(lst, text); - vsprintf(buffer, text, lst); - va_end(lst); + va_list lst; + va_start(lst, text); + vsprintf(buffer, text, lst); + va_end(lst); - allFn(x, y, data); - return data.dirtyRect; + allFn(x, y, data); + return data.dirtyRect; } @@ -852,193 +854,193 @@ SDL_Rect NFont::drawAll(int x, int y, NFont::AnimFn allFn, const char* text, ... // Getters SDL_Surface* NFont::getDest() const { - return dest; + return dest; } SDL_Surface* NFont::getSurface() const { - return src; + return src; } int NFont::getHeight(const char* formatted_text, ...) const { - if(formatted_text == NULL) - return height; + if(formatted_text == NULL) + return height; - va_list lst; - va_start(lst, formatted_text); - vsprintf(buffer, formatted_text, lst); - va_end(lst); + va_list lst; + va_start(lst, formatted_text); + vsprintf(buffer, formatted_text, lst); + va_end(lst); - int numLines = 1; - const char* c; + int numLines = 1; + const char* c; - for (c = buffer; *c != '\0'; c++) - { - if(*c == '\n') - numLines++; - } + for (c = buffer; *c != '\0'; c++) + { + if(*c == '\n') + numLines++; + } - // Actual height of letter region + line spacing - return height*numLines + lineSpacing*(numLines - 1); //height*numLines; + // Actual height of letter region + line spacing + return height*numLines + lineSpacing*(numLines - 1); //height*numLines; } int NFont::getWidth(const char* formatted_text, ...) const { - if (formatted_text == NULL) - return 0; - - va_list lst; - va_start(lst, formatted_text); - vsprintf(buffer, formatted_text, lst); - va_end(lst); - - const char* c; - int charnum = 0; - int width = 0; - int bigWidth = 0; // Allows for multi-line strings - - for (c = buffer; *c != '\0'; c++) - { - charnum = (unsigned char)(*c) - 33; - - // skip spaces and nonprintable characters - if(*c == '\n') - { - bigWidth = bigWidth >= width? bigWidth : width; - width = 0; - } - else if (*c == ' ' || charnum > 222) - { - width += charWidth[0]; - continue; - } - - width += charWidth[charnum]; - } - bigWidth = bigWidth >= width? bigWidth : width; - - return bigWidth; + if (formatted_text == NULL) + return 0; + + va_list lst; + va_start(lst, formatted_text); + vsprintf(buffer, formatted_text, lst); + va_end(lst); + + const char* c; + int charnum = 0; + int width = 0; + int bigWidth = 0; // Allows for multi-line strings + + for (c = buffer; *c != '\0'; c++) + { + charnum = (unsigned char)(*c) - 33; + + // skip spaces and nonprintable characters + if(*c == '\n') + { + bigWidth = bigWidth >= width? bigWidth : width; + width = 0; + } + else if (*c == ' ' || charnum > 222) + { + width += charWidth[0]; + continue; + } + + width += charWidth[charnum]; + } + bigWidth = bigWidth >= width? bigWidth : width; + + return bigWidth; } int NFont::getAscent(const char character) const { - unsigned char test = (unsigned char)character; - if(test < 33 || test > 222 || (test > 126 && test < 161)) - return 0; - unsigned char num = (unsigned char)character - 33; - // Get the max ascent - int x = charPos[num]; - int i, j = 1, result = 0; - Uint32 pixel = getPixel(src, 0, src->h - 1); // bg pixel - while(j < baseline && j < src->h) - { - i = charPos[num]; - while(i < x + charWidth[num]) - { - if(getPixel(src, i, j) != pixel) - { - result = baseline - j; - j = src->h; - break; - } - i++; - } - j++; - } - return result; + unsigned char test = (unsigned char)character; + if(test < 33 || test > 222 || (test > 126 && test < 161)) + return 0; + unsigned char num = (unsigned char)character - 33; + // Get the max ascent + int x = charPos[num]; + int i, j = 1, result = 0; + Uint32 pixel = getPixel(src, 0, src->h - 1); // bg pixel + while(j < baseline && j < src->h) + { + i = charPos[num]; + while(i < x + charWidth[num]) + { + if(getPixel(src, i, j) != pixel) + { + result = baseline - j; + j = src->h; + break; + } + i++; + } + j++; + } + return result; } int NFont::getAscent(const char* formatted_text, ...) const { - if(formatted_text == NULL) - return ascent; - - va_list lst; - va_start(lst, formatted_text); - vsprintf(buffer, formatted_text, lst); - va_end(lst); - - int max = 0; - const char* c = buffer; - - for (; *c != '\0'; c++) - { - int asc = getAscent(*c); - if(asc > max) - max = asc; - } - return max; + if(formatted_text == NULL) + return ascent; + + va_list lst; + va_start(lst, formatted_text); + vsprintf(buffer, formatted_text, lst); + va_end(lst); + + int max = 0; + const char* c = buffer; + + for (; *c != '\0'; c++) + { + int asc = getAscent(*c); + if(asc > max) + max = asc; + } + return max; } int NFont::getDescent(const char character) const { - unsigned char test = (unsigned char)character; - if(test < 33 || test > 222 || (test > 126 && test < 161)) - return 0; - unsigned char num = (unsigned char)character - 33; - // Get the max descent - int x = charPos[num]; - int i, j = src->h - 1, result = 0; - Uint32 pixel = getPixel(src, 0, src->h - 1); // bg pixel - while(j > 0 && j > baseline) - { - i = charPos[num]; - while(i < x + charWidth[num]) - { - if(getPixel(src, i, j) != pixel) - { - result = j - baseline; - j = 0; - break; - } - i++; - } - j--; - } - return result; + unsigned char test = (unsigned char)character; + if(test < 33 || test > 222 || (test > 126 && test < 161)) + return 0; + unsigned char num = (unsigned char)character - 33; + // Get the max descent + int x = charPos[num]; + int i, j = src->h - 1, result = 0; + Uint32 pixel = getPixel(src, 0, src->h - 1); // bg pixel + while(j > 0 && j > baseline) + { + i = charPos[num]; + while(i < x + charWidth[num]) + { + if(getPixel(src, i, j) != pixel) + { + result = j - baseline; + j = 0; + break; + } + i++; + } + j--; + } + return result; } int NFont::getDescent(const char* formatted_text, ...) const { - if(formatted_text == NULL) - return descent; - - va_list lst; - va_start(lst, formatted_text); - vsprintf(buffer, formatted_text, lst); - va_end(lst); - - int max = 0; - const char* c = buffer; - - for (; *c != '\0'; c++) - { - int des = getDescent(*c); - if(des > max) - max = des; - } - return max; + if(formatted_text == NULL) + return descent; + + va_list lst; + va_start(lst, formatted_text); + vsprintf(buffer, formatted_text, lst); + va_end(lst); + + int max = 0; + const char* c = buffer; + + for (; *c != '\0'; c++) + { + int des = getDescent(*c); + if(des > max) + max = des; + } + return max; } int NFont::getSpacing() const { - return letterSpacing; + return letterSpacing; } int NFont::getLineSpacing() const { - return lineSpacing; + return lineSpacing; } int NFont::getBaseline() const { - return baseline; + return baseline; } int NFont::getMaxWidth() const { - return maxWidth; + return maxWidth; } @@ -1048,54 +1050,54 @@ int NFont::getMaxWidth() const // Setters void NFont::setSpacing(int LetterSpacing) { - letterSpacing = LetterSpacing; + letterSpacing = LetterSpacing; } void NFont::setLineSpacing(int LineSpacing) { - lineSpacing = LineSpacing; + lineSpacing = LineSpacing; } void NFont::setDest(SDL_Surface* Dest) { - dest = Dest; + dest = Dest; } int NFont::setBaseline(int Baseline) { - if(Baseline >= 0) - baseline = Baseline; - else - { - // Get the baseline by checking a, b, and c and averaging their lowest y-value. - // Is there a better way? - Uint32 pixel = getPixel(src, 0, src->h - 1); - int heightSum = 0; - int x, i, j; - for(unsigned char avgChar = 64; avgChar < 67; avgChar++) - { - x = charPos[avgChar]; - - j = src->h - 1; - while(j > 0) - { - i = x; - while(i - x < charWidth[64]) - { - if(getPixel(src, i, j) != pixel) - { - heightSum += j; - j = 0; - break; - } - i++; - } - j--; - } - } - baseline = int(heightSum/3.0f + 0.5f); // Round up and cast - } - return baseline; + if(Baseline >= 0) + baseline = Baseline; + else + { + // Get the baseline by checking a, b, and c and averaging their lowest y-value. + // Is there a better way? + Uint32 pixel = getPixel(src, 0, src->h - 1); + int heightSum = 0; + int x, i, j; + for(unsigned char avgChar = 64; avgChar < 67; avgChar++) + { + x = charPos[avgChar]; + + j = src->h - 1; + while(j > 0) + { + i = x; + while(i - x < charWidth[64]) + { + if(getPixel(src, i, j) != pixel) + { + heightSum += j; + j = 0; + break; + } + i++; + } + j--; + } + } + baseline = int(heightSum/3.0f + 0.5f); // Round up and cast + } + return baseline; } diff --git a/source/code/Libs/NFont.h b/source/code/Libs/NFont.h index 14036e5..c8f5d4e 100644 --- a/source/code/Libs/NFont.h +++ b/source/code/Libs/NFont.h @@ -15,30 +15,30 @@ Optionally Requires: Notes: NFont is a bitmap font class with text-block alignment, full - support for the newline character ('\n'), animation, and extended ASCII - support. It accepts SDL_Surfaces so that any image format you can load + support for the newline character ('\n'), animation, and extended ASCII + support. It accepts SDL_Surfaces so that any image format you can load can be used as an NFont. - - NFont has the ability to animate the font in two ways: It's position or - it's everything. By using drawPos(), you can use a function you create - to handle the final positions of the drawn characters. With drawAll(), - you can handle everything that the font does (please use my + + NFont has the ability to animate the font in two ways: It's position or + it's everything. By using drawPos(), you can use a function you create + to handle the final positions of the drawn characters. With drawAll(), + you can handle everything that the font does (please use my drawToSurface() function as a reference). Internally, NFont uses a pointer (SDL_Surface*) to handle the destination - surface. You have to set the destination before the font can be used. Be - aware that you will need to use setDest() if you replace the memory that + surface. You have to set the destination before the font can be used. Be + aware that you will need to use setDest() if you replace the memory that it points to (like when using screen = SDL_SetVideoMode()). - + NFont can use standard SFont bitmaps or extended bitmaps. The standard bitmaps have the following characters (ASCII 33-126) separated by pink (255, 0, 255) pixels in the topmost row: ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ - + And the extended bitmaps have these (ASCII 161-255): ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � - - NFont can also load SDL_ttf fonts. Define NFONT_USE_TTF before including + + NFont can also load SDL_ttf fonts. Define NFONT_USE_TTF before including NFont.h to use the flexibility of NFont with TrueType fonts. If you come up with something cool using NFont, I'd love to hear about it. @@ -46,9 +46,9 @@ Notes: License: The short: - Use it however you'd like, but keep the copyright and license notice + Use it however you'd like, but keep the copyright and license notice whenever these files or parts of them are distributed in uncompiled form. - + The long: Copyright (c) 2010 Jonathan Dearborn @@ -79,143 +79,143 @@ THE SOFTWARE. #include "stdarg.h" #ifdef NFONT_USE_TTF - #include "SDL_ttf.h" +#include "SDL_ttf.h" #endif class NFont { public: - // Nested struct - struct AnimData - { - const NFont* font; - - SDL_Surface* dest; - SDL_Surface* src; - char* text; // Buffer for efficient drawing - int height; - const int* charPos; - const int* charWidth; - int maxX; - - int index; - int letterNum; - int wordNum; - int lineNum; - int startX; - int startY; - void* userVar; - - SDL_Rect dirtyRect; - }; - - // Function pointer - typedef void (*AnimFn)(int&, int&, AnimData&); - + // Nested struct + struct AnimData + { + const NFont* font; + + SDL_Surface* dest; + SDL_Surface* src; + char* text; // Buffer for efficient drawing + int height; + const int* charPos; + const int* charWidth; + int maxX; + + int index; + int letterNum; + int wordNum; + int lineNum; + int startX; + int startY; + void* userVar; + + SDL_Rect dirtyRect; + }; + + // Function pointer + typedef void (*AnimFn)(int&, int&, AnimData&); + protected: - - SDL_Surface* src; // bitmap source of characters - SDL_Surface* dest; // Destination to blit to - int height; + SDL_Surface* src; // bitmap source of characters + SDL_Surface* dest; // Destination to blit to + + int height; + + int maxWidth; + int baseline; + int ascent; + int descent; + + int lineSpacing; + int letterSpacing; - int maxWidth; - int baseline; - int ascent; - int descent; + int charPos[256]; + int charWidth[256]; + int maxPos; - int lineSpacing; - int letterSpacing; + void init(); - int charPos[256]; - int charWidth[256]; - int maxPos; - - void init(); + SDL_Rect drawToSurface(int x, int y, const char* text) const; + SDL_Rect drawToSurfacePos(int x, int y, NFont::AnimFn posFn) const; - SDL_Rect drawToSurface(int x, int y, const char* text) const; - SDL_Rect drawToSurfacePos(int x, int y, NFont::AnimFn posFn) const; - - // Static variables - static char* buffer; // Buffer for efficient drawing - static AnimData data; // Data is wrapped in a struct so it can all be passed to - // the function pointers for animation + // Static variables + static char* buffer; // Buffer for efficient drawing + static AnimData data; // Data is wrapped in a struct so it can all be passed to + // the function pointers for animation public: - - // Static functions - static char* copyString(const char* c); - static Uint32 getPixel(SDL_Surface *Surface, int x, int y); - static inline SDL_Rect makeRect(Sint16 x, Sint16 y, Uint16 w, Uint16 h) - { - SDL_Rect r = {x, y, w, h}; - return r; - } - static SDL_Rect rectUnion(const SDL_Rect& A, const SDL_Rect& B); - static SDL_Surface* copySurface(SDL_Surface *Surface); - static SDL_Surface* verticalGradient(SDL_Surface* targetSurface, Uint32 topColor, Uint32 bottomColor, int heightAdjust = 0); - - // Static accessors - static void setAnimData(void* data); - static void setBuffer(unsigned int size); - - // Constructors - NFont(); - NFont(SDL_Surface* src); - NFont(SDL_Surface* dest, SDL_Surface* src); - #ifdef NFONT_USE_TTF - NFont(TTF_Font* ttf, SDL_Color fg); // Alpha bg - NFont(TTF_Font* ttf, SDL_Color fg, SDL_Color bg); - NFont(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style = TTF_STYLE_NORMAL); // Alpha bg - NFont(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_Color bg, int style = TTF_STYLE_NORMAL); - NFont(SDL_Surface* dest, TTF_Font* ttf, SDL_Color fg); // Alpha bg - NFont(SDL_Surface* dest, TTF_Font* ttf, SDL_Color fg, SDL_Color bg); - NFont(SDL_Surface* dest, const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style = TTF_STYLE_NORMAL); // Alpha bg - NFont(SDL_Surface* dest, const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_Color bg, int style = TTF_STYLE_NORMAL); - #endif - - ~NFont(); - - // Loading - bool load(SDL_Surface* FontSurface); - bool load(SDL_Surface* destSurface, SDL_Surface* FontSurface); - #ifdef NFONT_USE_TTF - bool load(TTF_Font* ttf, SDL_Color fg); // Alpha bg - bool load(TTF_Font* ttf, SDL_Color fg, SDL_Color bg); - bool load(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style = TTF_STYLE_NORMAL); // Alpha bg - bool load(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_Color bg, int style = TTF_STYLE_NORMAL); - #endif - - void freeSurface(); - - // Drawing - SDL_Rect draw(int x, int y, const char* formatted_text, ...) const; - SDL_Rect drawCenter(int x, int y, const char* formatted_text, ...) const; - SDL_Rect drawRight(int x, int y, const char* formatted_text, ...) const; - SDL_Rect drawPos(int x, int y, NFont::AnimFn posFn, const char* text, ...) const; - SDL_Rect drawAll(int x, int y, NFont::AnimFn allFn, const char* text, ...) const; - - // Getters - SDL_Surface* getDest() const; - SDL_Surface* getSurface() const; - int getHeight(const char* formatted_text = NULL, ...) const; - int getWidth(const char* formatted_text, ...) const; - int getSpacing() const; - int getLineSpacing() const; - int getBaseline() const; - int getAscent(const char character) const; - int getAscent(const char* formatted_text = NULL, ...) const; - int getDescent(const char character) const; - int getDescent(const char* formatted_text = NULL, ...) const; - int getMaxWidth() const; - - // Setters - void setDest(SDL_Surface* Dest); - void setSpacing(int LetterSpacing); - void setLineSpacing(int LineSpacing); - int setBaseline(int Baseline = -1); + + // Static functions + static char* copyString(const char* c); + static Uint32 getPixel(SDL_Surface *Surface, int x, int y); + static inline SDL_Rect makeRect(Sint16 x, Sint16 y, Uint16 w, Uint16 h) + { + SDL_Rect r = {x, y, w, h}; + return r; + } + static SDL_Rect rectUnion(const SDL_Rect& A, const SDL_Rect& B); + static SDL_Surface* copySurface(SDL_Surface *Surface); + static SDL_Surface* verticalGradient(SDL_Surface* targetSurface, Uint32 topColor, Uint32 bottomColor, int heightAdjust = 0); + + // Static accessors + static void setAnimData(void* data); + static void setBuffer(unsigned int size); + + // Constructors + NFont(); + NFont(SDL_Surface* src); + NFont(SDL_Surface* dest, SDL_Surface* src); +#ifdef NFONT_USE_TTF + NFont(TTF_Font* ttf, SDL_Color fg); // Alpha bg + NFont(TTF_Font* ttf, SDL_Color fg, SDL_Color bg); + NFont(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style = TTF_STYLE_NORMAL); // Alpha bg + NFont(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_Color bg, int style = TTF_STYLE_NORMAL); + NFont(SDL_Surface* dest, TTF_Font* ttf, SDL_Color fg); // Alpha bg + NFont(SDL_Surface* dest, TTF_Font* ttf, SDL_Color fg, SDL_Color bg); + NFont(SDL_Surface* dest, const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style = TTF_STYLE_NORMAL); // Alpha bg + NFont(SDL_Surface* dest, const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_Color bg, int style = TTF_STYLE_NORMAL); +#endif + + ~NFont(); + + // Loading + bool load(SDL_Surface* FontSurface); + bool load(SDL_Surface* destSurface, SDL_Surface* FontSurface); +#ifdef NFONT_USE_TTF + bool load(TTF_Font* ttf, SDL_Color fg); // Alpha bg + bool load(TTF_Font* ttf, SDL_Color fg, SDL_Color bg); + bool load(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style = TTF_STYLE_NORMAL); // Alpha bg + bool load(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_Color bg, int style = TTF_STYLE_NORMAL); +#endif + + void freeSurface(); + + // Drawing + SDL_Rect draw(int x, int y, const char* formatted_text, ...) const; + SDL_Rect drawCenter(int x, int y, const char* formatted_text, ...) const; + SDL_Rect drawRight(int x, int y, const char* formatted_text, ...) const; + SDL_Rect drawPos(int x, int y, NFont::AnimFn posFn, const char* text, ...) const; + SDL_Rect drawAll(int x, int y, NFont::AnimFn allFn, const char* text, ...) const; + + // Getters + SDL_Surface* getDest() const; + SDL_Surface* getSurface() const; + int getHeight(const char* formatted_text = NULL, ...) const; + int getWidth(const char* formatted_text, ...) const; + int getSpacing() const; + int getLineSpacing() const; + int getBaseline() const; + int getAscent(const char character) const; + int getAscent(const char* formatted_text = NULL, ...) const; + int getDescent(const char character) const; + int getDescent(const char* formatted_text = NULL, ...) const; + int getMaxWidth() const; + + // Setters + void setDest(SDL_Surface* Dest); + void setSpacing(int LetterSpacing); + void setLineSpacing(int LineSpacing); + int setBaseline(int Baseline = -1); }; diff --git a/source/code/MenuSystem.cc b/source/code/MenuSystem.cc index 44947ad..63e80e4 100644 --- a/source/code/MenuSystem.cc +++ b/source/code/MenuSystem.cc @@ -1,21 +1,24 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2008 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include @@ -33,10 +36,10 @@ int mousey; /*Draws a image from on a given Surface. Takes source image, destination surface and coordinates*/ inline void DrawIMG(SDL_Surface *img, SDL_Surface *target, int x, int y) { - SDL_Rect dest; - dest.x = x; - dest.y = y; - SDL_BlitSurface(img, NULL, target, &dest); + SDL_Rect dest; + dest.x = x; + dest.y = y; + SDL_BlitSurface(img, NULL, target, &dest); } CppSdl::CppSdlImageHolder ButtonGfx::_marked; @@ -47,18 +50,18 @@ NFont ButtonGfx::thefont; void ButtonGfx::setSurfaces(CppSdl::CppSdlImageHolder marked,CppSdl::CppSdlImageHolder unmarked) { - ButtonGfx::_marked = marked; - ButtonGfx::_unmarked = unmarked; - xsize=(marked).GetWidth(); - ysize=(marked).GetHeight(); - cout << "Surfaces set, size: " <= this->x && y >= this->y && x<= this->x+ButtonGfx::xsize && y <= this->y + ButtonGfx::ysize) - return true; - else - return false; + if ( x >= this->x && y >= this->y && x<= this->x+ButtonGfx::xsize && y <= this->y + ButtonGfx::ysize) + return true; + else + return false; } void Button::doAction() { - if(action) - action(this); - else - cout << "Warning: button \"" << label << "\" has no action assigned!"; + if(action) + action(this); + else + cout << "Warning: button \"" << label << "\" has no action assigned!"; } void Button::drawTo(SDL_Surface **surface) { - #if DEBUG - //cout << "Painting button: " << label << " at: " << x << "," << y << endl; - #endif - if (marked) - ButtonGfx::_marked.PaintTo(*surface,x,y); - else - ButtonGfx::_unmarked.PaintTo(*surface,x,y); - //int stringx = x + (ButtonGfx::xsize)/2 - ButtonGfx::ttf->getTextWidth(label)/2; - //int stringy = y + (ButtonGfx::ysize)/2 - ButtonGfx::ttf->getTextHeight()/2; - //ButtonGfx::ttf->writeText(label,surface,stringx,stringy); - ButtonGfx::thefont.setDest(*surface); - ButtonGfx::thefont.drawCenter(x+ButtonGfx::xsize/2,y+ButtonGfx::ysize/2-ButtonGfx::thefont.getHeight(label.c_str())/2,label.c_str()); +#if DEBUG + //cout << "Painting button: " << label << " at: " << x << "," << y << endl; +#endif + if (marked) + ButtonGfx::_marked.PaintTo(*surface,x,y); + else + ButtonGfx::_unmarked.PaintTo(*surface,x,y); + //int stringx = x + (ButtonGfx::xsize)/2 - ButtonGfx::ttf->getTextWidth(label)/2; + //int stringy = y + (ButtonGfx::ysize)/2 - ButtonGfx::ttf->getTextHeight()/2; + //ButtonGfx::ttf->writeText(label,surface,stringx,stringy); + ButtonGfx::thefont.setDest(*surface); + ButtonGfx::thefont.drawCenter(x+ButtonGfx::xsize/2,y+ButtonGfx::ysize/2-ButtonGfx::thefont.getHeight(label.c_str())/2,label.c_str()); } void Menu::drawSelf() { - DrawIMG(backgroundImage,screen,0,0); - vector::iterator it; - for(it = buttons.begin();it < buttons.end(); it++) - (*it)->drawTo(&screen); - exit.drawTo(&screen); - ButtonGfx::thefont.draw(50,50,title.c_str()); - mouse.PaintTo(screen,mousex,mousey); + DrawIMG(backgroundImage,screen,0,0); + vector::iterator it; + for(it = buttons.begin(); it < buttons.end(); it++) + (*it)->drawTo(&screen); + exit.drawTo(&screen); + ButtonGfx::thefont.draw(50,50,title.c_str()); + mouse.PaintTo(screen,mousex,mousey); } void Menu::performClick(int x,int y) { - vector::iterator it; - for(it = buttons.begin();it < buttons.end(); it++) - { - Button *b = (*it); - if(b->isClicked(x,y)) - b->doAction(); - } - if(exit.isClicked(x,y)) - running = false; + vector::iterator it; + for(it = buttons.begin(); it < buttons.end(); it++) + { + Button *b = (*it); + if(b->isClicked(x,y)) + b->doAction(); + } + if(exit.isClicked(x,y)) + running = false; } void Menu::placeButtons() { - int nextY = 100; - const int X = 50; - vector::iterator it; - for(it = buttons.begin();it < buttons.end(); it++) - { - (*it)->x = X; - (*it)->y = nextY; - nextY += ButtonGfx::ysize+10; - } - exit.x = X; - exit.y = nextY; + int nextY = 100; + const int X = 50; + vector::iterator it; + for(it = buttons.begin(); it < buttons.end(); it++) + { + (*it)->x = X; + (*it)->y = nextY; + nextY += ButtonGfx::ysize+10; + } + exit.x = X; + exit.y = nextY; } void Menu::addButton(Button *b) { - buttons.push_back(b); - b->marked = false; - placeButtons(); + buttons.push_back(b); + b->marked = false; + placeButtons(); } Menu::Menu(SDL_Surface **screen) { - this->screen = *screen; - buttons = vector(10); - isSubmenu = true; - exit.setLabel( _("Back") ); + this->screen = *screen; + buttons = vector(10); + isSubmenu = true; + exit.setLabel( _("Back") ); } Menu::Menu(SDL_Surface **screen,bool submenu) { - this->screen = *screen; - buttons = vector(0); - isSubmenu = submenu; - if(isSubmenu) - exit.setLabel( _("Back") ); - else - exit.setLabel( _("Exit") ); + this->screen = *screen; + buttons = vector(0); + isSubmenu = submenu; + if(isSubmenu) + exit.setLabel( _("Back") ); + else + exit.setLabel( _("Exit") ); } -Menu::Menu(SDL_Surface** screen, string title, bool submenu) { - this->screen = *screen; - buttons = vector(0); - isSubmenu = submenu; - this->title = title; - if(isSubmenu) - exit.setLabel(_("Back") ); - else - exit.setLabel(_("Exit") ); +Menu::Menu(SDL_Surface** screen, string title, bool submenu) +{ + this->screen = *screen; + buttons = vector(0); + isSubmenu = submenu; + this->title = title; + if(isSubmenu) + exit.setLabel(_("Back") ); + else + exit.setLabel(_("Exit") ); } void Menu::run() { - running = true; - bool bMouseUp = false; - long oldmousex = mousex; - long oldmousey = mousey; - while(running && !Config::getInstance()->isShuttingDown()) - { - if (!(highPriority)) SDL_Delay(10); - - - SDL_Event event; - - while ( SDL_PollEvent(&event) ) - { - if ( event.type == SDL_QUIT ) { - Config::getInstance()->setShuttingDown(5); - running = false; - } - - if ( event.type == SDL_KEYDOWN ) - { - if ( event.key.keysym.sym == SDLK_ESCAPE ) - { - running = false; - } - - if (event.key.keysym.sym == SDLK_UP) - { - marked--; - if(marked<0) - marked = buttons.size(); //not -1, since exit is after the last element in the list - } - - if (event.key.keysym.sym == SDLK_DOWN) - { - marked++; - if(marked>buttons.size()) - marked = 0; - } - - if(event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER ) { - if(marked < buttons.size()) - buttons.at(marked)->doAction(); - if(marked == buttons.size()) - running = false; - } - } - - - } - - for(int i=0;imarked = (i == marked); - } - exit.marked = (marked == buttons.size()); - Uint8 buttonState = SDL_GetMouseState(&mousex,&mousey); - // If the mouse button is released, make bMouseUp equal true - if ( (buttonState&SDL_BUTTON(1))==0) - { - bMouseUp=true; - } - - if(abs(mousex-oldmousex)>5 || abs(mousey-oldmousey)>5) { - for(int i=0;i< buttons.size();++i) { - if(buttons.at(i)->isClicked(mousex,mousey)) { - marked = i; - } - } - if(exit.isClicked(mousex,mousey)) { - marked = buttons.size(); - } - oldmousex = mousex; - oldmousey = mousey; - } - - //mouse clicked - if(buttonState&SDL_BUTTON(1)==SDL_BUTTON(1) && bMouseUp) - { - bMouseUp = false; - for(int i=0;i< buttons.size();++i) { - if(buttons.at(i)->isClicked(mousex,mousey)) { - buttons.at(i)->doAction(); - } - } - if(exit.isClicked(mousex,mousey)) { - running = false; - } - } - - drawSelf(); - SDL_Flip(screen); - } + running = true; + bool bMouseUp = false; + long oldmousex = mousex; + long oldmousey = mousey; + while(running && !Config::getInstance()->isShuttingDown()) + { + if (!(highPriority)) SDL_Delay(10); + + + SDL_Event event; + + while ( SDL_PollEvent(&event) ) + { + if ( event.type == SDL_QUIT ) + { + Config::getInstance()->setShuttingDown(5); + running = false; + } + + if ( event.type == SDL_KEYDOWN ) + { + if ( event.key.keysym.sym == SDLK_ESCAPE ) + { + running = false; + } + + if (event.key.keysym.sym == SDLK_UP) + { + marked--; + if(marked<0) + marked = buttons.size(); //not -1, since exit is after the last element in the list + } + + if (event.key.keysym.sym == SDLK_DOWN) + { + marked++; + if(marked>buttons.size()) + marked = 0; + } + + if(event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER ) + { + if(marked < buttons.size()) + buttons.at(marked)->doAction(); + if(marked == buttons.size()) + running = false; + } + } + + + } + + for(int i=0; imarked = (i == marked); + } + exit.marked = (marked == buttons.size()); + Uint8 buttonState = SDL_GetMouseState(&mousex,&mousey); + // If the mouse button is released, make bMouseUp equal true + if ( (buttonState&SDL_BUTTON(1))==0) + { + bMouseUp=true; + } + + if(abs(mousex-oldmousex)>5 || abs(mousey-oldmousey)>5) + { + for(int i=0; i< buttons.size(); ++i) + { + if(buttons.at(i)->isClicked(mousex,mousey)) + { + marked = i; + } + } + if(exit.isClicked(mousex,mousey)) + { + marked = buttons.size(); + } + oldmousex = mousex; + oldmousey = mousey; + } + + //mouse clicked + if(buttonState&SDL_BUTTON(1)==SDL_BUTTON(1) && bMouseUp) + { + bMouseUp = false; + for(int i=0; i< buttons.size(); ++i) + { + if(buttons.at(i)->isClicked(mousex,mousey)) + { + buttons.at(i)->doAction(); + } + } + if(exit.isClicked(mousex,mousey)) + { + running = false; + } + } + + drawSelf(); + SDL_Flip(screen); + } } diff --git a/source/code/MenuSystem.h b/source/code/MenuSystem.h index 8d8fb58..9eddc42 100644 --- a/source/code/MenuSystem.h +++ b/source/code/MenuSystem.h @@ -1,23 +1,24 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2008 Poul Sander +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ - blockattack@poulsander.com - http://blockattack.sf.net +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ @@ -33,88 +34,92 @@ Copyright (C) 2008 Poul Sander using namespace std; //The ButtonGfx object hold common media for all buttons, so we can reskin them by only changeing one pointer -class ButtonGfx { - public: - //Holds the graphic for a button that is selected - static CppSdl::CppSdlImageHolder _marked; - //Holds the graphic for a button that is not selected - static CppSdl::CppSdlImageHolder _unmarked; - //The size of the buttons, so we don't have to ask w and h from the SDL Surfaces each time - static int xsize; - static int ysize; - //A TTFont used for writing the label on the buttons - static NFont thefont; - static void setSurfaces(CppSdl::CppSdlImageHolder marked,CppSdl::CppSdlImageHolder unmarked); +class ButtonGfx +{ +public: + //Holds the graphic for a button that is selected + static CppSdl::CppSdlImageHolder _marked; + //Holds the graphic for a button that is not selected + static CppSdl::CppSdlImageHolder _unmarked; + //The size of the buttons, so we don't have to ask w and h from the SDL Surfaces each time + static int xsize; + static int ysize; + //A TTFont used for writing the label on the buttons + static NFont thefont; + static void setSurfaces(CppSdl::CppSdlImageHolder marked,CppSdl::CppSdlImageHolder unmarked); }; //A button -class Button { - private: - //The label. This is written on the button - string label; - //Pointer to a callback function. - void (*action)(Button *b); - - public: - //Is the button marked? - bool marked; - //Where is the button on the screen - int x; - int y; - - Button(); - Button(const Button& b); - ~Button(); - - - //Set the text to write on the button - void setLabel(string text); - //Set the action to run - void setAction(void (*action2run)(Button*)); - - bool isClicked(int x,int y); //Returns true if (x,y) is within the borders of the button - virtual void doAction(); //Run the callback function - void drawTo(SDL_Surface **surface); //Draws to screen +class Button +{ +private: + //The label. This is written on the button + string label; + //Pointer to a callback function. + void (*action)(Button *b); + +public: + //Is the button marked? + bool marked; + //Where is the button on the screen + int x; + int y; + + Button(); + Button(const Button& b); + ~Button(); + + + //Set the text to write on the button + void setLabel(string text); + //Set the action to run + void setAction(void (*action2run)(Button*)); + + bool isClicked(int x,int y); //Returns true if (x,y) is within the borders of the button + virtual void doAction(); //Run the callback function + void drawTo(SDL_Surface **surface); //Draws to screen }; -class Menu { - private: - vector buttons; //Vector holder the buttons - Button exit; //The exit button is special since it does not have a callback function - bool isSubmenu; //True if the menu is a submenu - int marked; //The index of the marked button (for keyboard up/down) - bool running; //The menu is running. The menu will terminate then this is false - SDL_Surface *screen; //Pointer to the screen to draw to - string title; +class Menu +{ +private: + vector buttons; //Vector holder the buttons + Button exit; //The exit button is special since it does not have a callback function + bool isSubmenu; //True if the menu is a submenu + int marked; //The index of the marked button (for keyboard up/down) + bool running; //The menu is running. The menu will terminate then this is false + SDL_Surface *screen; //Pointer to the screen to draw to + string title; // SDL_Surface *background; //Pointer to the background image - - void drawSelf(); //Private function to draw the screen - void performClick(int x, int y); //Private function to call then a click is detected. - void placeButtons(); //Rearanges the buttons to the correct place. - public: - //numberOfItems is the expected numberOfItems for vector initialization - //SubMenu is true by default - Menu(SDL_Surface **screen,bool isSubmenu); - Menu(SDL_Surface **screen); - Menu(SDL_Surface **screen, string title, bool isSubmenu); - - //Add a button to the menu - void addButton(Button *b); - - //Run the menu - void run(); + + void drawSelf(); //Private function to draw the screen + void performClick(int x, int y); //Private function to call then a click is detected. + void placeButtons(); //Rearanges the buttons to the correct place. +public: + //numberOfItems is the expected numberOfItems for vector initialization + //SubMenu is true by default + Menu(SDL_Surface **screen,bool isSubmenu); + Menu(SDL_Surface **screen); + Menu(SDL_Surface **screen, string title, bool isSubmenu); + + //Add a button to the menu + void addButton(Button *b); + + //Run the menu + void run(); }; -class FileMenu { +class FileMenu +{ private: - string pm_path; - string pm_fileending; - bool pm_hidden_files; + string pm_path; + string pm_fileending; + bool pm_hidden_files; public: - FileMenu(string path,string fileending,bool hidden_files = false); - - string getFile(SDL_Surface **screen); + FileMenu(string path,string fileending,bool hidden_files = false); + + string getFile(SDL_Surface **screen); }; #endif /* _MENUSYSTEM_H */ diff --git a/source/code/NetworkThing.hpp b/source/code/NetworkThing.hpp index 0dc1574..fc166cd 100644 --- a/source/code/NetworkThing.hpp +++ b/source/code/NetworkThing.hpp @@ -1,26 +1,24 @@ /* -NetworkThing.hpp -Copyright (C) 2007 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - R�veh�jvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #if NETWORK @@ -29,369 +27,364 @@ Copyright (C) 2007 Poul Sander class NetworkThing { private: - ENetAddress address; - ENetHost * server; - ENetHost * client; - ENetPeer *peer; - - BlockGame *bgHome, *bgAway; //Pointers to the two games, so we can call the procedures - bool weAreAServer, weAreAClient; - bool weAreConnected; - bool enemyIsReady; - bool enemyHasStarted; //If we should have a ready button - bool gameHasStarted; //If the player is GameOver it might just be because the game hasn't started yet... not if this is true! + ENetAddress address; + ENetHost * server; + ENetHost * client; + ENetPeer *peer; + + BlockGame *bgHome, *bgAway; //Pointers to the two games, so we can call the procedures + bool weAreAServer, weAreAClient; + bool weAreConnected; + bool enemyIsReady; + bool enemyHasStarted; //If we should have a ready button + bool gameHasStarted; //If the player is GameOver it might just be because the game hasn't started yet... not if this is true! public: - Uint32 theSeed; - - NetworkThing() - { - weAreAServer = false; - weAreAClient = false; - weAreConnected = false; - enemyIsReady = false; - enemyHasStarted = false; - gameHasStarted = false; - if (enet_initialize () != 0) - { - fprintf (stderr, "An error occurred while initializing ENet.\n"); - } - else - { - cout << "Network is working!" << endl; - } - //atexit (enet_deinitialize); in deconstructor - } - - //This function couses us to remove the connection to the other peer, plus destroying servers - void ntDisconnect() - { - strcpy(bgAway->name,player2name); - if (weAreConnected || weAreAClient || weAreAServer) - { - if (weAreAClient) - { - enet_peer_disconnect (peer,0); - SDL_Delay(20); - enet_host_destroy(client); - weAreAClient = false; - weAreConnected = false; - enemyHasStarted = false; - } - if (weAreAServer) - { - enet_host_destroy(server); - weAreAServer = false; - weAreConnected = false; - enemyHasStarted = false; - } - //If the game is running then we disconnect, we are considered the looser! - if ((!bgHome->isGameOver())&&(!bgAway->isGameOver())) - { - bgAway->setPlayerWon(); - bgHome->SetGameOver(); - } - gameHasStarted = false; - } - }; - - //Lets disconnect before we close... - ~NetworkThing() - { - cout << "Network system is going down" << endl; - ntDisconnect(); - enet_deinitialize(); - cout << "Network system went down" << endl; - } - - void theGameHasStarted() - { - gameHasStarted = true; - } - - //The NetworkThing needs to be able to call the models... here the pointers are set - void setBGpointers(BlockGame *bg1, BlockGame *bg2) - { - bgHome = bg1; - bgAway = bg2; - } - - //Starts a server instance - void startServer() - { - if (!weAreAServer) - { - ntDisconnect(); - - /* Bind the server to the default localhost. */ - /* A specific host address can be specified by */ - /* enet_address_set_host (& address, "x.x.x.x"); */ - - address.host = ENET_HOST_ANY; - /* Bind the server to port SERVERPORT. */ - address.port = SERVERPORT; - - server = enet_host_create (& address /* the address to bind the server host to */, - 1 /* allow up to 1 clients and/or outgoing connections */, - 4 /* allow 4 channels to be used */, - 0 /* assume any amount of incoming bandwidth */, - 0 /* assume any amount of outgoing bandwidth */); - if (server == NULL) - { - fprintf (stderr, - "An error occurred while trying to create an ENet server host.\n"); - - } - else - { - weAreAServer = true; - enemyIsReady = false; - gameHasStarted = false; - cout << "Server is listening on port " << SERVERPORT << endl; - } - } - } - - void connectToServer(string server) - { - ENetAddress address; - ENetEvent event; - - enet_address_set_host (& address, server.c_str()); - address.port = SERVERPORT; - - ntDisconnect(); - client = enet_host_create (NULL /* create a client host */, - 1 /* only allow 1 outgoing connection */, - 4 /* allow 4 channels to be used */, - 0 /* Unlimited downstream bandwidth */, - 0 /* Unlimted upstream bandwidth */); - - if (client == NULL) - { - cout << "An error occurred while trying to create an ENet client host." << endl; - } - else - { - /* Initiate the connection, allocating the four channels 0 and 1 and 2 and 3. */ - peer = enet_host_connect (client, & address, 4,0); - - if (peer == NULL) - { - cout << "No available peers for initiating an ENet connection." << endl; - } - else - if (enet_host_service (client, & event, 2000) > 0 && - event.type == ENET_EVENT_TYPE_CONNECT) - { - cout << "We are connected!" << endl; - enemyIsReady = false; - weAreAClient = true; - weAreConnected = true; - gameHasStarted = false; - } - else - { - cout << "Server didn't answer in time" << endl; - } - } - } - - bool isConnected() - { - return (weAreConnected||weAreAServer); - } - - bool isConnectedToPeer() - { - return weAreConnected; - } - - //This function must be called in the game loop: - void updateNetwork() - { - //Now we must send our own board: - if (weAreConnected) - { - //cout << "Creating package" << endl; - boardPackage boardpack = bgHome->getPackage(); - ENetPacket * packet = enet_packet_create (&boardpack, - sizeof(boardPackage), - 0); - //Now lets send the package - if (weAreAServer) - enet_host_broadcast (server, 0, packet); - else - if (weAreAClient) - enet_peer_send (peer, 0, packet); - //cout << "Package sent" << endl; - - //See if we are game over and in that case notify the other player - if ((gameHasStarted)&&(bgHome->isGameOver())) - { - ENetPacket * packet = enet_packet_create("G",2,ENET_PACKET_FLAG_RELIABLE); - if (weAreAServer) - enet_host_broadcast (server, 1, packet); - else - if (weAreAClient) - enet_peer_send (peer, 1, packet); - gameHasStarted=false; - } - - //Now lets see if we have something to throw at the opponent. - Uint8 x,y,type; - - if (gameHasStarted) - while (bgAway->popGarbage(&x,&y,&type)) - { //if there are garbage to drop - if (type==1) - { - x=255; - y=255; - } - Uint16 g = ((Uint16)x)*256+(Uint16)y; //A 16-bit int containing everything - ENetPacket * packet = enet_packet_create(&g,2,ENET_PACKET_FLAG_RELIABLE); - if (weAreAServer) - enet_host_broadcast (server, 2, packet); - else - if (weAreAClient) - enet_peer_send (peer, 2, packet); - cout << "We send a garbage block: " << (int)x << "," << (int)y << "==" << g << endl; - } - } - ENetEvent event; - - /* Wait up to 0 milliseconds for an event. */ - while (((weAreAClient)&&(enet_host_service (client, & event, 0) > 0))||((weAreAServer)&&(enet_host_service (server, & event, 0) > 0))) - { - switch (event.type) - { - case ENET_EVENT_TYPE_CONNECT: - printf ("A new client connected from %x:%u.\n", - event.peer -> address.host, - event.peer -> address.port); - weAreConnected = true; - /* Store any relevant client information here. */ - //event.peer -> data = "Client"; - { - - ENetPacket * namePacket = enet_packet_create(bgHome->name,sizeof(char[30]),ENET_PACKET_FLAG_RELIABLE); - //if(weAreAServer) - enet_host_broadcast (server, 3, namePacket); - ENetPacket * answerPacket = enet_packet_create("version3",sizeof("version3"),ENET_PACKET_FLAG_RELIABLE); - enet_host_broadcast (server, 3, answerPacket); - theSeed = time(0)/4; - bgHome->putStartBlocks(theSeed); - ENetPacket * timePacket = enet_packet_create(&theSeed,sizeof(theSeed),ENET_PACKET_FLAG_RELIABLE); - enet_host_broadcast (server, 3, timePacket); - cout << "We send the seed: " << theSeed << endl; - } - break; - - case ENET_EVENT_TYPE_RECEIVE: - /*printf ("A packet of length %u containing %s was received from %s on channel %u.\n", - event.packet -> dataLength, - event.packet -> data, - event.peer -> data, - event.channelID);*/ - //cout << "Package recieved" << endl; - if (event.channelID==0) //Unreliable (only boardPacks) - { - boardPackage bpack; - //cout << "Package size: "<< event.packet->dataLength << " should be: " << sizeof(boardPackage) << endl; - memcpy(&bpack,(const char*)event.packet->data,sizeof(boardPackage)); - bgAway->setBoard(bpack); - } - if (event.channelID==1) //reliable (used for GameOver notifications only!) - { - if ((bgHome->isGameOver())&&(!bgHome->GetIsWinner())&&(gameHasStarted)) - { - bgHome->setDraw(); - bgAway->setDraw(); - } - else - { - bgHome->setPlayerWon(); - bgAway->SetGameOver(); - } - gameHasStarted=false; - } - - if (event.channelID==2) //reliable (used for Garbage only!) - { - Uint16 g; - memcpy(&g,event.packet->data,sizeof(Uint16)); - Uint8 x = (g/256); - Uint8 y = (g%256); - cout << "Recieved Garbage: " << (int)x << "," << (int)y << endl; - if ((x==255)&&(y==255)) - bgHome->CreateGreyGarbage(); - else - bgHome->CreateGarbage(x,y); - } - - if (event.channelID==3) //We have reacieved a name or a version number - { - if (event.packet->dataLength==sizeof(char[30])) //We have reveived a name - { - strcpy(bgAway->name,(const char*)event.packet->data); - cout << "The enemy name is: " << bgAway->name << " Length: " << sizeof(char[30])<< endl; - if (weAreAClient) //We have just recieved the servers name and must send our own - { - ENetPacket * answerPacket = enet_packet_create(bgHome->name,sizeof(char[30]),ENET_PACKET_FLAG_RELIABLE); - enet_peer_send (peer, 3, answerPacket); - } - } - else - if (event.packet->dataLength==sizeof("version3")) //We have recieved aversion number - { - if (0!=strcmp((const char*)event.packet->data,"version3")) - { - cout << "Incompatible version: " << event.packet->data << "!=" << "version3" << endl; - ntDisconnect(); - } - if (weAreAClient) //We will send our version number - { - ENetPacket * answerPacket = enet_packet_create("version3",sizeof("version3"),ENET_PACKET_FLAG_RELIABLE); - enet_peer_send (peer, 3, answerPacket); - } - } - else - if (event.packet->dataLength==sizeof(Uint32)) //We have recieved a seed - { - memcpy(&theSeed,event.packet->data,sizeof(Uint32)); - bgHome->putStartBlocks(theSeed); - cout << "We recieved a seed: " << theSeed << endl; - } - } - - /* Clean up the packet now that we're done using it. */ - enet_packet_destroy (event.packet); - - break; - - case ENET_EVENT_TYPE_DISCONNECT: - //printf ("%s disconected.\n", event.peer -> data); - cout << event.peer -> data << " disconnected." << endl; - - /* Reset the peer's client information. */ - - event.peer -> data = NULL; - //weAreConnected = false; - if ((!bgHome->isGameOver())&&(!bgAway->isGameOver())) - { - bgHome->setPlayerWon(); - bgAway->SetGameOver(); - } - - ntDisconnect(); //When we will disconnect! - - } - } - - - } + Uint32 theSeed; + + NetworkThing() + { + weAreAServer = false; + weAreAClient = false; + weAreConnected = false; + enemyIsReady = false; + enemyHasStarted = false; + gameHasStarted = false; + if (enet_initialize () != 0) + { + fprintf (stderr, "An error occurred while initializing ENet.\n"); + } + else + { + cout << "Network is working!" << endl; + } + //atexit (enet_deinitialize); in deconstructor + } + + //This function couses us to remove the connection to the other peer, plus destroying servers + void ntDisconnect() + { + strcpy(bgAway->name,player2name); + if (weAreConnected || weAreAClient || weAreAServer) + { + if (weAreAClient) + { + enet_peer_disconnect (peer,0); + SDL_Delay(20); + enet_host_destroy(client); + weAreAClient = false; + weAreConnected = false; + enemyHasStarted = false; + } + if (weAreAServer) + { + enet_host_destroy(server); + weAreAServer = false; + weAreConnected = false; + enemyHasStarted = false; + } + //If the game is running then we disconnect, we are considered the looser! + if ((!bgHome->isGameOver())&&(!bgAway->isGameOver())) + { + bgAway->setPlayerWon(); + bgHome->SetGameOver(); + } + gameHasStarted = false; + } + }; + + //Lets disconnect before we close... + ~NetworkThing() + { + cout << "Network system is going down" << endl; + ntDisconnect(); + enet_deinitialize(); + cout << "Network system went down" << endl; + } + + void theGameHasStarted() + { + gameHasStarted = true; + } + + //The NetworkThing needs to be able to call the models... here the pointers are set + void setBGpointers(BlockGame *bg1, BlockGame *bg2) + { + bgHome = bg1; + bgAway = bg2; + } + + //Starts a server instance + void startServer() + { + if (!weAreAServer) + { + ntDisconnect(); + + /* Bind the server to the default localhost. */ + /* A specific host address can be specified by */ + /* enet_address_set_host (& address, "x.x.x.x"); */ + + address.host = ENET_HOST_ANY; + /* Bind the server to port SERVERPORT. */ + address.port = SERVERPORT; + + server = enet_host_create (& address /* the address to bind the server host to */, + 1 /* allow up to 1 clients and/or outgoing connections */, + 4 /* allow 4 channels to be used */, + 0 /* assume any amount of incoming bandwidth */, + 0 /* assume any amount of outgoing bandwidth */); + if (server == NULL) + { + fprintf (stderr, + "An error occurred while trying to create an ENet server host.\n"); + + } + else + { + weAreAServer = true; + enemyIsReady = false; + gameHasStarted = false; + cout << "Server is listening on port " << SERVERPORT << endl; + } + } + } + + void connectToServer(string server) + { + ENetAddress address; + ENetEvent event; + + enet_address_set_host (& address, server.c_str()); + address.port = SERVERPORT; + + ntDisconnect(); + client = enet_host_create (NULL /* create a client host */, + 1 /* only allow 1 outgoing connection */, + 4 /* allow 4 channels to be used */, + 0 /* Unlimited downstream bandwidth */, + 0 /* Unlimted upstream bandwidth */); + + if (client == NULL) + { + cout << "An error occurred while trying to create an ENet client host." << endl; + } + else + { + /* Initiate the connection, allocating the four channels 0 and 1 and 2 and 3. */ + peer = enet_host_connect (client, & address, 4,0); + + if (peer == NULL) + { + cout << "No available peers for initiating an ENet connection." << endl; + } + else if (enet_host_service (client, & event, 2000) > 0 && + event.type == ENET_EVENT_TYPE_CONNECT) + { + cout << "We are connected!" << endl; + enemyIsReady = false; + weAreAClient = true; + weAreConnected = true; + gameHasStarted = false; + } + else + { + cout << "Server didn't answer in time" << endl; + } + } + } + + bool isConnected() + { + return (weAreConnected||weAreAServer); + } + + bool isConnectedToPeer() + { + return weAreConnected; + } + + //This function must be called in the game loop: + void updateNetwork() + { + //Now we must send our own board: + if (weAreConnected) + { + //cout << "Creating package" << endl; + boardPackage boardpack = bgHome->getPackage(); + ENetPacket * packet = enet_packet_create (&boardpack, + sizeof(boardPackage), + 0); + //Now lets send the package + if (weAreAServer) + enet_host_broadcast (server, 0, packet); + else if (weAreAClient) + enet_peer_send (peer, 0, packet); + //cout << "Package sent" << endl; + + //See if we are game over and in that case notify the other player + if ((gameHasStarted)&&(bgHome->isGameOver())) + { + ENetPacket * packet = enet_packet_create("G",2,ENET_PACKET_FLAG_RELIABLE); + if (weAreAServer) + enet_host_broadcast (server, 1, packet); + else if (weAreAClient) + enet_peer_send (peer, 1, packet); + gameHasStarted=false; + } + + //Now lets see if we have something to throw at the opponent. + Uint8 x,y,type; + + if (gameHasStarted) + while (bgAway->popGarbage(&x,&y,&type)) + { + //if there are garbage to drop + if (type==1) + { + x=255; + y=255; + } + Uint16 g = ((Uint16)x)*256+(Uint16)y; //A 16-bit int containing everything + ENetPacket * packet = enet_packet_create(&g,2,ENET_PACKET_FLAG_RELIABLE); + if (weAreAServer) + enet_host_broadcast (server, 2, packet); + else if (weAreAClient) + enet_peer_send (peer, 2, packet); + cout << "We send a garbage block: " << (int)x << "," << (int)y << "==" << g << endl; + } + } + ENetEvent event; + + /* Wait up to 0 milliseconds for an event. */ + while (((weAreAClient)&&(enet_host_service (client, & event, 0) > 0))||((weAreAServer)&&(enet_host_service (server, & event, 0) > 0))) + { + switch (event.type) + { + case ENET_EVENT_TYPE_CONNECT: + printf ("A new client connected from %x:%u.\n", + event.peer -> address.host, + event.peer -> address.port); + weAreConnected = true; + /* Store any relevant client information here. */ + //event.peer -> data = "Client"; + { + + ENetPacket * namePacket = enet_packet_create(bgHome->name,sizeof(char[30]),ENET_PACKET_FLAG_RELIABLE); + //if(weAreAServer) + enet_host_broadcast (server, 3, namePacket); + ENetPacket * answerPacket = enet_packet_create("version3",sizeof("version3"),ENET_PACKET_FLAG_RELIABLE); + enet_host_broadcast (server, 3, answerPacket); + theSeed = time(0)/4; + bgHome->putStartBlocks(theSeed); + ENetPacket * timePacket = enet_packet_create(&theSeed,sizeof(theSeed),ENET_PACKET_FLAG_RELIABLE); + enet_host_broadcast (server, 3, timePacket); + cout << "We send the seed: " << theSeed << endl; + } + break; + + case ENET_EVENT_TYPE_RECEIVE: + /*printf ("A packet of length %u containing %s was received from %s on channel %u.\n", + event.packet -> dataLength, + event.packet -> data, + event.peer -> data, + event.channelID);*/ + //cout << "Package recieved" << endl; + if (event.channelID==0) //Unreliable (only boardPacks) + { + boardPackage bpack; + //cout << "Package size: "<< event.packet->dataLength << " should be: " << sizeof(boardPackage) << endl; + memcpy(&bpack,(const char*)event.packet->data,sizeof(boardPackage)); + bgAway->setBoard(bpack); + } + if (event.channelID==1) //reliable (used for GameOver notifications only!) + { + if ((bgHome->isGameOver())&&(!bgHome->GetIsWinner())&&(gameHasStarted)) + { + bgHome->setDraw(); + bgAway->setDraw(); + } + else + { + bgHome->setPlayerWon(); + bgAway->SetGameOver(); + } + gameHasStarted=false; + } + + if (event.channelID==2) //reliable (used for Garbage only!) + { + Uint16 g; + memcpy(&g,event.packet->data,sizeof(Uint16)); + Uint8 x = (g/256); + Uint8 y = (g%256); + cout << "Recieved Garbage: " << (int)x << "," << (int)y << endl; + if ((x==255)&&(y==255)) + bgHome->CreateGreyGarbage(); + else + bgHome->CreateGarbage(x,y); + } + + if (event.channelID==3) //We have reacieved a name or a version number + { + if (event.packet->dataLength==sizeof(char[30])) //We have reveived a name + { + strcpy(bgAway->name,(const char*)event.packet->data); + cout << "The enemy name is: " << bgAway->name << " Length: " << sizeof(char[30])<< endl; + if (weAreAClient) //We have just recieved the servers name and must send our own + { + ENetPacket * answerPacket = enet_packet_create(bgHome->name,sizeof(char[30]),ENET_PACKET_FLAG_RELIABLE); + enet_peer_send (peer, 3, answerPacket); + } + } + else if (event.packet->dataLength==sizeof("version3")) //We have recieved aversion number + { + if (0!=strcmp((const char*)event.packet->data,"version3")) + { + cout << "Incompatible version: " << event.packet->data << "!=" << "version3" << endl; + ntDisconnect(); + } + if (weAreAClient) //We will send our version number + { + ENetPacket * answerPacket = enet_packet_create("version3",sizeof("version3"),ENET_PACKET_FLAG_RELIABLE); + enet_peer_send (peer, 3, answerPacket); + } + } + else if (event.packet->dataLength==sizeof(Uint32)) //We have recieved a seed + { + memcpy(&theSeed,event.packet->data,sizeof(Uint32)); + bgHome->putStartBlocks(theSeed); + cout << "We recieved a seed: " << theSeed << endl; + } + } + + /* Clean up the packet now that we're done using it. */ + enet_packet_destroy (event.packet); + + break; + + case ENET_EVENT_TYPE_DISCONNECT: + //printf ("%s disconected.\n", event.peer -> data); + cout << event.peer -> data << " disconnected." << endl; + + /* Reset the peer's client information. */ + + event.peer -> data = NULL; + //weAreConnected = false; + if ((!bgHome->isGameOver())&&(!bgAway->isGameOver())) + { + bgHome->setPlayerWon(); + bgAway->SetGameOver(); + } + + ntDisconnect(); //When we will disconnect! + + } + } + + + } }; //NetworkThing #endif diff --git a/source/code/ReadKeyboard.cpp b/source/code/ReadKeyboard.cpp index 816d783..1ff83b1 100644 --- a/source/code/ReadKeyboard.cpp +++ b/source/code/ReadKeyboard.cpp @@ -1,33 +1,34 @@ /* -ReadKeyboard.cpp -Copyright (C) 2005 Poul Sander +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ - Poul Sander - blockattack@poulsander.com +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include "ReadKeyboard.h" ReadKeyboard::ReadKeyboard(void) { - length = 0; - maxLength = 16; - position = 0; - strcpy(textstring," "); + length = 0; + maxLength = 16; + position = 0; + strcpy(textstring," "); } ReadKeyboard::~ReadKeyboard(void) @@ -36,343 +37,342 @@ ReadKeyboard::~ReadKeyboard(void) Uint8 ReadKeyboard::CharsBeforeCursor() { - return position; + return position; } ReadKeyboard::ReadKeyboard(char *oldName) { - length = 0; - maxLength = 16; - position = 0; - strcpy(textstring," "); - strcpy(textstring,oldName); - char charecter = textstring[maxLength+1]; - int i = maxLength+1; - while ((charecter == ' ') && (i>0)) - { - i--; - charecter = textstring[i]; - } - if (i>0)length = i+1; - else - if (charecter == ' ') length = 0; - else length = 1; - position = length; + length = 0; + maxLength = 16; + position = 0; + strcpy(textstring," "); + strcpy(textstring,oldName); + char charecter = textstring[maxLength+1]; + int i = maxLength+1; + while ((charecter == ' ') && (i>0)) + { + i--; + charecter = textstring[i]; + } + if (i>0)length = i+1; + else if (charecter == ' ') length = 0; + else length = 1; + position = length; } void ReadKeyboard::putchar(char thing) { - if (length < maxLength) - { - for (int i = 28; i>position;i--) - { - textstring[i]=textstring[i-1]; - } - textstring[position] = thing; - length++; - position++; - } + if (length < maxLength) + { + for (int i = 28; i>position; i--) + { + textstring[i]=textstring[i-1]; + } + textstring[position] = thing; + length++; + position++; + } } void ReadKeyboard::removeChar() { - for (int i = position;i<28;i++) - { - textstring[i]=textstring[i+1]; - } - textstring[28]=' '; - if (length>0)length--; + for (int i = position; i<28; i++) + { + textstring[i]=textstring[i+1]; + } + textstring[28]=' '; + if (length>0)length--; } bool ReadKeyboard::ReadKey(SDLKey keyPressed) { - if (keyPressed == SDLK_SPACE) - { - ReadKeyboard::putchar(' '); - return true; - } - if (keyPressed == SDLK_DELETE) - { - if ((length>0)&& (position0) - { - position--; - ReadKeyboard::removeChar(); - return true; - } - return false; - } - Uint8* keys; - keys = SDL_GetKeyState(NULL); - if (keyPressed == SDLK_HOME) - { - position=0; - return true; - } - if (keyPressed == SDLK_END) - { - position=length; - return true; - } - if ((keyPressed == SDLK_LEFT) && (position>0)) - { - position--; - return true; - } - if ((keyPressed == SDLK_RIGHT) && (position0)&& (position0) + { + position--; + ReadKeyboard::removeChar(); + return true; + } + return false; + } + Uint8* keys; + keys = SDL_GetKeyState(NULL); + if (keyPressed == SDLK_HOME) + { + position=0; + return true; + } + if (keyPressed == SDLK_END) + { + position=length; + return true; + } + if ((keyPressed == SDLK_LEFT) && (position>0)) + { + position--; + return true; + } + if ((keyPressed == SDLK_RIGHT) && (position> val; - return val; - }catch(ios_base::failure f) - { - return 0.0; - } + try + { + stringstream converter(str2parse); + double val = 0.0; + converter >> val; + return val; + } + catch(ios_base::failure f) + { + return 0.0; + } } /** @@ -67,37 +66,40 @@ double str2double(string str2parse) */ int str2int(string str2parse) { - try{ - stringstream converter(str2parse); - int val = 0; - converter >> val; - return val; - }catch(ios_base::failure f) - { - return 0; - } + try + { + stringstream converter(str2parse); + int val = 0; + converter >> val; + return val; + } + catch(ios_base::failure f) + { + return 0; + } } #ifdef WIN32 //Returns path to "my Documents" in windows: string getMyDocumentsPath() { - TCHAR pszPath[MAX_PATH]; - //if (SUCCEEDED(SHGetSpecialFolderPath(NULL, pszPath, CSIDL_PERSONAL, FALSE))) { - if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, pszPath))) { - // pszPath is now the path that you want + TCHAR pszPath[MAX_PATH]; + //if (SUCCEEDED(SHGetSpecialFolderPath(NULL, pszPath, CSIDL_PERSONAL, FALSE))) { + if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, pszPath))) + { + // pszPath is now the path that you want #if DEBUG - cout << "MyDocuments Located: " << pszPath << endl; + cout << "MyDocuments Located: " << pszPath << endl; #endif - string theResult= pszPath; - return theResult; - } - else - { - cout << "Warning: My Documents not found!" << endl; - string theResult =""; - return theResult; - } + string theResult= pszPath; + return theResult; + } + else + { + cout << "Warning: My Documents not found!" << endl; + string theResult =""; + return theResult; + } } #endif @@ -111,11 +113,11 @@ string getMyDocumentsPath() string getPathToSaveFiles() { #ifdef __unix__ - return (string)getenv("HOME")+(string)"/.gamesaves/"+GAMENAME; + return (string)getenv("HOME")+(string)"/.gamesaves/"+GAMENAME; #elif WIN32 - return getMyDocumentsPath()+(string)"/My Games/"+GAMENAME; + return getMyDocumentsPath()+(string)"/My Games/"+GAMENAME; #else - return "."; + return "."; #endif } @@ -124,49 +126,49 @@ string getPathToSaveFiles() */ commonTime TimeHandler::ms2ct(unsigned int milliseconds) { - commonTime ct; - ct.days = 0; - unsigned int time = milliseconds; - ct.hours = time/(1000*60*60); - time = time % (1000*60*60); - ct.minutes = time/(1000*60); - time = time % (1000*60); - ct.seconds = time/1000; - return ct; + commonTime ct; + ct.days = 0; + unsigned int time = milliseconds; + ct.hours = time/(1000*60*60); + time = time % (1000*60*60); + ct.minutes = time/(1000*60); + time = time % (1000*60); + ct.seconds = time/1000; + return ct; } commonTime TimeHandler::getTime(string name) { - commonTime ct; - ct.days = Config::getInstance()->getInt(name+"Days"); - ct.hours = Config::getInstance()->getInt(name+"Hours"); - ct.minutes = Config::getInstance()->getInt(name+"Minutes"); - ct.seconds = Config::getInstance()->getInt(name+"Seconds"); - return ct; + commonTime ct; + ct.days = Config::getInstance()->getInt(name+"Days"); + ct.hours = Config::getInstance()->getInt(name+"Hours"); + ct.minutes = Config::getInstance()->getInt(name+"Minutes"); + ct.seconds = Config::getInstance()->getInt(name+"Seconds"); + return ct; } /** - * Returns the total runtime with toAdd added but without writing it to config file. + * Returns the total runtime with toAdd added but without writing it to config file. * Used for stats */ commonTime TimeHandler::peekTime(string name, commonTime toAdd) { - commonTime ct = getTime(name); + commonTime ct = getTime(name); - ct.seconds +=toAdd.seconds; - ct.minutes +=ct.seconds/60; - ct.seconds = ct.seconds%60; + ct.seconds +=toAdd.seconds; + ct.minutes +=ct.seconds/60; + ct.seconds = ct.seconds%60; - ct.minutes += toAdd.minutes; - ct.hours += ct.minutes/60; - ct.minutes = ct.minutes%60; + ct.minutes += toAdd.minutes; + ct.hours += ct.minutes/60; + ct.minutes = ct.minutes%60; - ct.hours += toAdd.hours; - ct.days += ct.hours/24; - ct.hours = ct.hours%24; + ct.hours += toAdd.hours; + ct.days += ct.hours/24; + ct.hours = ct.hours%24; - ct.days += toAdd.days; - return ct; + ct.days += toAdd.days; + return ct; } /** @@ -175,140 +177,142 @@ commonTime TimeHandler::peekTime(string name, commonTime toAdd) */ commonTime TimeHandler::addTime(string name, commonTime toAdd) { - commonTime ct = peekTime(name,toAdd); - - Config::getInstance()->setInt(name+"Days",ct.days); - Config::getInstance()->setInt(name+"Hours",ct.hours); - Config::getInstance()->setInt(name+"Minutes",ct.minutes); - Config::getInstance()->setInt(name+"Seconds",ct.seconds); - return ct; + commonTime ct = peekTime(name,toAdd); + + Config::getInstance()->setInt(name+"Days",ct.days); + Config::getInstance()->setInt(name+"Hours",ct.hours); + Config::getInstance()->setInt(name+"Minutes",ct.minutes); + Config::getInstance()->setInt(name+"Seconds",ct.seconds); + return ct; } Config* Config::instance = 0; Config::Config() { - configMap.clear(); - load(); - shuttingDown = 0; // Not shutting down + configMap.clear(); + load(); + shuttingDown = 0; // Not shutting down } void Config::load() { - string filename = getPathToSaveFiles()+"/configFile"; - ifstream inFile(filename.c_str()); - string key; - string previuskey; - char value[MAX_VAR_LENGTH]; - if(inFile) - { - while(!inFile.eof()) - { - inFile >> key; - if(key==previuskey) //the last entry will be read 2 times if a linebreak is missing in the end - continue; - previuskey = key; - inFile.get(); //Read the space between the key and the content - inFile.getline(value,MAX_VAR_LENGTH); - #if DEBUG - cout << "Config "<< "read: " << key << " with:\"" << value << "\"" << endl; - #endif - configMap[key] = (string)value; - } - inFile.close(); - } + string filename = getPathToSaveFiles()+"/configFile"; + ifstream inFile(filename.c_str()); + string key; + string previuskey; + char value[MAX_VAR_LENGTH]; + if(inFile) + { + while(!inFile.eof()) + { + inFile >> key; + if(key==previuskey) //the last entry will be read 2 times if a linebreak is missing in the end + continue; + previuskey = key; + inFile.get(); //Read the space between the key and the content + inFile.getline(value,MAX_VAR_LENGTH); +#if DEBUG + cout << "Config "<< "read: " << key << " with:\"" << value << "\"" << endl; +#endif + configMap[key] = (string)value; + } + inFile.close(); + } } Config* Config::getInstance() { - if(Config::instance==0) - { - Config::instance = new Config(); - - } - return Config::instance; + if(Config::instance==0) + { + Config::instance = new Config(); + + } + return Config::instance; } void Config::save() { - string filename = getPathToSaveFiles()+"/configFile"; - ofstream outFile(filename.c_str(),ios::trunc); - - if(outFile) - { - map::iterator iter; - for(iter = configMap.begin(); iter != configMap.end(); iter++) - { - outFile << iter->first << " " << iter->second << endl; - } - outFile << "\n"; //The last entry in the file will be read double if a linebreak is missing - //This is checked on load too in case a user changes it himself. - } - outFile.close(); + string filename = getPathToSaveFiles()+"/configFile"; + ofstream outFile(filename.c_str(),ios::trunc); + + if(outFile) + { + map::iterator iter; + for(iter = configMap.begin(); iter != configMap.end(); iter++) + { + outFile << iter->first << " " << iter->second << endl; + } + outFile << "\n"; //The last entry in the file will be read double if a linebreak is missing + //This is checked on load too in case a user changes it himself. + } + outFile.close(); } bool Config::exists(string varName) const { - //Using that find returns an iterator to the end of the map if not found - return configMap.find(varName) != configMap.end(); + //Using that find returns an iterator to the end of the map if not found + return configMap.find(varName) != configMap.end(); } void Config::setDefault(string varName,string content) { - if(exists(varName)) - return; //Already exists do not change - setString(varName,content); + if(exists(varName)) + return; //Already exists do not change + setString(varName,content); } -void Config::setShuttingDown(long shuttingDown) { - this->shuttingDown = shuttingDown; +void Config::setShuttingDown(long shuttingDown) +{ + this->shuttingDown = shuttingDown; } -long Config::isShuttingDown() const { - return shuttingDown; +long Config::isShuttingDown() const +{ + return shuttingDown; } void Config::setString(string varName, string content) { - configMap[varName] = content; + configMap[varName] = content; } void Config::setInt(string varName, int content) { - configMap[varName] = itoa(content); + configMap[varName] = itoa(content); } void Config::setValue(string varName,double content) { - configMap[varName] = double2str(content); + configMap[varName] = double2str(content); } string Config::getString(string varName) { - if(exists(varName)) - { - return configMap[varName]; - } - else - return ""; + if(exists(varName)) + { + return configMap[varName]; + } + else + return ""; } int Config::getInt(string varName) { - if(exists(varName)) - { - return str2int(configMap[varName]); - } - else - return 0; + if(exists(varName)) + { + return str2int(configMap[varName]); + } + else + return 0; } double Config::getValue(string varName) { - if(exists(varName)) - { - return str2double(configMap[varName]); - } - else - return 0.0; + if(exists(varName)) + { + return str2double(configMap[varName]); + } + else + return 0.0; } diff --git a/source/code/common.h b/source/code/common.h index 0a2e2eb..c1bf53b 100644 --- a/source/code/common.h +++ b/source/code/common.h @@ -1,27 +1,24 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2008 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - R�vehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ /* @@ -57,11 +54,12 @@ Copyright (C) 2008 Poul Sander using namespace std; using boost::format; -struct commonTime{ - unsigned int days; - unsigned int hours; - unsigned int minutes; - unsigned int seconds; +struct commonTime +{ + unsigned int days; + unsigned int hours; + unsigned int minutes; + unsigned int seconds; }; string itoa(int num) __attribute__((const)); @@ -93,11 +91,11 @@ class TimeHandler { public: static commonTime ms2ct(unsigned int milliseconds); - + static commonTime getTime(string name); - + static commonTime peekTime(string name, commonTime toAdd); - + static commonTime addTime(string name, commonTime toAdd); }; @@ -111,100 +109,100 @@ public: */ class Config { -private: - map configMap; - - static Config *instance; - - void load(); - - /* tells if the user has requested a shutdown */ - long shuttingDown; +private: + map configMap; + + static Config *instance; + + void load(); + + /* tells if the user has requested a shutdown */ + long shuttingDown; protected: - - Config(); - - + + Config(); + + public: - /*Config is a singleton. - *It is accessed like this: - *Config::getInstance()->method2call(paramters); - */ - static Config* getInstance(); - - /*save() - *forces the config to be written to disk. This will also happened if the - *program terminates normally. - */ - void save(); - - /*getString(varName) - *Looks in the config file and returns the string that matches the key "varName" - *Returns an empty string if varName does not exist. - */ - string getString(string varName); - - /*getInt(varName) - *Looks in the config file and returns the int that matches the key "varName" - *Returns "0" if varName does not exist or cannot be parsed. - */ - int getInt(string varName); - - /*getValue(varName) - *Looks in the config file and returns the double that matches the key "varName" - *Returns "0.0" if varName does not exist or cannot be parsed. - */ - double getValue(string varName); - - /*setString(varName,content) - *Sets the config variable with key "varName" to the value of "content" - */ - void setString(string varName,string content); - - /*setInt(varName,content) - *Sets the config variable with key "varName" to the value of "content" - */ - void setInt(string varName,int content); - - /** - * Sets a config variable to a given (double) value - * @param varName Name of the variable to set - * @param content Value to give the variable - */ - void setValue(string varName,double content); - - /** - * returns true if the key varName exists. This is used the first time 1.4.0 - * starts so that it can see that it has to import configs from an earlier - * version. - * @param varName Name of the variable - * @return true if the varaible exists - */ - bool exists(string varName) const; - - /*setDefault(varName,value) - *if the variable "varName" does not exist it will be created with value "value" - *if varName exists then this will have no effect - */ - /** - * Set default value for a variable. If the variable "varName" does not exist it will be created with value "value" - * if varName exists then this will have no effect - * @param varName Name of the variable - * @param content The default value - */ - void setDefault(string varName, string content); - - /** - * Should be set if the user has requested the program to shutdown. - * @param shuttingDown value of shutdown command. 5 = default = shutdown but allow saving - */ - void setShuttingDown(long shuttingDown = 5); - - /** - * tells if the user wants to shutdown. This can be used if the exit button is pressed deaply in the program. - * @return - */ - long isShuttingDown() const; + /*Config is a singleton. + *It is accessed like this: + *Config::getInstance()->method2call(paramters); + */ + static Config* getInstance(); + + /*save() + *forces the config to be written to disk. This will also happened if the + *program terminates normally. + */ + void save(); + + /*getString(varName) + *Looks in the config file and returns the string that matches the key "varName" + *Returns an empty string if varName does not exist. + */ + string getString(string varName); + + /*getInt(varName) + *Looks in the config file and returns the int that matches the key "varName" + *Returns "0" if varName does not exist or cannot be parsed. + */ + int getInt(string varName); + + /*getValue(varName) + *Looks in the config file and returns the double that matches the key "varName" + *Returns "0.0" if varName does not exist or cannot be parsed. + */ + double getValue(string varName); + + /*setString(varName,content) + *Sets the config variable with key "varName" to the value of "content" + */ + void setString(string varName,string content); + + /*setInt(varName,content) + *Sets the config variable with key "varName" to the value of "content" + */ + void setInt(string varName,int content); + + /** + * Sets a config variable to a given (double) value + * @param varName Name of the variable to set + * @param content Value to give the variable + */ + void setValue(string varName,double content); + + /** + * returns true if the key varName exists. This is used the first time 1.4.0 + * starts so that it can see that it has to import configs from an earlier + * version. + * @param varName Name of the variable + * @return true if the varaible exists + */ + bool exists(string varName) const; + + /*setDefault(varName,value) + *if the variable "varName" does not exist it will be created with value "value" + *if varName exists then this will have no effect + */ + /** + * Set default value for a variable. If the variable "varName" does not exist it will be created with value "value" + * if varName exists then this will have no effect + * @param varName Name of the variable + * @param content The default value + */ + void setDefault(string varName, string content); + + /** + * Should be set if the user has requested the program to shutdown. + * @param shuttingDown value of shutdown command. 5 = default = shutdown but allow saving + */ + void setShuttingDown(long shuttingDown = 5); + + /** + * tells if the user wants to shutdown. This can be used if the exit button is pressed deaply in the program. + * @return + */ + long isShuttingDown() const; }; #endif /* _COMMON_H */ diff --git a/source/code/editor/BoardHolder.cpp b/source/code/editor/BoardHolder.cpp index b4cad67..e1c70fb 100644 --- a/source/code/editor/BoardHolder.cpp +++ b/source/code/editor/BoardHolder.cpp @@ -1,154 +1,151 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2007 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - Raevehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include "BoardHolder.hpp" BoardHolder::BoardHolder(string filename) { - fstream inFile(filename.c_str(),ios::in); - if(inFile) - { - int nrOfBoards; - inFile >> nrOfBoards; - for(int i=0;i> nrOfBoards; + for(int i=0; i> temp; + ourBoard.setNumberOfMoves(temp); + for(int j=0; j<12; j++) { - TheBoard ourBoard; - int temp; - inFile >> temp; - ourBoard.setNumberOfMoves(temp); - for(int j=0;j<12;j++) + for(int k=0; k<6; k++) { - for(int k=0;k<6;k++) - { - inFile >> temp; - ourBoard.setBrick(k,j,temp); - } + inFile >> temp; + ourBoard.setBrick(k,j,temp); } - theBoards[i] = ourBoard; } + theBoards[i] = ourBoard; + } isNull = false; - } + } } BoardHolder::BoardHolder() { - isNull = false; + isNull = false; } bool BoardHolder::saveBoards(string filename) { - fstream outFile(filename.c_str(),ios::out); - if(outFile) - { - outFile << getNumberOfBoards() << endl; - for(int i=0;i49)||(nr<0)) - return false; - theBoards[nr] = model; - return true; + if((nr>49)||(nr<0)) + return false; + theBoards[nr] = model; + return true; } int BoardHolder::getNumberOfBoards() { - return theBoards.size(); + return theBoards.size(); } bool BoardHolder::addBoard() { - if(!(theBoards.size()<49)) - return false; - TheBoard tb; - theBoards[theBoards.size()] = tb; - return true; + if(!(theBoards.size()<49)) + return false; + TheBoard tb; + theBoards[theBoards.size()] = tb; + return true; } bool BoardHolder::removeBoard(int nr) { - vector::iterator itr; - itr = theBoards.begin(); - itr+=nr; - theBoards.erase(itr); + vector::iterator itr; + itr = theBoards.begin(); + itr+=nr; + theBoards.erase(itr); } bool BoardHolder::moveBoardBack(int nr) { - if(nr<1) //We can't move back - return false; - if(nr>getNumberOfBoards()) - return false; - TheBoard temp = theBoards[nr]; - theBoards[nr] = theBoards[nr-1]; - theBoards[nr-1] = temp; - return true; + if(nr<1) //We can't move back + return false; + if(nr>getNumberOfBoards()) + return false; + TheBoard temp = theBoards[nr]; + theBoards[nr] = theBoards[nr-1]; + theBoards[nr-1] = temp; + return true; } bool BoardHolder::moveBoardForward(int nr) { - if(nr>getNumberOfBoards()-2) //We can't move forward - return false; - if(nr<0) - return false; - TheBoard temp = theBoards[nr]; - theBoards[nr] = theBoards[nr+1]; - theBoards[nr+1] = temp; - return true; + if(nr>getNumberOfBoards()-2) //We can't move forward + return false; + if(nr<0) + return false; + TheBoard temp = theBoards[nr]; + theBoards[nr] = theBoards[nr+1]; + theBoards[nr+1] = temp; + return true; } diff --git a/source/code/editor/BoardHolder.hpp b/source/code/editor/BoardHolder.hpp index 18661fe..db32c5e 100644 --- a/source/code/editor/BoardHolder.hpp +++ b/source/code/editor/BoardHolder.hpp @@ -1,27 +1,24 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2007 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - Rævehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include "TheBoard.hpp" @@ -34,21 +31,21 @@ Copyright (C) 2007 Poul Sander #define BOARDHOLDERDEFINED class BoardHolder { - - private: - vector theBoards; - - public: - bool isNull; - BoardHolder(); - BoardHolder(string filename); - bool saveBoards(string filename); - TheBoard getModel(int); - bool setModel(int nr,TheBoard model); - int getNumberOfBoards(); - bool addBoard(); - bool removeBoard(int); - bool moveBoardBack(int); - bool moveBoardForward(int); + +private: + vector theBoards; + +public: + bool isNull; + BoardHolder(); + BoardHolder(string filename); + bool saveBoards(string filename); + TheBoard getModel(int); + bool setModel(int nr,TheBoard model); + int getNumberOfBoards(); + bool addBoard(); + bool removeBoard(int); + bool moveBoardBack(int); + bool moveBoardForward(int); }; #endif diff --git a/source/code/editor/EditorInterface.cpp b/source/code/editor/EditorInterface.cpp index 5f94c4c..8f26878 100644 --- a/source/code/editor/EditorInterface.cpp +++ b/source/code/editor/EditorInterface.cpp @@ -1,31 +1,28 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2007 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - Raevehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ /* -TODO: The way we test for +TODO: The way we test for */ @@ -33,43 +30,43 @@ TODO: The way we test for EditorInterface::EditorInterface() { - boardActive = -1; - saved = true; - fileSaved = true; - bh.isNull = true; + boardActive = -1; + saved = true; + fileSaved = true; + bh.isNull = true; } void EditorInterface::getModel(int nr) { - tb = bh.getModel(nr); - saved = true; - boardActive = nr; + tb = bh.getModel(nr); + saved = true; + boardActive = nr; } bool EditorInterface::exists() { - if(bh.isNull) - return false; - else - return true; + if(bh.isNull) + return false; + else + return true; } void EditorInterface::selectColor(int color) { - colorSelected = color; + colorSelected = color; } int EditorInterface::getSelectedColor() { - return colorSelected; + return colorSelected; } void EditorInterface::drawOnModel(int x, int y) { - if(boardActive!=-1) + if(boardActive!=-1) { if(colorSelected<7) //Ordinary thing - tb.setBrick(x,y,colorSelected); + tb.setBrick(x,y,colorSelected); if(colorSelected==7) tb.moveUp(x,y); if(colorSelected==8) @@ -81,7 +78,7 @@ void EditorInterface::drawOnModel(int x, int y) void EditorInterface::moveLeft() { if(boardActive!=-1) - tb.moveLeft(); + tb.moveLeft(); saved = false; } @@ -91,7 +88,7 @@ void EditorInterface::moveRight() tb.moveRight(); saved = false; } - + void EditorInterface::deleteBoard() { if(boardActive!=-1) @@ -102,7 +99,7 @@ void EditorInterface::deleteBoard() fileSaved = false; } } - + void EditorInterface::moveBoardBack() { if(boardActive!=-1) @@ -111,7 +108,7 @@ void EditorInterface::moveBoardBack() boardActive--; } } - + void EditorInterface::moveBoardForward() { if(boardActive!=-1) @@ -120,7 +117,7 @@ void EditorInterface::moveBoardForward() boardActive++; } } - + void EditorInterface::saveBoard() { if(boardActive!=-1) @@ -130,19 +127,19 @@ void EditorInterface::saveBoard() fileSaved = false; } } - + bool EditorInterface::saveFile(string filename) { if((!bh.isNull)&&(filename!="")) { - fileName = filename; + fileName = filename; bh.saveBoards(filename); fileSaved = true; return true; } return false; } - + bool EditorInterface::saveFile() { if((!bh.isNull)&&(fileName!="")) @@ -153,7 +150,7 @@ bool EditorInterface::saveFile() } return false; } - + void EditorInterface::openFile(string filename) { fileName = filename; @@ -162,30 +159,30 @@ void EditorInterface::openFile(string filename) saved = true; fileSaved = true; } - + void EditorInterface::newFile() { fileName = ""; bh = BoardHolder(); TheBoard tb2; - tb.isNull = true; // = null; What here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + tb.isNull = true; // = null; What here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! boardActive = -1; saved = true; fileSaved = false; } - + int EditorInterface::getColor(int x, int y) { if(boardActive==-1) return -1; return tb.getBrick(x,y); } - + int EditorInterface::getActiveBoardNr() { return boardActive; } - + int EditorInterface::getNumberOfMoves() { if(!tb.isNull) @@ -194,7 +191,7 @@ int EditorInterface::getNumberOfMoves() } return 0; } - + bool EditorInterface::newBoard() { if(!bh.isNull) @@ -205,7 +202,7 @@ bool EditorInterface::newBoard() else return false; } - + int EditorInterface::getNumberOfBoards() { if(!bh.isNull) @@ -213,7 +210,7 @@ int EditorInterface::getNumberOfBoards() else return 0; } - + void EditorInterface::setNumberOfMoves(int moves) { if(!tb.isNull) @@ -222,12 +219,12 @@ void EditorInterface::setNumberOfMoves(int moves) tb.setNumberOfMoves(moves); } } - + bool EditorInterface::isSaved() { return saved; } - + bool EditorInterface::fileIsSaved() { return fileSaved; diff --git a/source/code/editor/EditorInterface.hpp b/source/code/editor/EditorInterface.hpp index df747de..39b4c5a 100644 --- a/source/code/editor/EditorInterface.hpp +++ b/source/code/editor/EditorInterface.hpp @@ -1,27 +1,24 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2007 Poul Sander +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - Rævehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include "BoardHolder.hpp" @@ -30,39 +27,39 @@ Copyright (C) 2007 Poul Sander #define EDITORINTERFACEDEFINED class EditorInterface { - private: - int colorSelected; //The color the user have selected - int boardActive; //Number of the active board, -1 if not active - TheBoard tb; //The active board - BoardHolder bh; //The Vector that holds the boards - bool saved; //The current board is saved - bool fileSaved; //The whole file is saved - string fileName; //The filename that is open, "" if no filename is given - - public: - EditorInterface(); - void getModel(int); - bool exists(); - void selectColor(int color); - int getSelectedColor(); - void drawOnModel(int x, int y); - void moveLeft(); - void moveRight(); - void deleteBoard(); - void moveBoardBack(); - void moveBoardForward(); - void saveBoard(); - bool saveFile(string); - bool saveFile(); - void openFile(string); - void newFile(); - int getColor(int x, int y); - int getActiveBoardNr(); - int getNumberOfMoves(); - bool newBoard(); - int getNumberOfBoards(); - void setNumberOfMoves(int); - bool isSaved(); - bool fileIsSaved(); +private: + int colorSelected; //The color the user have selected + int boardActive; //Number of the active board, -1 if not active + TheBoard tb; //The active board + BoardHolder bh; //The Vector that holds the boards + bool saved; //The current board is saved + bool fileSaved; //The whole file is saved + string fileName; //The filename that is open, "" if no filename is given + +public: + EditorInterface(); + void getModel(int); + bool exists(); + void selectColor(int color); + int getSelectedColor(); + void drawOnModel(int x, int y); + void moveLeft(); + void moveRight(); + void deleteBoard(); + void moveBoardBack(); + void moveBoardForward(); + void saveBoard(); + bool saveFile(string); + bool saveFile(); + void openFile(string); + void newFile(); + int getColor(int x, int y); + int getActiveBoardNr(); + int getNumberOfMoves(); + bool newBoard(); + int getNumberOfBoards(); + void setNumberOfMoves(int); + bool isSaved(); + bool fileIsSaved(); }; #endif diff --git a/source/code/editor/TheBoard.cpp b/source/code/editor/TheBoard.cpp index 05a8afd..4f349c6 100644 --- a/source/code/editor/TheBoard.cpp +++ b/source/code/editor/TheBoard.cpp @@ -1,141 +1,138 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2007 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - Rævehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include "TheBoard.hpp" TheBoard::TheBoard() { - numberOfMoves = 0; - for(int i = 0; i < BOARDWIDTH; i++) - for(int j = 0; j < BOARDHEIGHT;j++) - TheBoard::board[i][j] = -1; - isNull = false; + numberOfMoves = 0; + for(int i = 0; i < BOARDWIDTH; i++) + for(int j = 0; j < BOARDHEIGHT; j++) + TheBoard::board[i][j] = -1; + isNull = false; } TheBoard::TheBoard(const TheBoard &tb) { - TheBoard::numberOfMoves = tb.numberOfMoves; - for(int i = 0; i < BOARDWIDTH; i++) - for(int j = 0; j < BOARDHEIGHT;j++) - TheBoard::board[i][j] = tb.board[i][j]; - isNull = false; + TheBoard::numberOfMoves = tb.numberOfMoves; + for(int i = 0; i < BOARDWIDTH; i++) + for(int j = 0; j < BOARDHEIGHT; j++) + TheBoard::board[i][j] = tb.board[i][j]; + isNull = false; } void TheBoard::copyFrom(TheBoard *tb) { - TheBoard::numberOfMoves = tb->numberOfMoves; - for(int i = 0; i < BOARDWIDTH; i++) - for(int j = 0; j < BOARDHEIGHT;j++) - TheBoard::board[i][j] = tb->board[i][j]; + TheBoard::numberOfMoves = tb->numberOfMoves; + for(int i = 0; i < BOARDWIDTH; i++) + for(int j = 0; j < BOARDHEIGHT; j++) + TheBoard::board[i][j] = tb->board[i][j]; } bool TheBoard::setBrick(int x, int y, int color) { - if((x<0)||(x>=BOARDWIDTH)||(y<0)||(y>=12)) - return false; - board[x][y]=color; - return true; + if((x<0)||(x>=BOARDWIDTH)||(y<0)||(y>=12)) + return false; + board[x][y]=color; + return true; } int TheBoard::getBrick(int x, int y) { - if((x<0)||(x>=BOARDWIDTH)||(y<0)||(y>=BOARDHEIGHT)) - return -999; - return board[x][y]; + if((x<0)||(x>=BOARDWIDTH)||(y<0)||(y>=BOARDHEIGHT)) + return -999; + return board[x][y]; } void TheBoard::setNumberOfMoves(int moves) { - TheBoard::numberOfMoves = moves; + TheBoard::numberOfMoves = moves; } int TheBoard::getNumberOfMoves() { - return TheBoard::numberOfMoves; + return TheBoard::numberOfMoves; } bool TheBoard::moveUp(int x, int y) { - if((x<0)||(x>=BOARDWIDTH)||(y<0)||(y>=BOARDHEIGHT)) - return false; - for(int i=1; i<=y; i++) - { - board[x][i-1]=board[x][i]; - } - board[x][y]=-1; - return true; + if((x<0)||(x>=BOARDWIDTH)||(y<0)||(y>=BOARDHEIGHT)) + return false; + for(int i=1; i<=y; i++) + { + board[x][i-1]=board[x][i]; + } + board[x][y]=-1; + return true; } //moveUp bool TheBoard::moveDown(int x, int y) { - if((x<0)||(x>=BOARDWIDTH)||(y<0)||(y>=BOARDHEIGHT)) - return false; - for(int i=y-1; i>=0; i--) - { - board[x][i+1]=board[x][i]; - } - board[x][0]=-1; - return true; + if((x<0)||(x>=BOARDWIDTH)||(y<0)||(y>=BOARDHEIGHT)) + return false; + for(int i=y-1; i>=0; i--) + { + board[x][i+1]=board[x][i]; + } + board[x][0]=-1; + return true; } void TheBoard::moveRight() { - for(int i=0; i=0; j--) { - for(int j=BOARDWIDTH-2; j>=0; j--) - { - board[j+1][i]=board[j][i]; - } - board[0][i] = -1; + board[j+1][i]=board[j][i]; } + board[0][i] = -1; + } } //moveRight //moves all pieces one to the right void TheBoard::moveLeft() { - for(int i=0; i0) - ei.setNumberOfMoves(ei.getNumberOfMoves()-1); - } - } + +public: + moveDownButton() + { + aButton::aButton(240,100,bMoveDown); + } + + void click(int x,int y) + { + if(clicked(x,y)) + { + if(ei.getNumberOfMoves()>0) + ei.setNumberOfMoves(ei.getNumberOfMoves()-1); + } + } }; theEditor::theEditor() { - //This is the constructor - createFileButton cb; - buttons.push_back(cb); - deletePuzzleButton dpb; - buttons.push_back(dpb); + //This is the constructor + createFileButton cb; + buttons.push_back(cb); + deletePuzzleButton dpb; + buttons.push_back(dpb); } void theEditor::drawButtons() { - for(int i = 0;idraw(); - } + for(int i = 0; idraw(); + } } void aButton::click(int x, int y) { - cout << "Error: aButtons's click command was executed!" << endl; + cout << "Error: aButtons's click command was executed!" << endl; } void aButton::draw() { - DrawIMG(label,screen,x,y); + DrawIMG(label,screen,x,y); } void theEditor::click(int x, int y) { - for(int i = 0;iclick(x,y); - } -} - -int main() { - theEditor te; - te.drawButtons(); + for(int i = 0; iclick(x,y); + } +} + +int main() +{ + theEditor te; + te.drawButtons(); } \ No newline at end of file diff --git a/source/code/editor/editorMain.hpp b/source/code/editor/editorMain.hpp index 9f51540..0bdcfa3 100644 --- a/source/code/editor/editorMain.hpp +++ b/source/code/editor/editorMain.hpp @@ -1,29 +1,27 @@ /* -editorMain.hpp -Copyright (C) 2007 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - R�veh�jvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ -#include "SDL.h" +#include "SDL.h" #include "EditorInterface.hpp" #include @@ -50,35 +48,35 @@ extern EditorInterface ei; class aButton { - public: - int x,y,width,height; - SDL_Surface *label; - - aButton() - { - } - - aButton(int x,int y,SDL_Surface *ss) - { - this->x = x; - this->y = y; - this->label = ss; - width = this->label->w; - height = this->label->h; - } - - void draw(); - - //Function to check if the button is clicked. - bool clicked(int x, int y) - { - if((x>=this->x)&&(x<=this->x+width)&&(y>=this->y)&&(y<=this->y+height)) - return true; - else - return false; - } - - void click(int x, int y); +public: + int x,y,width,height; + SDL_Surface *label; + + aButton() + { + } + + aButton(int x,int y,SDL_Surface *ss) + { + this->x = x; + this->y = y; + this->label = ss; + width = this->label->w; + height = this->label->h; + } + + void draw(); + + //Function to check if the button is clicked. + bool clicked(int x, int y) + { + if((x>=this->x)&&(x<=this->x+width)&&(y>=this->y)&&(y<=this->y+height)) + return true; + else + return false; + } + + void click(int x, int y); }; const int numberOfButtons = 14; @@ -86,16 +84,16 @@ const int numberOfButtons = 14; //The editor itself... class theEditor { - private: - vector buttons; - - - public: - - theEditor(); - - virtual void drawButtons(); - - virtual void click(int x, int y); - +private: + vector buttons; + + +public: + + theEditor(); + + virtual void drawButtons(); + + virtual void click(int x, int y); + }; diff --git a/source/code/global.hpp b/source/code/global.hpp index f7bbd93..cbdd7db 100644 --- a/source/code/global.hpp +++ b/source/code/global.hpp @@ -1,9 +1,25 @@ -/* - * File: global.hpp - * Author: poul - * - * Created on 5. juni 2011, 18:26 - */ +/* +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== +*/ #ifndef _GLOBAL_HPP #define _GLOBAL_HPP diff --git a/source/code/highscore.cpp b/source/code/highscore.cpp index b7fda7d..152cc84 100644 --- a/source/code/highscore.cpp +++ b/source/code/highscore.cpp @@ -1,26 +1,24 @@ /* -highscore.cpp -Copyright (C) 2005 Poul Sander +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ - Poul Sander - R�veh�jvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include "highscore.h" @@ -30,20 +28,21 @@ Copyright (C) 2005 Poul Sander //Returns path to "my Documents" in windows: string getMyDocumentsPath1() { - TCHAR pszPath[MAX_PATH]; - //if (SUCCEEDED(SHGetSpecialFolderPath(NULL, pszPath, CSIDL_PERSONAL, FALSE))) { - if (SUCCEEDED(SHGetSpecialFolderPath(NULL, pszPath, CSIDL_PERSONAL, FALSE))) { - // pszPath is now the path that you want - cout << "MyDocuments Located: " << pszPath << endl; - string theResult= pszPath; - return theResult; - } - else - { - cout << "Warning: My Documents not found!" << endl; - string theResult =""; - return theResult; - } + TCHAR pszPath[MAX_PATH]; + //if (SUCCEEDED(SHGetSpecialFolderPath(NULL, pszPath, CSIDL_PERSONAL, FALSE))) { + if (SUCCEEDED(SHGetSpecialFolderPath(NULL, pszPath, CSIDL_PERSONAL, FALSE))) + { + // pszPath is now the path that you want + cout << "MyDocuments Located: " << pszPath << endl; + string theResult= pszPath; + return theResult; + } + else + { + cout << "Warning: My Documents not found!" << endl; + string theResult =""; + return theResult; + } } #endif @@ -51,122 +50,122 @@ string getMyDocumentsPath1() Highscore::Highscore(int type) { #if defined(__unix__) - string home = getenv("HOME"); - string filename1 = home+"/.gamesaves/blockattack/endless.dat"; - string filename2 = home+"/.gamesaves/blockattack/timetrial.dat"; + string home = getenv("HOME"); + string filename1 = home+"/.gamesaves/blockattack/endless.dat"; + string filename2 = home+"/.gamesaves/blockattack/timetrial.dat"; #elif defined(_WIN32) - string home = getMyDocumentsPath1(); - string filename1, filename2; - if (&home!=NULL) - { - filename1 = home+"/My Games/blockattack/endless.dat"; - filename2 = home+"/My Games/blockattack/timetrial.dat"; - } - else - { - filename1 = "endless.dat"; - filename2 = "timetrial.dat"; - } + string home = getMyDocumentsPath1(); + string filename1, filename2; + if (&home!=NULL) + { + filename1 = home+"/My Games/blockattack/endless.dat"; + filename2 = home+"/My Games/blockattack/timetrial.dat"; + } + else + { + filename1 = "endless.dat"; + filename2 = "timetrial.dat"; + } #else - string filename1 = "endless.dat"; - string filename2 = "timetrial.dat"; + string filename1 = "endless.dat"; + string filename2 = "timetrial.dat"; #endif - ourType = type; - if (type == 1) filename = filename1; - if (type == 2) filename = filename2; - ifstream scorefile(filename.c_str(), ios::binary); - if (scorefile) - { - for (int i = 0; i(&tabel[i].score), sizeof(int)); - } - } - else - { - for (int i = 0; i(&tabel[i].score), sizeof(int)); + } + } + else + { + for (int i = 0; i(&tabel[i].score),sizeof(int)); - } - outfile.close(); + if (ourType == 1) filename = filename1; + if (ourType == 2) filename = filename2; + + ofstream outfile; + outfile.open(Highscore::filename.c_str(), ios::binary |ios::trunc); + if (!outfile) + { + cout << "Error writing to file: " << filename << endl; + exit(1); + } + for (int i = 0; i(&tabel[i].score),sizeof(int)); + } + outfile.close(); } bool Highscore::isHighScore(int newScore) { - if (newScore>tabel[top-1].score) - return true; - else - return false; + if (newScore>tabel[top-1].score) + return true; + else + return false; } void Highscore::addScore(char newName[], int newScore) { - int ranking = top-1; - while ((tabel[ranking-1].scoreranking; i--) - { - tabel[i].score = tabel[i-1].score; - strcpy(tabel[i].name," \0"); - strcpy(tabel[i].name,tabel[i-1].name); - } - tabel[ranking].score = newScore; - strcpy(tabel[ranking].name," \0"); - strcpy(tabel[ranking].name,newName); - Highscore::writeFile(); + int ranking = top-1; + while ((tabel[ranking-1].scoreranking; i--) + { + tabel[i].score = tabel[i-1].score; + strcpy(tabel[i].name," \0"); + strcpy(tabel[i].name,tabel[i-1].name); + } + tabel[ranking].score = newScore; + strcpy(tabel[ranking].name," \0"); + strcpy(tabel[ranking].name,newName); + Highscore::writeFile(); } int Highscore::getScoreNumber(int room) { - return tabel[room].score; + return tabel[room].score; } char* Highscore::getScoreName(int room) { - return &tabel[room].name[0]; + return &tabel[room].name[0]; } diff --git a/source/code/highscore.h b/source/code/highscore.h index e25ce53..6580524 100644 --- a/source/code/highscore.h +++ b/source/code/highscore.h @@ -1,26 +1,24 @@ /* -highscore.h -Copyright (C) 2005 Poul Sander +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ - Poul Sander - R�veh�jvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include @@ -44,27 +42,27 @@ const int top = 10; struct record { - char name[30]; - int score; + char name[30]; + int score; }; class Highscore { private: - record tabel[top]; - string filename; - int ourType; //This is ugly, remove me, plz! - void writeFile(); + record tabel[top]; + string filename; + int ourType; //This is ugly, remove me, plz! + void writeFile(); public: - Highscore() - { - } + Highscore() + { + } - Highscore(int type); + Highscore(int type); - bool isHighScore(int); - void addScore(char[],int); - int getScoreNumber(int); - char* getScoreName(int); + bool isHighScore(int); + void addScore(char[],int); + int getScoreNumber(int); + char* getScoreName(int); }; diff --git a/source/code/joypad.cpp b/source/code/joypad.cpp index d6a2d45..f001394 100644 --- a/source/code/joypad.cpp +++ b/source/code/joypad.cpp @@ -1,177 +1,174 @@ /* -joypad.cpp - Enables joypad support -Copyright (C) 2005 Poul Sander +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ - Poul Sander - R�veh�jvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include "joypad.h" bool Joypad_init() { - if (0==SDL_InitSubSystem(SDL_INIT_JOYSTICK)) - return true; - else - return false; + if (0==SDL_InitSubSystem(SDL_INIT_JOYSTICK)) + return true; + else + return false; } Joypad_status Joypad_getStatus(SDL_Joystick *joystick) { - Joypad_status status; - for (int i=0; i=SDL_JoystickNumAxes(joystick)) - { - status.padDown[i]=false; - status.padUp[i] = false; - status.padLeft[i] = false; - status.padRight[i] = false; - } - else - { - //cout << SDL_JoystickGetAxis(joystick,i*2+1)<< endl; - if (SDL_JoystickGetAxis(joystick,i*2)<(-8000)) - status.padLeft[i]=1; - else - status.padLeft[i]=0; - if (SDL_JoystickGetAxis(joystick,i*2)>(8000)) - status.padRight[i]=1; - else - status.padRight[i]=0; - if (SDL_JoystickGetAxis(joystick,i*2+1)<(-8000)) - status.padUp[i]=1; - else - status.padUp[i]=0; - if (SDL_JoystickGetAxis(joystick,i*2+1)>(8000)) - status.padDown[i]=1; - else - status.padDown[i]=0; - } - }//NRofPADS - for (int i=0; i=SDL_JoystickNumButtons(joystick)) - status.button[i]=false; - else - if (1==SDL_JoystickGetButton(joystick,i)) - status.button[i] = true; - else - status.button[i] = false; - } - return status; + Joypad_status status; + for (int i=0; i=SDL_JoystickNumAxes(joystick)) + { + status.padDown[i]=false; + status.padUp[i] = false; + status.padLeft[i] = false; + status.padRight[i] = false; + } + else + { + //cout << SDL_JoystickGetAxis(joystick,i*2+1)<< endl; + if (SDL_JoystickGetAxis(joystick,i*2)<(-8000)) + status.padLeft[i]=1; + else + status.padLeft[i]=0; + if (SDL_JoystickGetAxis(joystick,i*2)>(8000)) + status.padRight[i]=1; + else + status.padRight[i]=0; + if (SDL_JoystickGetAxis(joystick,i*2+1)<(-8000)) + status.padUp[i]=1; + else + status.padUp[i]=0; + if (SDL_JoystickGetAxis(joystick,i*2+1)>(8000)) + status.padDown[i]=1; + else + status.padDown[i]=0; + } + }//NRofPADS + for (int i=0; i=SDL_JoystickNumButtons(joystick)) + status.button[i]=false; + else if (1==SDL_JoystickGetButton(joystick,i)) + status.button[i] = true; + else + status.button[i] = false; + } + return status; } Joypad::Joypad() { - up=false; - down=false; - left=false; - right=false; - but1=false; - but2=false; - upREL=true; - downREL=true; - leftREL=true; - rightREL=true; - but1REL=true; - but2REL=true; - int joynum = 0; - while ((SDL_JoystickOpened(joynum))&&(joynum=Joypad_number) - working = false; - else - { - joystick=SDL_JoystickOpen(joynum); - if (joystick==NULL) - working =false; - else - working=true; - } + up=false; + down=false; + left=false; + right=false; + but1=false; + but2=false; + upREL=true; + downREL=true; + leftREL=true; + rightREL=true; + but1REL=true; + but2REL=true; + int joynum = 0; + while ((SDL_JoystickOpened(joynum))&&(joynum=Joypad_number) + working = false; + else + { + joystick=SDL_JoystickOpen(joynum); + if (joystick==NULL) + working =false; + else + working=true; + } } Joypad::~Joypad() { if(working) - SDL_JoystickClose(joystick); + SDL_JoystickClose(joystick); } void Joypad::update() { - SDL_JoystickUpdate(); - Joypad_status status = Joypad_getStatus(joystick); - if ((upREL)&&((status.padUp[0])||(status.padUp[1])||(status.padUp[2])||(status.padUp[3]))) - { - up=true; - upREL=false; - } - else - up=false; - if ((downREL)&&((status.padDown[0])||(status.padDown[1])||(status.padDown[2])||(status.padDown[3]))) - { - down=true; - downREL=false; - } - else - down=false; - if ((leftREL)&&((status.padLeft[0])||(status.padLeft[1])||(status.padLeft[2])||(status.padLeft[3]))) - { - left=true; - leftREL=false; - } - else - left=false; - if ((rightREL)&&((status.padRight[0])||(status.padRight[1])||(status.padRight[2])||(status.padRight[3]))) - { - right=true; - rightREL=false; - } - else - right=false; - if ((but1REL)&&((status.button[0])||(status.button[2])||(status.button[4])||(status.button[6]))) - { - but1=true; - but1REL=false; - } - else - but1=false; - if ((but2REL)&&((status.button[1])||(status.button[3])||(status.button[5])||(status.button[7]))) - { - but2=true; - but2REL=false; - } - else - but2=false; - //Now testing for up - if (!((status.padUp[0])||(status.padUp[1])||(status.padUp[2])||(status.padUp[3]))) - upREL = true; - if (!((status.padDown[0])||(status.padDown[1])||(status.padDown[2])||(status.padDown[3]))) - downREL = true; - if (!((status.padLeft[0])||(status.padLeft[1])||(status.padLeft[2])||(status.padLeft[3]))) - leftREL = true; - if (!((status.padRight[0])||(status.padRight[1])||(status.padRight[2])||(status.padRight[3]))) - rightREL= true; - if (!((status.button[0])||(status.button[2])||(status.button[4])||(status.button[6]))) - but1REL = true; - if (!((status.button[1])||(status.button[3])||(status.button[5])||(status.button[7]))) - but2REL = true; + SDL_JoystickUpdate(); + Joypad_status status = Joypad_getStatus(joystick); + if ((upREL)&&((status.padUp[0])||(status.padUp[1])||(status.padUp[2])||(status.padUp[3]))) + { + up=true; + upREL=false; + } + else + up=false; + if ((downREL)&&((status.padDown[0])||(status.padDown[1])||(status.padDown[2])||(status.padDown[3]))) + { + down=true; + downREL=false; + } + else + down=false; + if ((leftREL)&&((status.padLeft[0])||(status.padLeft[1])||(status.padLeft[2])||(status.padLeft[3]))) + { + left=true; + leftREL=false; + } + else + left=false; + if ((rightREL)&&((status.padRight[0])||(status.padRight[1])||(status.padRight[2])||(status.padRight[3]))) + { + right=true; + rightREL=false; + } + else + right=false; + if ((but1REL)&&((status.button[0])||(status.button[2])||(status.button[4])||(status.button[6]))) + { + but1=true; + but1REL=false; + } + else + but1=false; + if ((but2REL)&&((status.button[1])||(status.button[3])||(status.button[5])||(status.button[7]))) + { + but2=true; + but2REL=false; + } + else + but2=false; + //Now testing for up + if (!((status.padUp[0])||(status.padUp[1])||(status.padUp[2])||(status.padUp[3]))) + upREL = true; + if (!((status.padDown[0])||(status.padDown[1])||(status.padDown[2])||(status.padDown[3]))) + downREL = true; + if (!((status.padLeft[0])||(status.padLeft[1])||(status.padLeft[2])||(status.padLeft[3]))) + leftREL = true; + if (!((status.padRight[0])||(status.padRight[1])||(status.padRight[2])||(status.padRight[3]))) + rightREL= true; + if (!((status.button[0])||(status.button[2])||(status.button[4])||(status.button[6]))) + but1REL = true; + if (!((status.button[1])||(status.button[3])||(status.button[5])||(status.button[7]))) + but2REL = true; } diff --git a/source/code/joypad.h b/source/code/joypad.h index e0bba66..b8dff90 100644 --- a/source/code/joypad.h +++ b/source/code/joypad.h @@ -1,26 +1,24 @@ /* -joypad.h - Enables joypad support -Copyright (C) 2005 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - Rævehøjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ //headerfile joypad.h @@ -34,12 +32,13 @@ Copyright (C) 2005 Poul Sander using namespace std; -struct Joypad_status{ - bool padLeft[NRofPADS]; - bool padRight[NRofPADS]; - bool padUp[NRofPADS]; - bool padDown[NRofPADS]; - bool button[NRofBUTTONS]; +struct Joypad_status +{ + bool padLeft[NRofPADS]; + bool padRight[NRofPADS]; + bool padUp[NRofPADS]; + bool padDown[NRofPADS]; + bool button[NRofBUTTONS]; }; //Contains the init code @@ -54,17 +53,18 @@ bool Joypad_init(); //Returns the status of the joypad Joypad_status Joypad_getStatus(SDL_Joystick); -class Joypad{ +class Joypad +{ private: - SDL_Joystick *joystick; - static int Joy_count; + SDL_Joystick *joystick; + static int Joy_count; public: - bool up,down,left,right,but1,but2; - bool upREL,downREL,leftREL,rightREL,but1REL,but2REL; - bool working; + bool up,down,left,right,but1,but2; + bool upREL,downREL,leftREL,rightREL,but1REL,but2REL; + bool working; - Joypad(); - ~Joypad(); + Joypad(); + ~Joypad(); - void update(); + void update(); }; diff --git a/source/code/listFiles.cpp b/source/code/listFiles.cpp index 72f35c9..0471103 100644 --- a/source/code/listFiles.cpp +++ b/source/code/listFiles.cpp @@ -1,26 +1,24 @@ /* -listFiles.cpp -Copyright (C) 2005 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - R�veh�jvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ /* @@ -42,140 +40,140 @@ ListFiles::~ListFiles() void ListFiles::setDirectory(string directory) { - for (int i=0;id_name; - if (!isInList(name) && name[0]!='.' ) - { - nrOfFiles++; - filenames[nrOfFiles] = name; - } - } - closedir(DirectoryPointer); + DIR *DirectoryPointer; + struct dirent *dp; + nrOfFiles=0; + //cout << "Will look in: " << directory << endl; + DirectoryPointer = opendir(directory.c_str()); + if(!DirectoryPointer) + return; + while ((dp=readdir(DirectoryPointer))&&(nrOfFilesd_name; + if (!isInList(name) && name[0]!='.' ) + { + nrOfFiles++; + filenames[nrOfFiles] = name; + } + } + closedir(DirectoryPointer); #endif - startFileNr=FIRST_FILE; - //Put code here + startFileNr=FIRST_FILE; + //Put code here } bool ListFiles::isInList(string name) { - for (int i=0;(i<=nrOfFiles);i++) - { - if (0==strcmp(name.c_str(),filenames[i].c_str())) - { - return true; - } - } - return false; + for (int i=0; (i<=nrOfFiles); i++) + { + if (0==strcmp(name.c_str(),filenames[i].c_str())) + { + return true; + } + } + return false; } void ListFiles::setDirectory2(string dic) { #if defined(__unix__) - DIR *DirectoryPointer; - struct dirent *dp; - //cout << "Will look in: " << dic << endl; - DirectoryPointer = opendir(dic.c_str()); - if(!DirectoryPointer) - return; - while ((dp=readdir(DirectoryPointer))&&(nrOfFilesd_name; - if (!isInList(name) && name != "." && name != "..") - { - nrOfFiles++; - filenames[nrOfFiles] = name; - } - } - closedir(DirectoryPointer); - - startFileNr=FIRST_FILE; + DIR *DirectoryPointer; + struct dirent *dp; + //cout << "Will look in: " << dic << endl; + DirectoryPointer = opendir(dic.c_str()); + if(!DirectoryPointer) + return; + while ((dp=readdir(DirectoryPointer))&&(nrOfFilesd_name; + if (!isInList(name) && name != "." && name != "..") + { + nrOfFiles++; + filenames[nrOfFiles] = name; + } + } + closedir(DirectoryPointer); + + startFileNr=FIRST_FILE; #endif } string ListFiles::getFileName(int nr) { - if (startFileNr+nrFIRST_FILE) - startFileNr = startFileNr-10; - if (startFileNrFIRST_FILE) + startFileNr = startFileNr-10; + if (startFileNrgetString("themename"))!=0) - { - //If this is a theme different from the saved one. Remember it! - Config::getInstance()->setString("themename",themeName); - } - if(themeName.compare("default")==0 || (themeName.compare("start")==0)) - { - InitImages(); - loaded =true; - return; //Nothing more to do - } - oldThemePath = "themes/"+themeName; - PHYSFS_addToSearchPath(oldThemePath.c_str(),0); - #if defined(__unix__) || defined(_WIN32) - PHYSFS_addToSearchPath((home+(string)"/"+oldThemePath).c_str(), 0); - #endif - InitImages(); - loaded = true; + //Remove old theme + PHYSFS_removeFromSearchPath(oldThemePath.c_str()); + //Look in blockattack.data + PHYSFS_addToSearchPath(((string)SHAREDIR+"/blockattack.data").c_str(), 1); + //Look in folder + PHYSFS_addToSearchPath(SHAREDIR, 1); + //Look in home folder +#if defined(__unix__) || defined(_WIN32) + PHYSFS_addToSearchPath(home.c_str(), 1); +#endif + if(themeName.compare(Config::getInstance()->getString("themename"))!=0) + { + //If this is a theme different from the saved one. Remember it! + Config::getInstance()->setString("themename",themeName); + } + if(themeName.compare("default")==0 || (themeName.compare("start")==0)) + { + InitImages(); + loaded =true; + return; //Nothing more to do + } + oldThemePath = "themes/"+themeName; + PHYSFS_addToSearchPath(oldThemePath.c_str(),0); +#if defined(__unix__) || defined(_WIN32) + PHYSFS_addToSearchPath((home+(string)"/"+oldThemePath).c_str(), 0); +#endif + InitImages(); + loaded = true; } -long NFont_OpenFont(NFont *target, string path,int ptsize, SDL_Color color, int style=TTF_STYLE_NORMAL) { - if (!PHYSFS_exists(path.c_str())) - { - cout << "File not in blockattack.data: " << path << endl; - return -1; //file doesn't exist - } +long NFont_OpenFont(NFont *target, string path,int ptsize, SDL_Color color, int style=TTF_STYLE_NORMAL) +{ + if (!PHYSFS_exists(path.c_str())) + { + cout << "File not in blockattack.data: " << path << endl; + return -1; //file doesn't exist + } - if(!(TTF_WasInit())) - TTF_Init(); + if(!(TTF_WasInit())) + TTF_Init(); - PHYSFS_file* myfile = PHYSFS_openRead(path.c_str()); + PHYSFS_file* myfile = PHYSFS_openRead(path.c_str()); - // Get the lenght of the file - unsigned int m_size = PHYSFS_fileLength(myfile); + // Get the lenght of the file + unsigned int m_size = PHYSFS_fileLength(myfile); - // Get the file data. - char *m_data = new char[m_size]; - int length_read = PHYSFS_read (myfile, m_data, 1, m_size); + // Get the file data. + char *m_data = new char[m_size]; + int length_read = PHYSFS_read (myfile, m_data, 1, m_size); - if (length_read != (int)m_size) - { - delete [] m_data; - m_data = 0; - PHYSFS_close(myfile); - cout << "Error. Curropt data file!" << endl; - return -3; - } + if (length_read != (int)m_size) + { + delete [] m_data; + m_data = 0; + PHYSFS_close(myfile); + cout << "Error. Curropt data file!" << endl; + return -3; + } - PHYSFS_close(myfile); + PHYSFS_close(myfile); // And this is how you load from a memory buffer with SDL - SDL_RWops *rw = SDL_RWFromMem (m_data, m_size); + SDL_RWops *rw = SDL_RWFromMem (m_data, m_size); - //The above might fail an return null. - if(!rw) - { - delete [] m_data; - m_data = 0; - PHYSFS_close(myfile); - cout << "Error. Curropt data file!" << endl; - return -2; - } + //The above might fail an return null. + if(!rw) + { + delete [] m_data; + m_data = 0; + PHYSFS_close(myfile); + cout << "Error. Curropt data file!" << endl; + return -2; + } - TTF_Font *font; - font=TTF_OpenFontRW(rw, 1, ptsize); - TTF_SetFontStyle(font,style); + TTF_Font *font; + font=TTF_OpenFontRW(rw, 1, ptsize); + TTF_SetFontStyle(font,style); - target->load(font,color); + target->load(font,color); - TTF_CloseFont(font); //Once loaded we don't care anymore! + TTF_CloseFont(font); //Once loaded we don't care anymore! - return 0; + return 0; } Mix_Music * Mix_LoadMUS2(string path) { - if (!PHYSFS_exists(path.c_str())) - { - cout << "File not in blockattack.data: " << path << endl; - return NULL; //file doesn't exist - } + if (!PHYSFS_exists(path.c_str())) + { + cout << "File not in blockattack.data: " << path << endl; + return NULL; //file doesn't exist + } - PHYSFS_file* myfile = PHYSFS_openRead(path.c_str()); + PHYSFS_file* myfile = PHYSFS_openRead(path.c_str()); - // Get the lenght of the file - unsigned int m_size = PHYSFS_fileLength(myfile); + // Get the lenght of the file + unsigned int m_size = PHYSFS_fileLength(myfile); - // Get the file data. - char *m_data = new char[m_size]; + // Get the file data. + char *m_data = new char[m_size]; - int length_read = PHYSFS_read (myfile, m_data, 1, m_size); + int length_read = PHYSFS_read (myfile, m_data, 1, m_size); - if (length_read != (int)m_size) - { - delete [] m_data; - m_data = 0; - PHYSFS_close(myfile); - cout << "Error. Curropt data file!" << endl; - return NULL; - } + if (length_read != (int)m_size) + { + delete [] m_data; + m_data = 0; + PHYSFS_close(myfile); + cout << "Error. Curropt data file!" << endl; + return NULL; + } - PHYSFS_close(myfile); + PHYSFS_close(myfile); // And this is how you load from a memory buffer with SDL - SDL_RWops *rw = SDL_RWFromMem (m_data, m_size); + SDL_RWops *rw = SDL_RWFromMem (m_data, m_size); - //The above might fail an return null. - if(!rw) - { - delete [] m_data; - m_data = 0; - PHYSFS_close(myfile); - cout << "Error. Curropt data file!" << endl; - return NULL; - } + //The above might fail an return null. + if(!rw) + { + delete [] m_data; + m_data = 0; + PHYSFS_close(myfile); + cout << "Error. Curropt data file!" << endl; + return NULL; + } - Mix_Music* ret = Mix_LoadMUS_RW(rw); + Mix_Music* ret = Mix_LoadMUS_RW(rw); - return ret; + return ret; } Mix_Chunk * Mix_LoadWAV2(char* path) { - if (!PHYSFS_exists(path)) - { - cout << "File not in blockattack.data: " << path << endl; - return NULL; //file doesn't exist - } + if (!PHYSFS_exists(path)) + { + cout << "File not in blockattack.data: " << path << endl; + return NULL; //file doesn't exist + } - PHYSFS_file* myfile = PHYSFS_openRead(path); + PHYSFS_file* myfile = PHYSFS_openRead(path); - // Get the lenght of the file - unsigned int m_size = PHYSFS_fileLength(myfile); + // Get the lenght of the file + unsigned int m_size = PHYSFS_fileLength(myfile); - // Get the file data. - char *m_data = new char[m_size]; + // Get the file data. + char *m_data = new char[m_size]; - int length_read = PHYSFS_read (myfile, m_data, 1, m_size); + int length_read = PHYSFS_read (myfile, m_data, 1, m_size); - if (length_read != (int)m_size) - { - delete [] m_data; - m_data = 0; - PHYSFS_close(myfile); - cout << "Error. Curropt data file!" << endl; - return NULL; - } + if (length_read != (int)m_size) + { + delete [] m_data; + m_data = 0; + PHYSFS_close(myfile); + cout << "Error. Curropt data file!" << endl; + return NULL; + } - PHYSFS_close(myfile); + PHYSFS_close(myfile); // And this is how you load from a memory buffer with SDL - SDL_RWops *rw = SDL_RWFromMem (m_data, m_size); + SDL_RWops *rw = SDL_RWFromMem (m_data, m_size); - //The above might fail an return null. - if(!rw) - { - delete [] m_data; - m_data = 0; - PHYSFS_close(myfile); - cout << "Error. Curropt data file!" << endl; - return NULL; - } + //The above might fail an return null. + if(!rw) + { + delete [] m_data; + m_data = 0; + PHYSFS_close(myfile); + cout << "Error. Curropt data file!" << endl; + return NULL; + } - Mix_Chunk* ret = Mix_LoadWAV_RW(rw,true); //the second argument tells the function to three RWops + Mix_Chunk* ret = Mix_LoadWAV_RW(rw,true); //the second argument tells the function to three RWops - return ret; + return ret; } //Load all image files to memory static int InitImages() { - if (!((backgroundImage = IMG_Load2("gfx/background.png")) - && (background = IMG_Load2("gfx/blackBackGround.png")) + if (!((backgroundImage = IMG_Load2("gfx/background.png")) + && (background = IMG_Load2("gfx/blackBackGround.png")) // && (b1player = IMG_Load2("gfx/bOnePlayer.png")) // && (b2players = IMG_Load2("gfx/bTwoPlayers.png")) // && (bVsMode = IMG_Load2("gfx/bVsGame.png")) @@ -412,134 +416,137 @@ static int InitImages() // && (bPuzzle = IMG_Load2((char*)"gfx/bPuzzle.png")) // && (bStageClear = IMG_Load2((char*)"gfx/bStageClear.png")) // && (bTimeTrial = IMG_Load2((char*)"gfx/bTimeTrial.png")) - //&& (bEndless = IMG_Load2((char*)"gfx/bEndless.png")) - && (bOptions = IMG_Load2((char*)"gfx/bOptions.png")) - && (bConfigure = IMG_Load2((char*)"gfx/bConfigure.png")) - && (bSelectPuzzle = IMG_Load2((char*)"gfx/bSelectPuzzle.png")) - && (bHighScore = IMG_Load2((char*)"gfx/bHighScore.png")) + //&& (bEndless = IMG_Load2((char*)"gfx/bEndless.png")) + && (bOptions = IMG_Load2((char*)"gfx/bOptions.png")) + && (bConfigure = IMG_Load2((char*)"gfx/bConfigure.png")) + && (bSelectPuzzle = IMG_Load2((char*)"gfx/bSelectPuzzle.png")) + && (bHighScore = IMG_Load2((char*)"gfx/bHighScore.png")) // && (bExit = IMG_Load2((char*)"gfx/bExit.png")) - && (bBack = IMG_Load2((char*)"gfx/bBack.png")) - && (bForward = IMG_Load2((char*)"gfx/bForward.png")) + && (bBack = IMG_Load2((char*)"gfx/bBack.png")) + && (bForward = IMG_Load2((char*)"gfx/bForward.png")) // && (bReplay = IMG_Load2((char*)"gfx/bReplays.png")) // && (bSave = IMG_Load2((char*)"gfx/bSave.png")) // && (bLoad = IMG_Load2((char*)"gfx/bLoad.png")) -/*#if NETWORK - && (bNetwork = IMG_Load2((char*)"gfx/bNetwork.png")) - && (bHost = IMG_Load2((char*)"gfx/bHost.png")) - && (bConnect = IMG_Load2((char*)"gfx/bConnect.png")) -#endif*/ - && (blackLine = IMG_Load2((char*)"gfx/blackLine.png")) - && (stageBobble = IMG_Load2((char*)"gfx/iStageClearLimit.png")) - && (bricks[0] = IMG_Load2((char*)"gfx/bricks/blue.png")) - && (bricks[1] = IMG_Load2((char*)"gfx/bricks/green.png")) - && (bricks[2] = IMG_Load2((char*)"gfx/bricks/purple.png")) - && (bricks[3] = IMG_Load2((char*)"gfx/bricks/red.png")) - && (bricks[4] = IMG_Load2((char*)"gfx/bricks/turkish.png")) - && (bricks[5] = IMG_Load2((char*)"gfx/bricks/yellow.png")) - && (bricks[6] = IMG_Load2((char*)"gfx/bricks/grey.png")) - && (crossover = IMG_Load2((char*)"gfx/crossover.png")) - && (balls[0] = IMG_Load2((char*)"gfx/balls/ballBlue.png")) - && (balls[1] = IMG_Load2((char*)"gfx/balls/ballGreen.png")) - && (balls[2] = IMG_Load2((char*)"gfx/balls/ballPurple.png")) - && (balls[3] = IMG_Load2((char*)"gfx/balls/ballRed.png")) - && (balls[4] = IMG_Load2((char*)"gfx/balls/ballTurkish.png")) - && (balls[5] = IMG_Load2((char*)"gfx/balls/ballYellow.png")) - && (balls[6] = IMG_Load2((char*)"gfx/balls/ballGray.png")) - && (cursor[0] = IMG_Load2((char*)"gfx/animations/cursor/1.png")) - && (cursor[1] = IMG_Load2((char*)"gfx/animations/cursor/2.png")) - && (bomb[0] = IMG_Load2((char*)"gfx/animations/bomb/bomb_1.png")) - && (bomb[1] = IMG_Load2((char*)"gfx/animations/bomb/bomb_2.png")) - && (ready[0] = IMG_Load2((char*)"gfx/animations/ready/ready_1.png")) - && (ready[1] = IMG_Load2((char*)"gfx/animations/ready/ready_2.png")) - && (explosion[0] = IMG_Load2((char*)"gfx/animations/explosion/0.png")) - && (explosion[1] = IMG_Load2((char*)"gfx/animations/explosion/1.png")) - && (explosion[2] = IMG_Load2((char*)"gfx/animations/explosion/2.png")) - && (explosion[3] = IMG_Load2((char*)"gfx/animations/explosion/3.png")) - && (counter[0] = IMG_Load2((char*)"gfx/counter/1.png")) - && (counter[1] = IMG_Load2((char*)"gfx/counter/2.png")) - && (counter[2] = IMG_Load2((char*)"gfx/counter/3.png")) - && (backBoard = IMG_Load2((char*)"gfx/BackBoard.png")) //not used, we just test if it exists :) - && (iGameOver = IMG_Load2((char*)"gfx/iGameOver.png")) - && (iWinner = IMG_Load2((char*)"gfx/iWinner.png")) - && (iDraw = IMG_Load2((char*)"gfx/iDraw.png")) - && (iLoser = IMG_Load2((char*)"gfx/iLoser.png")) - && (iChainBack = IMG_Load2((char*)"gfx/chainFrame.png")) + /*#if NETWORK + && (bNetwork = IMG_Load2((char*)"gfx/bNetwork.png")) + && (bHost = IMG_Load2((char*)"gfx/bHost.png")) + && (bConnect = IMG_Load2((char*)"gfx/bConnect.png")) + #endif*/ + && (blackLine = IMG_Load2((char*)"gfx/blackLine.png")) + && (stageBobble = IMG_Load2((char*)"gfx/iStageClearLimit.png")) + && (bricks[0] = IMG_Load2((char*)"gfx/bricks/blue.png")) + && (bricks[1] = IMG_Load2((char*)"gfx/bricks/green.png")) + && (bricks[2] = IMG_Load2((char*)"gfx/bricks/purple.png")) + && (bricks[3] = IMG_Load2((char*)"gfx/bricks/red.png")) + && (bricks[4] = IMG_Load2((char*)"gfx/bricks/turkish.png")) + && (bricks[5] = IMG_Load2((char*)"gfx/bricks/yellow.png")) + && (bricks[6] = IMG_Load2((char*)"gfx/bricks/grey.png")) + && (crossover = IMG_Load2((char*)"gfx/crossover.png")) + && (balls[0] = IMG_Load2((char*)"gfx/balls/ballBlue.png")) + && (balls[1] = IMG_Load2((char*)"gfx/balls/ballGreen.png")) + && (balls[2] = IMG_Load2((char*)"gfx/balls/ballPurple.png")) + && (balls[3] = IMG_Load2((char*)"gfx/balls/ballRed.png")) + && (balls[4] = IMG_Load2((char*)"gfx/balls/ballTurkish.png")) + && (balls[5] = IMG_Load2((char*)"gfx/balls/ballYellow.png")) + && (balls[6] = IMG_Load2((char*)"gfx/balls/ballGray.png")) + && (cursor[0] = IMG_Load2((char*)"gfx/animations/cursor/1.png")) + && (cursor[1] = IMG_Load2((char*)"gfx/animations/cursor/2.png")) + && (bomb[0] = IMG_Load2((char*)"gfx/animations/bomb/bomb_1.png")) + && (bomb[1] = IMG_Load2((char*)"gfx/animations/bomb/bomb_2.png")) + && (ready[0] = IMG_Load2((char*)"gfx/animations/ready/ready_1.png")) + && (ready[1] = IMG_Load2((char*)"gfx/animations/ready/ready_2.png")) + && (explosion[0] = IMG_Load2((char*)"gfx/animations/explosion/0.png")) + && (explosion[1] = IMG_Load2((char*)"gfx/animations/explosion/1.png")) + && (explosion[2] = IMG_Load2((char*)"gfx/animations/explosion/2.png")) + && (explosion[3] = IMG_Load2((char*)"gfx/animations/explosion/3.png")) + && (counter[0] = IMG_Load2((char*)"gfx/counter/1.png")) + && (counter[1] = IMG_Load2((char*)"gfx/counter/2.png")) + && (counter[2] = IMG_Load2((char*)"gfx/counter/3.png")) + && (backBoard = IMG_Load2((char*)"gfx/BackBoard.png")) //not used, we just test if it exists :) + && (iGameOver = IMG_Load2((char*)"gfx/iGameOver.png")) + && (iWinner = IMG_Load2((char*)"gfx/iWinner.png")) + && (iDraw = IMG_Load2((char*)"gfx/iDraw.png")) + && (iLoser = IMG_Load2((char*)"gfx/iLoser.png")) + && (iChainBack = IMG_Load2((char*)"gfx/chainFrame.png")) // && (optionsBack = IMG_Load2((char*)"gfx/options.png")) - && (bOn = IMG_Load2((char*)"gfx/bOn.png")) - && (bOff = IMG_Load2((char*)"gfx/bOff.png")) + && (bOn = IMG_Load2((char*)"gfx/bOn.png")) + && (bOff = IMG_Load2((char*)"gfx/bOff.png")) // && (bChange = IMG_Load2((char*)"gfx/bChange.png")) - && (b1024 = IMG_Load2((char*)"gfx/b1024.png")) - && (dialogBox = IMG_Load2((char*)"gfx/dialogbox.png")) + && (b1024 = IMG_Load2((char*)"gfx/b1024.png")) + && (dialogBox = IMG_Load2((char*)"gfx/dialogbox.png")) // && (fileDialogBox = IMG_Load2("gfx/fileDialogbox.png")) - && (iLevelCheck = IMG_Load2((char*)"gfx/iLevelCheck.png")) - && (iLevelCheckBox = IMG_Load2((char*)"gfx/iLevelCheckBox.png")) - && (iLevelCheckBoxMarked = IMG_Load2((char*)"gfx/iLevelCheckBoxMarked.png")) - && (iCheckBoxArea = IMG_Load2((char*)"gfx/iCheckBoxArea.png")) - && (boardBackBack = IMG_Load2((char*)"gfx/boardBackBack.png")) - && (changeButtonsBack = IMG_Load2((char*)"gfx/changeButtonsBack.png")) - && (garbageTL = IMG_Load2((char*)"gfx/garbage/garbageTL.png")) - && (garbageT = IMG_Load2((char*)"gfx/garbage/garbageT.png")) - && (garbageTR = IMG_Load2((char*)"gfx/garbage/garbageTR.png")) - && (garbageR = IMG_Load2((char*)"gfx/garbage/garbageR.png")) - && (garbageBR = IMG_Load2((char*)"gfx/garbage/garbageBR.png")) - && (garbageB = IMG_Load2((char*)"gfx/garbage/garbageB.png")) - && (garbageBL = IMG_Load2((char*)"gfx/garbage/garbageBL.png")) - && (garbageL = IMG_Load2((char*)"gfx/garbage/garbageL.png")) - && (garbageFill = IMG_Load2((char*)"gfx/garbage/garbageFill.png")) - && (garbageML = IMG_Load2((char*)"gfx/garbage/garbageML.png")) - && (garbageM = IMG_Load2((char*)"gfx/garbage/garbageM.png")) - && (garbageMR = IMG_Load2((char*)"gfx/garbage/garbageMR.png")) - && (garbageGM = IMG_Load2((char*)"gfx/garbage/garbageGM.png")) - && (garbageGML = IMG_Load2((char*)"gfx/garbage/garbageGML.png")) - && (garbageGMR = IMG_Load2((char*)"gfx/garbage/garbageGMR.png")) - && (smiley[0] = IMG_Load2((char*)"gfx/smileys/0.png")) - && (smiley[1] = IMG_Load2((char*)"gfx/smileys/1.png")) - && (smiley[2] = IMG_Load2((char*)"gfx/smileys/2.png")) - && (smiley[3] = IMG_Load2((char*)"gfx/smileys/3.png")) - //new in 1.3.2 - && (transCover = IMG_Load2((char*)"gfx/transCover.png")) - #if LEVELEDITOR - && (bCreateFile = IMG_Load2((char*)"gfx/editor/bCreateFile.png")) - && (bDeletePuzzle = IMG_Load2((char*)"gfx/editor/bDeletePuzzle.png")) - && (bLoadFile = IMG_Load2((char*)"gfx/editor/bLoadFile.png")) - && (bMoveBack = IMG_Load2((char*)"gfx/editor/bMoveBack.png")) - && (bMoveDown = IMG_Load2((char*)"gfx/editor/bMoveDown.png")) - && (bMoveForward = IMG_Load2((char*)"gfx/editor/bMoveForward.png")) - && (bMoveLeft = IMG_Load2((char*)"gfx/editor/bMoveLeft.png")) - && (bMoveRight = IMG_Load2((char*)"gfx/editor/bMoveRight.png")) - && (bMoveUp = IMG_Load2((char*)"gfx/editor/bMoveUp.png")) - && (bNewPuzzle = IMG_Load2((char*)"gfx/editor/bNewPuzzle.png")) - && (bSaveFileAs = IMG_Load2((char*)"gfx/editor/bSaveFileAs.png")) - && (bSavePuzzle = IMG_Load2((char*)"gfx/editor/bSavePuzzle.png")) - && (bSaveToFile = IMG_Load2((char*)"gfx/editor/bSaveToFile.png")) - && (bTestPuzzle = IMG_Load2((char*)"gfx/editor/bTestPuzzle.png")) - #endif - //end new in 1.3.2 - //new in 1.4.0 - && (bTheme = IMG_Load2((char*)"gfx/bTheme.png")) - && (bSkip = IMG_Load2((char*)"gfx/bSkip.png")) - && (bNext = IMG_Load2((char*)"gfx/bNext.png")) - && (bRetry = IMG_Load2((char*)"gfx/bRetry.png")) - )) - //if there was a problem ie. "File not found" - { - cout << "Error loading image file: " << SDL_GetError() << endl; - exit(1); - } - try{ - bNewGame = IMG_Load3("gfx/bNewGame.png"); - mouse = IMG_Load3("gfx/mouse.png"); - menuMarked = IMG_Load3("gfx/menu/marked.png"); - menuUnmarked = IMG_Load3("gfx/menu/unmarked.png"); - } catch (exception e) { - cout << e.what() << endl; - exit(1); - } - - - //Prepare for fast blittering! - CONVERT(background); - CONVERT(backgroundImage); + && (iLevelCheck = IMG_Load2((char*)"gfx/iLevelCheck.png")) + && (iLevelCheckBox = IMG_Load2((char*)"gfx/iLevelCheckBox.png")) + && (iLevelCheckBoxMarked = IMG_Load2((char*)"gfx/iLevelCheckBoxMarked.png")) + && (iCheckBoxArea = IMG_Load2((char*)"gfx/iCheckBoxArea.png")) + && (boardBackBack = IMG_Load2((char*)"gfx/boardBackBack.png")) + && (changeButtonsBack = IMG_Load2((char*)"gfx/changeButtonsBack.png")) + && (garbageTL = IMG_Load2((char*)"gfx/garbage/garbageTL.png")) + && (garbageT = IMG_Load2((char*)"gfx/garbage/garbageT.png")) + && (garbageTR = IMG_Load2((char*)"gfx/garbage/garbageTR.png")) + && (garbageR = IMG_Load2((char*)"gfx/garbage/garbageR.png")) + && (garbageBR = IMG_Load2((char*)"gfx/garbage/garbageBR.png")) + && (garbageB = IMG_Load2((char*)"gfx/garbage/garbageB.png")) + && (garbageBL = IMG_Load2((char*)"gfx/garbage/garbageBL.png")) + && (garbageL = IMG_Load2((char*)"gfx/garbage/garbageL.png")) + && (garbageFill = IMG_Load2((char*)"gfx/garbage/garbageFill.png")) + && (garbageML = IMG_Load2((char*)"gfx/garbage/garbageML.png")) + && (garbageM = IMG_Load2((char*)"gfx/garbage/garbageM.png")) + && (garbageMR = IMG_Load2((char*)"gfx/garbage/garbageMR.png")) + && (garbageGM = IMG_Load2((char*)"gfx/garbage/garbageGM.png")) + && (garbageGML = IMG_Load2((char*)"gfx/garbage/garbageGML.png")) + && (garbageGMR = IMG_Load2((char*)"gfx/garbage/garbageGMR.png")) + && (smiley[0] = IMG_Load2((char*)"gfx/smileys/0.png")) + && (smiley[1] = IMG_Load2((char*)"gfx/smileys/1.png")) + && (smiley[2] = IMG_Load2((char*)"gfx/smileys/2.png")) + && (smiley[3] = IMG_Load2((char*)"gfx/smileys/3.png")) + //new in 1.3.2 + && (transCover = IMG_Load2((char*)"gfx/transCover.png")) +#if LEVELEDITOR + && (bCreateFile = IMG_Load2((char*)"gfx/editor/bCreateFile.png")) + && (bDeletePuzzle = IMG_Load2((char*)"gfx/editor/bDeletePuzzle.png")) + && (bLoadFile = IMG_Load2((char*)"gfx/editor/bLoadFile.png")) + && (bMoveBack = IMG_Load2((char*)"gfx/editor/bMoveBack.png")) + && (bMoveDown = IMG_Load2((char*)"gfx/editor/bMoveDown.png")) + && (bMoveForward = IMG_Load2((char*)"gfx/editor/bMoveForward.png")) + && (bMoveLeft = IMG_Load2((char*)"gfx/editor/bMoveLeft.png")) + && (bMoveRight = IMG_Load2((char*)"gfx/editor/bMoveRight.png")) + && (bMoveUp = IMG_Load2((char*)"gfx/editor/bMoveUp.png")) + && (bNewPuzzle = IMG_Load2((char*)"gfx/editor/bNewPuzzle.png")) + && (bSaveFileAs = IMG_Load2((char*)"gfx/editor/bSaveFileAs.png")) + && (bSavePuzzle = IMG_Load2((char*)"gfx/editor/bSavePuzzle.png")) + && (bSaveToFile = IMG_Load2((char*)"gfx/editor/bSaveToFile.png")) + && (bTestPuzzle = IMG_Load2((char*)"gfx/editor/bTestPuzzle.png")) +#endif + //end new in 1.3.2 + //new in 1.4.0 + && (bTheme = IMG_Load2((char*)"gfx/bTheme.png")) + && (bSkip = IMG_Load2((char*)"gfx/bSkip.png")) + && (bNext = IMG_Load2((char*)"gfx/bNext.png")) + && (bRetry = IMG_Load2((char*)"gfx/bRetry.png")) + )) + //if there was a problem ie. "File not found" + { + cout << "Error loading image file: " << SDL_GetError() << endl; + exit(1); + } + try + { + bNewGame = IMG_Load3("gfx/bNewGame.png"); + mouse = IMG_Load3("gfx/mouse.png"); + menuMarked = IMG_Load3("gfx/menu/marked.png"); + menuUnmarked = IMG_Load3("gfx/menu/unmarked.png"); + } + catch (exception e) + { + cout << e.what() << endl; + exit(1); + } + + + //Prepare for fast blittering! + CONVERT(background); + CONVERT(backgroundImage); // CONVERT(b1player); // CONVERT(b2players); // CONVERT(bVsMode); @@ -547,160 +554,166 @@ static int InitImages() // CONVERT(bPuzzle); // CONVERT(bStageClear); // CONVERT(bTimeTrial); - //CONVERT(bEndless); - CONVERT(bOptions); - CONVERTA(bConfigure); - CONVERTA(bSelectPuzzle); + //CONVERT(bEndless); + CONVERT(bOptions); + CONVERTA(bConfigure); + CONVERTA(bSelectPuzzle); // CONVERTA(bReplay); // CONVERTA(bSave); // CONVERTA(bLoad); - CONVERTA(bTheme); - CONVERTA(bSkip); - CONVERTA(bRetry); - CONVERTA(bNext); -/*#if NETWORK - CONVERTA(bNetwork); - CONVERTA(bHost); - CONVERTA(bConnect); -#endif*/ - CONVERT(bHighScore); - CONVERTA(boardBackBack); - CONVERT(backBoard); - CONVERT(blackLine); - CONVERTA(changeButtonsBack); - CONVERTA(cursor[0]); - CONVERTA(cursor[1]); - CONVERTA(counter[0]); - CONVERTA(counter[1]); - CONVERTA(counter[2]); + CONVERTA(bTheme); + CONVERTA(bSkip); + CONVERTA(bRetry); + CONVERTA(bNext); + /*#if NETWORK + CONVERTA(bNetwork); + CONVERTA(bHost); + CONVERTA(bConnect); + #endif*/ + CONVERT(bHighScore); + CONVERTA(boardBackBack); + CONVERT(backBoard); + CONVERT(blackLine); + CONVERTA(changeButtonsBack); + CONVERTA(cursor[0]); + CONVERTA(cursor[1]); + CONVERTA(counter[0]); + CONVERTA(counter[1]); + CONVERTA(counter[2]); // CONVERTA(optionsBack); // CONVERT(bExit); - CONVERT(bOn); - CONVERT(bOff); + CONVERT(bOn); + CONVERT(bOff); // CONVERT(bChange); - CONVERT(b1024); - CONVERTA(dialogBox); + CONVERT(b1024); + CONVERTA(dialogBox); // CONVERTA(fileDialogBox); - CONVERTA(iLevelCheck); - CONVERT(iLevelCheckBox); - CONVERT(iLevelCheckBoxMarked); - CONVERTA(iCheckBoxArea); - for (int i = 0;i<4;i++) - { - CONVERTA(explosion[i]); - } - for (int i = 0; i<7; i++) - { - CONVERTA(bricks[i]); - CONVERTA(balls[i]); - } - CONVERTA(crossover); - CONVERTA(garbageTL); - CONVERTA(garbageT); - CONVERTA(garbageTR); - CONVERTA(garbageR); - CONVERTA(garbageBR); - CONVERTA(garbageB); - CONVERTA(garbageBL); - CONVERTA(garbageL); - CONVERTA(garbageFill); - CONVERTA(garbageML); - CONVERTA(garbageMR); - CONVERTA(garbageM); - CONVERTA(garbageGML); - CONVERTA(garbageGMR); - CONVERTA(garbageGM); - CONVERTA(smiley[0]); - CONVERTA(smiley[1]); - CONVERTA(smiley[2]); - CONVERTA(smiley[3]); - CONVERTA(iWinner); - CONVERTA(iDraw); - CONVERTA(iLoser); - CONVERTA(iChainBack); - CONVERTA(iGameOver); - mouse.OptimizeForBlit(true); - bNewGame.OptimizeForBlit(true); - CONVERTA(stageBobble); - CONVERTA(transCover); - //Editor: - #if LEVELEDITOR - CONVERTA(bCreateFile); - CONVERTA(bDeletePuzzle); - CONVERTA(bLoadFile); - CONVERTA(bMoveBack); - CONVERTA(bMoveDown); - CONVERTA(bMoveForward); - CONVERTA(bMoveLeft); - CONVERTA(bMoveRight); - CONVERTA(bMoveUp); - CONVERTA(bNewPuzzle); - CONVERTA(bSaveFileAs); - CONVERTA(bSavePuzzle); - CONVERTA(bSaveToFile); - CONVERTA(bTestPuzzle); - #endif - - SDL_Color nf_button_color, nf_standard_blue_color, nf_standard_small_color; - memset(&nf_button_color,0,sizeof(SDL_Color)); - nf_button_color.b = 255; nf_button_color.g = 255; nf_button_color.r = 255; - nf_standard_blue_color.b = 255; nf_standard_blue_color.g = 0; nf_standard_blue_color.r = 0; - nf_standard_small_color.b = 0; nf_standard_small_color.g = 0; nf_standard_small_color.r = 200; - NFont_OpenFont(&nf_button_font,"fonts/FreeSerif.ttf",24,nf_button_color); - nf_button_font.setDest(screen); - NFont_OpenFont(&nf_standard_blue_font,"fonts/FreeSerif.ttf",30,nf_standard_blue_color); - nf_standard_blue_font.setDest(screen); - NFont_OpenFont(&nf_standard_small_font,"fonts/FreeSerif.ttf",16,nf_standard_small_color); - nf_standard_small_font.setDest(screen); - NFont_OpenFont(&nf_scoreboard_font,"fonts/PenguinAttack.ttf",20,nf_button_color); - nf_scoreboard_font.setDest(boardBackBack); - nf_scoreboard_font.draw(370,148,_("Score:") ); - nf_scoreboard_font.draw(370,197,_("Time:") ); - nf_scoreboard_font.draw(370,246,_("Chain:") ); - nf_scoreboard_font.draw(370,295,_("Speed:") ); - - + CONVERTA(iLevelCheck); + CONVERT(iLevelCheckBox); + CONVERT(iLevelCheckBoxMarked); + CONVERTA(iCheckBoxArea); + for (int i = 0; i<4; i++) + { + CONVERTA(explosion[i]); + } + for (int i = 0; i<7; i++) + { + CONVERTA(bricks[i]); + CONVERTA(balls[i]); + } + CONVERTA(crossover); + CONVERTA(garbageTL); + CONVERTA(garbageT); + CONVERTA(garbageTR); + CONVERTA(garbageR); + CONVERTA(garbageBR); + CONVERTA(garbageB); + CONVERTA(garbageBL); + CONVERTA(garbageL); + CONVERTA(garbageFill); + CONVERTA(garbageML); + CONVERTA(garbageMR); + CONVERTA(garbageM); + CONVERTA(garbageGML); + CONVERTA(garbageGMR); + CONVERTA(garbageGM); + CONVERTA(smiley[0]); + CONVERTA(smiley[1]); + CONVERTA(smiley[2]); + CONVERTA(smiley[3]); + CONVERTA(iWinner); + CONVERTA(iDraw); + CONVERTA(iLoser); + CONVERTA(iChainBack); + CONVERTA(iGameOver); + mouse.OptimizeForBlit(true); + bNewGame.OptimizeForBlit(true); + CONVERTA(stageBobble); + CONVERTA(transCover); + //Editor: +#if LEVELEDITOR + CONVERTA(bCreateFile); + CONVERTA(bDeletePuzzle); + CONVERTA(bLoadFile); + CONVERTA(bMoveBack); + CONVERTA(bMoveDown); + CONVERTA(bMoveForward); + CONVERTA(bMoveLeft); + CONVERTA(bMoveRight); + CONVERTA(bMoveUp); + CONVERTA(bNewPuzzle); + CONVERTA(bSaveFileAs); + CONVERTA(bSavePuzzle); + CONVERTA(bSaveToFile); + CONVERTA(bTestPuzzle); +#endif + + SDL_Color nf_button_color, nf_standard_blue_color, nf_standard_small_color; + memset(&nf_button_color,0,sizeof(SDL_Color)); + nf_button_color.b = 255; + nf_button_color.g = 255; + nf_button_color.r = 255; + nf_standard_blue_color.b = 255; + nf_standard_blue_color.g = 0; + nf_standard_blue_color.r = 0; + nf_standard_small_color.b = 0; + nf_standard_small_color.g = 0; + nf_standard_small_color.r = 200; + NFont_OpenFont(&nf_button_font,"fonts/FreeSerif.ttf",24,nf_button_color); + nf_button_font.setDest(screen); + NFont_OpenFont(&nf_standard_blue_font,"fonts/FreeSerif.ttf",30,nf_standard_blue_color); + nf_standard_blue_font.setDest(screen); + NFont_OpenFont(&nf_standard_small_font,"fonts/FreeSerif.ttf",16,nf_standard_small_color); + nf_standard_small_font.setDest(screen); + NFont_OpenFont(&nf_scoreboard_font,"fonts/PenguinAttack.ttf",20,nf_button_color); + nf_scoreboard_font.setDest(boardBackBack); + nf_scoreboard_font.draw(370,148,_("Score:") ); + nf_scoreboard_font.draw(370,197,_("Time:") ); + nf_scoreboard_font.draw(370,246,_("Chain:") ); + nf_scoreboard_font.draw(370,295,_("Speed:") ); + + //Loads the sound if sound present - if (!NoSound) - { - //And here the music: - bgMusic = Mix_LoadMUS2((char*)"music/bgMusic.ogg"); - highbeatMusic = Mix_LoadMUS2((char*)"music/highbeat.ogg"); - //the music... we just hope it exists, else the user won't hear anything - //Same goes for the sounds - boing = Mix_LoadWAV2((char*)"sound/pop.ogg"); - applause = Mix_LoadWAV2((char*)"sound/applause.ogg"); - photoClick = Mix_LoadWAV2((char*)"sound/cameraclick.ogg"); - typingChunk = Mix_LoadWAV2((char*)"sound/typing.ogg"); - counterChunk = Mix_LoadWAV2((char*)"sound/counter.ogg"); - counterFinalChunk = Mix_LoadWAV2((char*)"sound/counterFinal.ogg"); - } //All sound has been loaded or not - return 0; + if (!NoSound) + { + //And here the music: + bgMusic = Mix_LoadMUS2((char*)"music/bgMusic.ogg"); + highbeatMusic = Mix_LoadMUS2((char*)"music/highbeat.ogg"); + //the music... we just hope it exists, else the user won't hear anything + //Same goes for the sounds + boing = Mix_LoadWAV2((char*)"sound/pop.ogg"); + applause = Mix_LoadWAV2((char*)"sound/applause.ogg"); + photoClick = Mix_LoadWAV2((char*)"sound/cameraclick.ogg"); + typingChunk = Mix_LoadWAV2((char*)"sound/typing.ogg"); + counterChunk = Mix_LoadWAV2((char*)"sound/counter.ogg"); + counterFinalChunk = Mix_LoadWAV2((char*)"sound/counterFinal.ogg"); + } //All sound has been loaded or not + return 0; } //InitImages() //Unload images and fonts and sounds void UnloadImages() { - cout << "Unloading data..." << endl; - if (!NoSound) //Only unload then it has been loaded! - { - Mix_HaltMusic(); - Mix_FreeMusic(bgMusic); - Mix_FreeMusic(highbeatMusic); - Mix_FreeChunk(boing); - Mix_FreeChunk(applause); - Mix_FreeChunk(photoClick); - Mix_FreeChunk(counterChunk); - Mix_FreeChunk(counterFinalChunk); - Mix_FreeChunk(typingChunk); - } - //Free surfaces: - //I think this will crash, at least it happend to me... - //Chrashes no more. Caused by an undocumented double free - SDL_FreeSurface(backgroundImage); - SDL_FreeSurface(background); - //SDL_FreeSurface(bNewGame); + cout << "Unloading data..." << endl; + if (!NoSound) //Only unload then it has been loaded! + { + Mix_HaltMusic(); + Mix_FreeMusic(bgMusic); + Mix_FreeMusic(highbeatMusic); + Mix_FreeChunk(boing); + Mix_FreeChunk(applause); + Mix_FreeChunk(photoClick); + Mix_FreeChunk(counterChunk); + Mix_FreeChunk(counterFinalChunk); + Mix_FreeChunk(typingChunk); + } + //Free surfaces: + //I think this will crash, at least it happend to me... + //Chrashes no more. Caused by an undocumented double free + SDL_FreeSurface(backgroundImage); + SDL_FreeSurface(background); + //SDL_FreeSurface(bNewGame); // SDL_FreeSurface(b1player); // SDL_FreeSurface(b2players); // SDL_FreeSurface(bVsMode); @@ -708,80 +721,80 @@ void UnloadImages() // SDL_FreeSurface(bPuzzle); // SDL_FreeSurface(bStageClear); // SDL_FreeSurface(bTimeTrial); - //SDL_FreeSurface(bEndless); - SDL_FreeSurface(bOptions); - SDL_FreeSurface(bConfigure); - SDL_FreeSurface(bSelectPuzzle); - SDL_FreeSurface(bHighScore); + //SDL_FreeSurface(bEndless); + SDL_FreeSurface(bOptions); + SDL_FreeSurface(bConfigure); + SDL_FreeSurface(bSelectPuzzle); + SDL_FreeSurface(bHighScore); // SDL_FreeSurface(bReplay); // SDL_FreeSurface(bSave); // SDL_FreeSurface(bLoad); -/* #if NETWORK - SDL_FreeSurface(bNetwork); - SDL_FreeSurface(bHost); - SDL_FreeSurface(bConnect); - #endif - SDL_FreeSurface(bExit);*/ - SDL_FreeSurface(blackLine); - SDL_FreeSurface(stageBobble); - SDL_FreeSurface(bricks[0]); - SDL_FreeSurface(bricks[1]); - SDL_FreeSurface(bricks[2]); - SDL_FreeSurface(bricks[3]); - SDL_FreeSurface(bricks[4]); - SDL_FreeSurface(bricks[5]); - SDL_FreeSurface(bricks[6]); - SDL_FreeSurface(crossover); - SDL_FreeSurface(balls[0]); - SDL_FreeSurface(balls[1]); - SDL_FreeSurface(balls[2]); - SDL_FreeSurface(balls[3]); - SDL_FreeSurface(balls[4]); - SDL_FreeSurface(balls[5]); - SDL_FreeSurface(balls[6]); - SDL_FreeSurface(cursor[0]); - SDL_FreeSurface(cursor[1]); - SDL_FreeSurface(backBoard); //not used, we just test if it exists :) - SDL_FreeSurface(iGameOver); - SDL_FreeSurface(iWinner); - SDL_FreeSurface(iDraw); - SDL_FreeSurface(iLoser); - SDL_FreeSurface(iChainBack); + /* #if NETWORK + SDL_FreeSurface(bNetwork); + SDL_FreeSurface(bHost); + SDL_FreeSurface(bConnect); + #endif + SDL_FreeSurface(bExit);*/ + SDL_FreeSurface(blackLine); + SDL_FreeSurface(stageBobble); + SDL_FreeSurface(bricks[0]); + SDL_FreeSurface(bricks[1]); + SDL_FreeSurface(bricks[2]); + SDL_FreeSurface(bricks[3]); + SDL_FreeSurface(bricks[4]); + SDL_FreeSurface(bricks[5]); + SDL_FreeSurface(bricks[6]); + SDL_FreeSurface(crossover); + SDL_FreeSurface(balls[0]); + SDL_FreeSurface(balls[1]); + SDL_FreeSurface(balls[2]); + SDL_FreeSurface(balls[3]); + SDL_FreeSurface(balls[4]); + SDL_FreeSurface(balls[5]); + SDL_FreeSurface(balls[6]); + SDL_FreeSurface(cursor[0]); + SDL_FreeSurface(cursor[1]); + SDL_FreeSurface(backBoard); //not used, we just test if it exists :) + SDL_FreeSurface(iGameOver); + SDL_FreeSurface(iWinner); + SDL_FreeSurface(iDraw); + SDL_FreeSurface(iLoser); + SDL_FreeSurface(iChainBack); // SDL_FreeSurface(optionsBack); - SDL_FreeSurface(bOn); - SDL_FreeSurface(bOff); + SDL_FreeSurface(bOn); + SDL_FreeSurface(bOff); // SDL_FreeSurface(bChange); - SDL_FreeSurface(b1024); - SDL_FreeSurface(dialogBox); - //SDL_FreeSurface(fileDialogBox); - SDL_FreeSurface(iLevelCheck); - SDL_FreeSurface(iLevelCheckBox); - SDL_FreeSurface(iLevelCheckBoxMarked); - SDL_FreeSurface(iCheckBoxArea); - SDL_FreeSurface(boardBackBack); - SDL_FreeSurface(changeButtonsBack); - SDL_FreeSurface(garbageTL); - SDL_FreeSurface(garbageT); - SDL_FreeSurface(garbageTR); - SDL_FreeSurface(garbageR); - SDL_FreeSurface(garbageBR); - SDL_FreeSurface(garbageB); - SDL_FreeSurface(garbageBL); - SDL_FreeSurface(garbageL); - SDL_FreeSurface(garbageFill); - SDL_FreeSurface(garbageML); - SDL_FreeSurface(garbageM); - SDL_FreeSurface(garbageMR); - SDL_FreeSurface(garbageGML); - SDL_FreeSurface(garbageGM); - SDL_FreeSurface(garbageGMR); - SDL_FreeSurface(smiley[0]); - SDL_FreeSurface(smiley[1]); - SDL_FreeSurface(smiley[2]); - SDL_FreeSurface(smiley[3]); - SDL_FreeSurface(transCover); - mouse.MakeNull(); - bNewGame.MakeNull(); + SDL_FreeSurface(b1024); + SDL_FreeSurface(dialogBox); + //SDL_FreeSurface(fileDialogBox); + SDL_FreeSurface(iLevelCheck); + SDL_FreeSurface(iLevelCheckBox); + SDL_FreeSurface(iLevelCheckBoxMarked); + SDL_FreeSurface(iCheckBoxArea); + SDL_FreeSurface(boardBackBack); + SDL_FreeSurface(changeButtonsBack); + SDL_FreeSurface(garbageTL); + SDL_FreeSurface(garbageT); + SDL_FreeSurface(garbageTR); + SDL_FreeSurface(garbageR); + SDL_FreeSurface(garbageBR); + SDL_FreeSurface(garbageB); + SDL_FreeSurface(garbageBL); + SDL_FreeSurface(garbageL); + SDL_FreeSurface(garbageFill); + SDL_FreeSurface(garbageML); + SDL_FreeSurface(garbageM); + SDL_FreeSurface(garbageMR); + SDL_FreeSurface(garbageGML); + SDL_FreeSurface(garbageGM); + SDL_FreeSurface(garbageGMR); + SDL_FreeSurface(smiley[0]); + SDL_FreeSurface(smiley[1]); + SDL_FreeSurface(smiley[2]); + SDL_FreeSurface(smiley[3]); + SDL_FreeSurface(transCover); + mouse.MakeNull(); + bNewGame.MakeNull(); } //Function to convert numbers to string @@ -795,79 +808,81 @@ void UnloadImages() //Function to convert numbers to string (2 diget) static string itoa2(int num) { - stringstream converter; - if(num<10) - converter << "0"; - converter << num; - return converter.str(); + stringstream converter; + if(num<10) + converter << "0"; + converter << num; + return converter.str(); } /*Loads all the puzzle levels*/ static int LoadPuzzleStages() { - //if(puzzleLoaded) - // return 1; - if (!PHYSFS_exists(("puzzles/"+puzzleName).c_str())) - { - cout << "File not in blockattack.data: " << ("puzzles/"+puzzleName) << endl; - return -1; //file doesn't exist - } - PhysFS::ifstream inFile(("puzzles/"+puzzleName).c_str()); - - inFile >> nrOfPuzzles; - if (nrOfPuzzles>maxNrOfPuzzleStages) - nrOfPuzzles=maxNrOfPuzzleStages; - for (int k=0; (k> nrOfMovesAllowed[k]; - for (int i=11;i>=0;i--) - for (int j=0;j<6;j++) - { - inFile >> puzzleLevels[k][j][i]; - } - } - puzzleLoaded = true; - return 0; + //if(puzzleLoaded) + // return 1; + if (!PHYSFS_exists(("puzzles/"+puzzleName).c_str())) + { + cout << "File not in blockattack.data: " << ("puzzles/"+puzzleName) << endl; + return -1; //file doesn't exist + } + PhysFS::ifstream inFile(("puzzles/"+puzzleName).c_str()); + + inFile >> nrOfPuzzles; + if (nrOfPuzzles>maxNrOfPuzzleStages) + nrOfPuzzles=maxNrOfPuzzleStages; + for (int k=0; (k> nrOfMovesAllowed[k]; + for (int i=11; i>=0; i--) + for (int j=0; j<6; j++) + { + inFile >> puzzleLevels[k][j][i]; + } + } + puzzleLoaded = true; + return 0; } /*Draws a image from on a given Surface. Takes source image, destination surface and coordinates*/ void DrawIMG(SDL_Surface *img, SDL_Surface *target, int x, int y) { - SDL_Rect dest; - dest.x = x; - dest.y = y; - SDL_BlitSurface(img, NULL, target, &dest); + SDL_Rect dest; + dest.x = x; + dest.y = y; + SDL_BlitSurface(img, NULL, target, &dest); } /*Draws a part of an image on a surface of choice*/ void DrawIMG(SDL_Surface *img, SDL_Surface * target, int x, int y, int w, int h, int x2, int y2) { - SDL_Rect dest; - dest.x = x; - dest.y = y; - SDL_Rect dest2; - dest2.x = x2; - dest2.y = y2; - dest2.w = w; - dest2.h = h; - SDL_BlitSurface(img, &dest2, target, &dest); + SDL_Rect dest; + dest.x = x; + dest.y = y; + SDL_Rect dest2; + dest2.x = x2; + dest2.y = y2; + dest2.w = w; + dest2.h = h; + SDL_BlitSurface(img, &dest2, target, &dest); } -void NFont_Write(SDL_Surface *target,int x,int y,string text) { - nf_standard_blue_font.setDest(target); - nf_standard_blue_font.draw(x,y,text.c_str()); - nf_standard_blue_font.setDest(screen); +void NFont_Write(SDL_Surface *target,int x,int y,string text) +{ + nf_standard_blue_font.setDest(target); + nf_standard_blue_font.draw(x,y,text.c_str()); + nf_standard_blue_font.setDest(screen); } -void ResetFullscreen(){ +void ResetFullscreen() +{ #if defined(WIN32) - if (bFullscreen) screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_FULLSCREEN|SDL_ANYFORMAT); - else screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_ANYFORMAT); - DrawIMG(background, screen, 0, 0); + if (bFullscreen) screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_FULLSCREEN|SDL_ANYFORMAT); + else screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_ANYFORMAT); + DrawIMG(background, screen, 0, 0); #else - SDL_WM_ToggleFullScreen(screen); //Will only work in Linux + SDL_WM_ToggleFullScreen(screen); //Will only work in Linux #endif - SDL_ShowCursor(SDL_DISABLE); + SDL_ShowCursor(SDL_DISABLE); } @@ -875,67 +890,67 @@ void ResetFullscreen(){ class aBall { private: - double x; - double y; - double velocityY; - double velocityX; - int color; - unsigned long int lastTime; + double x; + double y; + double velocityY; + double velocityX; + int color; + unsigned long int lastTime; public: - aBall() - {} - - //constructor: - aBall(int X, int Y, bool right, int coulor) - { - double tal = 1.0; - velocityY = -tal*startVelocityY; - lastTime = currentTime; - x = (double)X; - y = (double)Y; - color = coulor; - if (right) - velocityX = tal*VelocityX; - else - velocityX = -tal*VelocityX; - } //constructor - - //Deconstructor - ~aBall() - { - } //Deconstructor - - void update() - { - double timePassed = (((double)(currentTime-lastTime))/1000.0); //time passed in seconds - x = x+timePassed*velocityX; - y = y+timePassed*velocityY; - velocityY = velocityY + gravity*timePassed; - if (y<1.0) - velocityY=10.0; - if ((velocityY>minVelocity) && (y>(double)(768-ballSize)) && (y<768.0)) - { - velocityY = -0.70*velocityY; - y = 768.0-ballSize; - } - lastTime = currentTime; - } - - int getX() - { - return (int)x; - } - - int getY() - { - return (int)y; - } - - int getColor() - { - return color; - } + aBall() + {} + + //constructor: + aBall(int X, int Y, bool right, int coulor) + { + double tal = 1.0; + velocityY = -tal*startVelocityY; + lastTime = currentTime; + x = (double)X; + y = (double)Y; + color = coulor; + if (right) + velocityX = tal*VelocityX; + else + velocityX = -tal*VelocityX; + } //constructor + + //Deconstructor + ~aBall() + { + } //Deconstructor + + void update() + { + double timePassed = (((double)(currentTime-lastTime))/1000.0); //time passed in seconds + x = x+timePassed*velocityX; + y = y+timePassed*velocityY; + velocityY = velocityY + gravity*timePassed; + if (y<1.0) + velocityY=10.0; + if ((velocityY>minVelocity) && (y>(double)(768-ballSize)) && (y<768.0)) + { + velocityY = -0.70*velocityY; + y = 768.0-ballSize; + } + lastTime = currentTime; + } + + int getX() + { + return (int)x; + } + + int getY() + { + return (int)y; + } + + int getColor() + { + return color; + } }; //aBall static const int maxNumberOfBalls = 6*12*2*2; @@ -943,59 +958,59 @@ static const int maxNumberOfBalls = 6*12*2*2; class ballManeger { public: - aBall ballArray[maxNumberOfBalls]; - bool ballUsed[maxNumberOfBalls]; - //The old ball information is also saved so balls can be deleted! - aBall oldBallArray[maxNumberOfBalls]; - bool oldBallUsed[maxNumberOfBalls]; - - ballManeger() - { - for (int i=0; i800 || ballArray[i].getX()>xsize || ballArray[i].getX()<-ballSize) - { - ballUsed[i] = false; - } - } - else - { - oldBallUsed[i] = false; - } - } - } //update + aBall ballArray[maxNumberOfBalls]; + bool ballUsed[maxNumberOfBalls]; + //The old ball information is also saved so balls can be deleted! + aBall oldBallArray[maxNumberOfBalls]; + bool oldBallUsed[maxNumberOfBalls]; + + ballManeger() + { + for (int i=0; i800 || ballArray[i].getX()>xsize || ballArray[i].getX()<-ballSize) + { + ballUsed[i] = false; + } + } + else + { + oldBallUsed[i] = false; + } + } + } //update }; //theBallManeger @@ -1006,112 +1021,112 @@ static ballManeger theBallManeger; class anExplosion { private: - int x; - int y; - Uint8 frameNumber; + int x; + int y; + Uint8 frameNumber; #define frameLength 80 - //How long an image in an animation should be showed + //How long an image in an animation should be showed #define maxFrame 4 - //How many images there are in the animation - unsigned long int placeTime; //Then the explosion occored + //How many images there are in the animation + unsigned long int placeTime; //Then the explosion occored public: - anExplosion() - {} - - //constructor: - anExplosion(int X, int Y) - { - placeTime = currentTime; - x = X; - y = Y; - frameNumber=0; - } //constructor - - //Deconstructor - ~anExplosion() - { - } //Deconstructor - - //true if animation has played and object should be removed from the screen - bool removeMe() - { - frameNumber = (currentTime-placeTime)/frameLength; - return (!(frameNumbertime; - } - - int getX() - { - return x; - } - - int getY() - { - return y; - } - - char* getText() - { - return textt; - } + textMessage() + {} + + //constructor: + textMessage(int X, int Y,const char* Text,unsigned int Time) + { + placeTime = currentTime; + x = X; + y = Y; + strncpy(textt,Text,10); + textt[9]=0; + time = Time; + } //constructor + + //true if the text has expired + bool removeMe() + { + return currentTime-placeTime>time; + } + + int getX() + { + return x; + } + + int getY() + { + return y; + } + + char* getText() + { + return textt; + } }; //text popup class textManeger { public: - textMessage textArray[maxNumberOfBalls]; - bool textUsed[maxNumberOfBalls]; - //The old text information is also saved so text can be deleted! - textMessage oldTextArray[maxNumberOfBalls]; - bool oldTextUsed[maxNumberOfBalls]; - - textManeger() - { - for (int i=0; i5) right = -1; - else right = board[j+1][i]; - if (i>28) over = -1; - else over = board[j][i+1]; - if (i<1) under = -1; - else under = board[j][i-1]; - if ((left == number)&&(right == number)&&(over == number)&&(under == number)) - DrawIMG(garbageFill, sBoard, j*bsize, bsize*12-i*bsize-pixels); - if ((left != number)&&(right == number)&&(over == number)&&(under == number)) - DrawIMG(garbageL, sBoard, j*bsize, bsize*12-i*bsize-pixels); - if ((left == number)&&(right != number)&&(over == number)&&(under == number)) - DrawIMG(garbageR, sBoard, j*bsize, bsize*12-i*bsize-pixels); - if ((left == number)&&(right == number)&&(over != number)&&(under == number)) - DrawIMG(garbageT, sBoard, j*bsize, bsize*12-i*bsize-pixels); - if ((left == number)&&(right == number)&&(over == number)&&(under != number)) - DrawIMG(garbageB, sBoard, j*bsize, bsize*12-i*bsize-pixels); - if ((left != number)&&(right == number)&&(over != number)&&(under == number)) - DrawIMG(garbageTL, sBoard, j*bsize, bsize*12-i*bsize-pixels); - if ((left != number)&&(right == number)&&(over == number)&&(under != number)) - DrawIMG(garbageBL, sBoard, j*bsize, bsize*12-i*bsize-pixels); - if ((left == number)&&(right != number)&&(over != number)&&(under == number)) - DrawIMG(garbageTR, sBoard, j*bsize, bsize*12-i*bsize-pixels); - if ((left == number)&&(right != number)&&(over == number)&&(under != number)) - DrawIMG(garbageBR, sBoard, j*bsize, bsize*12-i*bsize-pixels); - if ((left == number)&&(right != number)&&(over != number)&&(under != number)) - DrawIMG(garbageMR, sBoard, j*bsize, bsize*12-i*bsize-pixels); - if ((left == number)&&(right == number)&&(over != number)&&(under != number)) - DrawIMG(garbageM, sBoard, j*bsize, bsize*12-i*bsize-pixels); - if ((left != number)&&(right == number)&&(over != number)&&(under != number)) - DrawIMG(garbageML, sBoard, j*bsize, bsize*12-i*bsize-pixels); - } - if ((board[j][i]/1000000)%10==2) { - if (j==0) - DrawIMG(garbageGML, sBoard, j*bsize, bsize*12-i*bsize-pixels); - else - if (j==5) - DrawIMG(garbageGMR, sBoard, j*bsize, bsize*12-i*bsize-pixels); - else - DrawIMG(garbageGM, sBoard, j*bsize, bsize*12-i*bsize-pixels); - } - } - const int j = 0; - - int garbageSize=0; - for (int i=0;i<20;i++) { - if ((board[j][i]/1000000)%10==1) { - int left, right, over, under; - int number = board[j][i]; - if (j<1) left = -1; - else left = board[j-1][i]; - if (j>5) right = -1; - else right = board[j+1][i]; - if (i>28) over = -1; - else over = board[j][i+1]; - if (i<1) under = -1; - else under = board[j][i-1]; - if (((left != number)&&(right == number)&&(over != number)&&(under == number))&&(garbageSize>0)) { - DrawIMG(smiley[board[j][i]%4], sBoard, 2*bsize, 12*bsize-i*bsize-pixels+(bsize/2)*garbageSize); - } - if (!((left != number)&&(right == number)&&(over == number)&&(under == number))) //not in garbage - { - garbageSize=0; - } - else { - //cout << "In garbage" << endl; - garbageSize++; - } - - } - } - for (int i=0;i<6;i++) - if (board[i][0]!=-1) - DrawIMG(transCover, sBoard, i*bsize, 12*bsize-pixels); //Make the appering blocks transperant - - } - //Paints the bricks gotten from a replay/net package - void SimplePaintBricks() { - /* - * We will need to mark the blocks that must have a bomb, we will here need to see, what is falling - */ - bool bbomb[6][13]; //has a bomb on it! - bool falling[6][13]; //this is falling - bool getReady[6][13]; //getReady - for (int i=0;i<6;i++) - for (int j=0;j<13;j++) { - bbomb[i][j]=false; //All false by default - falling[i][j]=false; - if (board[i][j]>29) - getReady[i][j]=true; - else - getReady[i][j]=false; - } - //See that is falling - for (int i=0;i<6;i++) { - bool rowFalling = false; - for (int j=0;j<13;j++) { - if (rowFalling) - falling[i][j]=true; - if ((!rowFalling)&&(board[i][j]%30==-1)) - rowFalling = true; - if ((rowFalling)&&(board[i][j]%30>6)) - rowFalling = false; - if (getReady[i][j]) { - falling[i][j]=true; //getReady is the same as falling - rowFalling = false; - } - } - } - //Now looking at rows: - for (int i=0;i<6;i++) { - int count = 0; - int color = -1; - for (int j=1;j<13;j++) { - if ((board[i][j]%30==color)&&(!falling[i][j])) - count++; - else - if (falling[i][j]) { - count = 0; - } - else { - color=board[i][j]%30; - count=1; - } - if ((count>2)&&(color>-1)&&(color)<7) { - bbomb[i][j]=true; - bbomb[i][j-1]=true; - bbomb[i][j-2]=true; - } - } - } - //now looking for lines - for (int i=1;i<13;i++) { - int count = 0; - int color = -1; - for (int j=0;j<6;j++) { - if ((board[j][i]%30==color)&&(!falling[j][i])) - count++; - else - if (falling[j][i]) { - count = 0; - } - else { - color=board[j][i]%30; - count=1; - } - if ((count>2)&&(color>-1)&&(color<7)) { - bbomb[j][i]=true; - bbomb[j-1][i]=true; - bbomb[j-2][i]=true; - } - } - } - for (int i=0;((i<13)&&(i<30));i++) - for (int j=0;j<6;j++) { - if ((board[j][i]%10 != -1) && (board[j][i]%30 < 7)) { - DrawIMG(bricks[board[j][i]%10], sBoard, j*bsize, 12*bsize-i*bsize-pixels); - if (bbomb[j][i]) - DrawIMG(bomb[(ticks/BOMBTIME)%2], sBoard, j*bsize, 12*bsize-i*bsize-pixels); - if (getReady[j][i]) - DrawIMG(ready[(ticks/READYTIME)%2], sBoard, j*bsize, 12*bsize-i*bsize-pixels); - } - if (board[j][i]%30>6) { - if (board[j][i]%30==7) - DrawIMG(garbageR, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==9) - DrawIMG(garbageML, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==10) - DrawIMG(garbageMR, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==11) - DrawIMG(garbageTR, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==12) - DrawIMG(garbageTL, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==13) - DrawIMG(garbageBL, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==14) - DrawIMG(garbageBR, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==15) - DrawIMG(garbageM, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==16) - DrawIMG(garbageFill, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==17) - DrawIMG(garbageT, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==18) - DrawIMG(garbageB, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==19) - DrawIMG(garbageL, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good - if (board[j][i]%30==20) - switch(j) { - case 0: - DrawIMG(garbageGML, sBoard,j*bsize, 12*bsize-i*bsize-pixels); - break; - case 5: - DrawIMG(garbageGMR, sBoard,j*bsize, 12*bsize-i*bsize-pixels); - break; - default: - DrawIMG(garbageGM, sBoard,j*bsize, 12*bsize-i*bsize-pixels); - } - //cout << "IS: " << board[j][i] << endl; - } - - - } - - int garbageSize=0; - for (int i=0;i<20;i++) { - if ((board[0][i]%30==12)&&(garbageSize>0)) { - DrawIMG(smiley[0], sBoard, 2*bsize, bsize-i*bsize-pixels+(bsize/2)*garbageSize); - } - if (board[0][i]%30!=19) //not in garbage - { - garbageSize=0; - } - else { - //cout << "In garbage" << endl; - garbageSize++; - } + void convertSurface() + { + SDL_FreeSurface(sBoard); + sBoard = SDL_DisplayFormat(backBoard); + } + //Draws all the bricks to the board (including garbage) + void PaintBricks() + { + for (int i=0; ((i<13)&&(i<30)); i++) + for (int j=0; j<6; j++) + { + if ((board[j][i]%10 != -1) && (board[j][i]%10 < 7) && ((board[j][i]/1000000)%10==0)) + { + DrawIMG(bricks[board[j][i]%10], sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((board[j][i]/BLOCKWAIT)%10==1) + DrawIMG(bomb[(ticks/BOMBTIME)%2], sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((board[j][i]/BLOCKHANG)%10==1) + DrawIMG(ready[(ticks/READYTIME)%2], sBoard, j*bsize, bsize*12-i*bsize-pixels); + + } + if ((board[j][i]/1000000)%10==1) + { + int left, right, over, under; + int number = board[j][i]; + if (j<1) left = -1; + else left = board[j-1][i]; + if (j>5) right = -1; + else right = board[j+1][i]; + if (i>28) over = -1; + else over = board[j][i+1]; + if (i<1) under = -1; + else under = board[j][i-1]; + if ((left == number)&&(right == number)&&(over == number)&&(under == number)) + DrawIMG(garbageFill, sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((left != number)&&(right == number)&&(over == number)&&(under == number)) + DrawIMG(garbageL, sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((left == number)&&(right != number)&&(over == number)&&(under == number)) + DrawIMG(garbageR, sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((left == number)&&(right == number)&&(over != number)&&(under == number)) + DrawIMG(garbageT, sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((left == number)&&(right == number)&&(over == number)&&(under != number)) + DrawIMG(garbageB, sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((left != number)&&(right == number)&&(over != number)&&(under == number)) + DrawIMG(garbageTL, sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((left != number)&&(right == number)&&(over == number)&&(under != number)) + DrawIMG(garbageBL, sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((left == number)&&(right != number)&&(over != number)&&(under == number)) + DrawIMG(garbageTR, sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((left == number)&&(right != number)&&(over == number)&&(under != number)) + DrawIMG(garbageBR, sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((left == number)&&(right != number)&&(over != number)&&(under != number)) + DrawIMG(garbageMR, sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((left == number)&&(right == number)&&(over != number)&&(under != number)) + DrawIMG(garbageM, sBoard, j*bsize, bsize*12-i*bsize-pixels); + if ((left != number)&&(right == number)&&(over != number)&&(under != number)) + DrawIMG(garbageML, sBoard, j*bsize, bsize*12-i*bsize-pixels); + } + if ((board[j][i]/1000000)%10==2) + { + if (j==0) + DrawIMG(garbageGML, sBoard, j*bsize, bsize*12-i*bsize-pixels); + else if (j==5) + DrawIMG(garbageGMR, sBoard, j*bsize, bsize*12-i*bsize-pixels); + else + DrawIMG(garbageGM, sBoard, j*bsize, bsize*12-i*bsize-pixels); + } + } + const int j = 0; + + int garbageSize=0; + for (int i=0; i<20; i++) + { + if ((board[j][i]/1000000)%10==1) + { + int left, right, over, under; + int number = board[j][i]; + if (j<1) left = -1; + else left = board[j-1][i]; + if (j>5) right = -1; + else right = board[j+1][i]; + if (i>28) over = -1; + else over = board[j][i+1]; + if (i<1) under = -1; + else under = board[j][i-1]; + if (((left != number)&&(right == number)&&(over != number)&&(under == number))&&(garbageSize>0)) + { + DrawIMG(smiley[board[j][i]%4], sBoard, 2*bsize, 12*bsize-i*bsize-pixels+(bsize/2)*garbageSize); + } + if (!((left != number)&&(right == number)&&(over == number)&&(under == number))) //not in garbage + { + garbageSize=0; + } + else + { + //cout << "In garbage" << endl; + garbageSize++; + } + + } + } + for (int i=0; i<6; i++) + if (board[i][0]!=-1) + DrawIMG(transCover, sBoard, i*bsize, 12*bsize-pixels); //Make the appering blocks transperant + + } + //Paints the bricks gotten from a replay/net package + void SimplePaintBricks() + { + /* + * We will need to mark the blocks that must have a bomb, we will here need to see, what is falling + */ + bool bbomb[6][13]; //has a bomb on it! + bool falling[6][13]; //this is falling + bool getReady[6][13]; //getReady + for (int i=0; i<6; i++) + for (int j=0; j<13; j++) + { + bbomb[i][j]=false; //All false by default + falling[i][j]=false; + if (board[i][j]>29) + getReady[i][j]=true; + else + getReady[i][j]=false; + } + //See that is falling + for (int i=0; i<6; i++) + { + bool rowFalling = false; + for (int j=0; j<13; j++) + { + if (rowFalling) + falling[i][j]=true; + if ((!rowFalling)&&(board[i][j]%30==-1)) + rowFalling = true; + if ((rowFalling)&&(board[i][j]%30>6)) + rowFalling = false; + if (getReady[i][j]) + { + falling[i][j]=true; //getReady is the same as falling + rowFalling = false; + } + } + } + //Now looking at rows: + for (int i=0; i<6; i++) + { + int count = 0; + int color = -1; + for (int j=1; j<13; j++) + { + if ((board[i][j]%30==color)&&(!falling[i][j])) + count++; + else if (falling[i][j]) + { + count = 0; + } + else + { + color=board[i][j]%30; + count=1; + } + if ((count>2)&&(color>-1)&&(color)<7) + { + bbomb[i][j]=true; + bbomb[i][j-1]=true; + bbomb[i][j-2]=true; + } + } + } + //now looking for lines + for (int i=1; i<13; i++) + { + int count = 0; + int color = -1; + for (int j=0; j<6; j++) + { + if ((board[j][i]%30==color)&&(!falling[j][i])) + count++; + else if (falling[j][i]) + { + count = 0; + } + else + { + color=board[j][i]%30; + count=1; + } + if ((count>2)&&(color>-1)&&(color<7)) + { + bbomb[j][i]=true; + bbomb[j-1][i]=true; + bbomb[j-2][i]=true; + } + } + } + for (int i=0; ((i<13)&&(i<30)); i++) + for (int j=0; j<6; j++) + { + if ((board[j][i]%10 != -1) && (board[j][i]%30 < 7)) + { + DrawIMG(bricks[board[j][i]%10], sBoard, j*bsize, 12*bsize-i*bsize-pixels); + if (bbomb[j][i]) + DrawIMG(bomb[(ticks/BOMBTIME)%2], sBoard, j*bsize, 12*bsize-i*bsize-pixels); + if (getReady[j][i]) + DrawIMG(ready[(ticks/READYTIME)%2], sBoard, j*bsize, 12*bsize-i*bsize-pixels); + } + if (board[j][i]%30>6) + { + if (board[j][i]%30==7) + DrawIMG(garbageR, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==9) + DrawIMG(garbageML, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==10) + DrawIMG(garbageMR, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==11) + DrawIMG(garbageTR, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==12) + DrawIMG(garbageTL, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==13) + DrawIMG(garbageBL, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==14) + DrawIMG(garbageBR, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==15) + DrawIMG(garbageM, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==16) + DrawIMG(garbageFill, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==17) + DrawIMG(garbageT, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==18) + DrawIMG(garbageB, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==19) + DrawIMG(garbageL, sBoard, j*bsize, 12*bsize-i*bsize-pixels); //good + if (board[j][i]%30==20) + switch(j) + { + case 0: + DrawIMG(garbageGML, sBoard,j*bsize, 12*bsize-i*bsize-pixels); + break; + case 5: + DrawIMG(garbageGMR, sBoard,j*bsize, 12*bsize-i*bsize-pixels); + break; + default: + DrawIMG(garbageGM, sBoard,j*bsize, 12*bsize-i*bsize-pixels); + } + //cout << "IS: " << board[j][i] << endl; + } + + + } + + int garbageSize=0; + for (int i=0; i<20; i++) + { + if ((board[0][i]%30==12)&&(garbageSize>0)) + { + DrawIMG(smiley[0], sBoard, 2*bsize, bsize-i*bsize-pixels+(bsize/2)*garbageSize); + } + if (board[0][i]%30!=19) //not in garbage + { + garbageSize=0; + } + else + { + //cout << "In garbage" << endl; + garbageSize++; + } - } - } + } + } public: - //Draws everything - void DoPaintJob() { - DrawIMG(backBoard, sBoard, 0, 0); - nf_standard_blue_font.setDest(sBoard); //reset to screen at the end of this funciton! - #if NETWORK - if ((!bReplaying)&&(!bNetworkPlayer)) - #else - if (!bReplaying) - #endif - PaintBricks(); - else - SimplePaintBricks(); - if (stageClear) DrawIMG(blackLine, sBoard, 0, bsize*(12+2)+bsize*(stageClearLimit-linesCleared)-pixels-1); - if (puzzleMode&&(!bGameOver)) { - //We need to write nr. of moves left! - strHolder = "Moves left: " + itoa(MovesLeft); - nf_standard_blue_font.draw(5,5,strHolder.c_str()); - - } - if(puzzleMode && stageButtonStatus == SBpuzzleMode) - { - DrawIMG(bRetry,sBoard, cordRetryButton.x, cordRetryButton.y); - if(LevelgameStartedAt+10000)&&(!bGameOver)) - { - int currentCounter = (ticks-(int)gameStartedAt)/1000; - if(currentCounter!=lastCounter) - { - if(currentCounter>115 && currentCounter<120) - Mix_PlayChannel(1,counterChunk,0); - } - lastCounter = currentCounter; - } - else - { - if( (0==lastCounter) && (SoundEnabled)&&(!NoSound)) - { - Mix_PlayChannel(1,counterFinalChunk,0); - } - lastCounter = -1; - } - } + if (!bGameOver)DrawIMG(cursor[(ticks/600)%2],sBoard,cursorx*bsize-4,11*bsize-cursory*bsize-pixels-4); + if (ticksgameStartedAt+10000)&&(!bGameOver)) + { + int currentCounter = (ticks-(int)gameStartedAt)/1000; + if(currentCounter!=lastCounter) + { + if(currentCounter>115 && currentCounter<120) + Mix_PlayChannel(1,counterChunk,0); + } + lastCounter = currentCounter; + } + else + { + if( (0==lastCounter) && (SoundEnabled)&&(!NoSound)) + { + Mix_PlayChannel(1,counterFinalChunk,0); + } + lastCounter = -1; + } + } - if ((bGameOver)&&(!editorMode)) - if (hasWonTheGame)DrawIMG(iWinner, sBoard, 0, 5*bsize); - else if (bDraw) DrawIMG(iDraw, sBoard, 0, 5*bsize); - else - DrawIMG(iGameOver, sBoard, 0, 5*bsize); - nf_standard_blue_font.setDest(screen); - } + if ((bGameOver)&&(!editorMode)) + if (hasWonTheGame)DrawIMG(iWinner, sBoard, 0, 5*bsize); + else if (bDraw) DrawIMG(iDraw, sBoard, 0, 5*bsize); + else + DrawIMG(iGameOver, sBoard, 0, 5*bsize); + nf_standard_blue_font.setDest(screen); + } - void Update(int newtick) { - BlockGame::Update(newtick); - DoPaintJob(); - } + void Update(int newtick) + { + BlockGame::Update(newtick); + DoPaintJob(); + } }; @@ -1616,35 +1667,35 @@ public: //writeScreenShot saves the screen as a bmp file, it uses the time to get a unique filename void writeScreenShot() { - cout << "Saving screenshot" << endl; - int rightNow = (int)time(NULL); -/*#if defined(__unix__) - char buf[514]; - sprintf( buf, "%s/.gamesaves/blockattack/screenshots/screenshot%i.bmp", getenv("HOME"), rightNow ); -#elif defined(__win32__) - char buf[MAX_PATH]; - sprintf( buf, "%s\\My Games\\blockattack\\screenshots\\screenshot%i.bmp", (getMyDocumentsPath()).c_str(), rightNow ); -#else - char buf[MAX_PATH]; - sprintf( buf, "screenshot%i.bmp", rightNow ); -#endif*/ + cout << "Saving screenshot" << endl; + int rightNow = (int)time(NULL); + /*#if defined(__unix__) + char buf[514]; + sprintf( buf, "%s/.gamesaves/blockattack/screenshots/screenshot%i.bmp", getenv("HOME"), rightNow ); + #elif defined(__win32__) + char buf[MAX_PATH]; + sprintf( buf, "%s\\My Games\\blockattack\\screenshots\\screenshot%i.bmp", (getMyDocumentsPath()).c_str(), rightNow ); + #else + char buf[MAX_PATH]; + sprintf( buf, "screenshot%i.bmp", rightNow ); + #endif*/ #if defined(__unix__) - string buf = (string)getenv("HOME")+"/.gamesaves/blockattack/screenshots/screenshot"+itoa(rightNow)+".bmp"; + string buf = (string)getenv("HOME")+"/.gamesaves/blockattack/screenshots/screenshot"+itoa(rightNow)+".bmp"; #elif defined(__win32__) - string buf = getMyDocumentsPath()+"\\My Games\\blockattack\\screenshots\\screenshot"+itoa(rightNow)+".bmp"; + string buf = getMyDocumentsPath()+"\\My Games\\blockattack\\screenshots\\screenshot"+itoa(rightNow)+".bmp"; #else - string buf = "screenshot"+itoa(rightNow)+".bmp"; + string buf = "screenshot"+itoa(rightNow)+".bmp"; #endif - SDL_SaveBMP( screen, buf.c_str() ); - if (!NoSound) - if (SoundEnabled)Mix_PlayChannel(1,photoClick,0); + SDL_SaveBMP( screen, buf.c_str() ); + if (!NoSound) + if (SoundEnabled)Mix_PlayChannel(1,photoClick,0); } //Function to return the name of a key, to be displayed... static string getKeyName(SDLKey key) { - string keyname(SDL_GetKeyName(key)); - return keyname; + string keyname(SDL_GetKeyName(key)); + return keyname; } void MakeBackground(int xsize,int ysize,BlockGame &theGame, BlockGame &theGame2); @@ -1853,297 +1904,303 @@ void MakeBackground(int xsize,int ysize,BlockGame &theGame, BlockGame &theGame2) //Dialogbox bool OpenDialogbox(int x, int y, char *name) { - bool done = false; //We are done! - bool accept = false; //New name is accepted! (not Cancelled) - bool repeating = false; //The key is being held (BACKSPACE) - const int repeatDelay = 200; //Repeating - unsigned long time = 0; - ReadKeyboard rk = ReadKeyboard(name); - Uint8* keys; - string strHolder; - MakeBackground(xsize,ysize); - DrawIMG(background,screen,0,0); - while (!done && !Config::getInstance()->isShuttingDown()) - { - DrawIMG(dialogBox,screen,x,y); - NFont_Write(screen, x+40,y+76,rk.GetString()); - strHolder = rk.GetString(); - strHolder.erase((int)rk.CharsBeforeCursor()); + bool done = false; //We are done! + bool accept = false; //New name is accepted! (not Cancelled) + bool repeating = false; //The key is being held (BACKSPACE) + const int repeatDelay = 200; //Repeating + unsigned long time = 0; + ReadKeyboard rk = ReadKeyboard(name); + Uint8* keys; + string strHolder; + MakeBackground(xsize,ysize); + DrawIMG(background,screen,0,0); + while (!done && !Config::getInstance()->isShuttingDown()) + { + DrawIMG(dialogBox,screen,x,y); + NFont_Write(screen, x+40,y+76,rk.GetString()); + strHolder = rk.GetString(); + strHolder.erase((int)rk.CharsBeforeCursor()); + + if (((SDL_GetTicks()/600)%2)==1) + NFont_Write(screen, x+40+nf_standard_blue_font.getWidth( strHolder.c_str()),y+76,"|"); + + SDL_Event event; + + while ( SDL_PollEvent(&event) ) + { + if ( event.type == SDL_QUIT ) + { + Config::getInstance()->setShuttingDown(5); + done = true; + accept = false; + } + + if ( event.type == SDL_KEYDOWN ) + { + if ( (event.key.keysym.sym == SDLK_RETURN)||(event.key.keysym.sym == SDLK_KP_ENTER) ) + { + done = true; + accept = true; + } + else if ( (event.key.keysym.sym == SDLK_ESCAPE) ) + { + done = true; + accept = false; + } + else if (!(event.key.keysym.sym == SDLK_BACKSPACE)) + { + if ((rk.ReadKey(event.key.keysym.sym))&&(SoundEnabled)&&(!NoSound))Mix_PlayChannel(1,typingChunk,0); + } + else if ((event.key.keysym.sym == SDLK_BACKSPACE)&&(!repeating)) + { + if ((rk.ReadKey(event.key.keysym.sym))&&(SoundEnabled)&&(!NoSound))Mix_PlayChannel(1,typingChunk,0); + repeating = true; + time=SDL_GetTicks(); + } + } + + } //while(event) + + if (SDL_GetTicks()>(time+repeatDelay)) + { + time = SDL_GetTicks(); + keys = SDL_GetKeyState(NULL); + if ( (keys[SDLK_BACKSPACE])&&(repeating) ) + { + if ((rk.ReadKey(SDLK_BACKSPACE))&&(SoundEnabled)&&(!NoSound))Mix_PlayChannel(1,typingChunk,0); + } + else + repeating = false; + } - if (((SDL_GetTicks()/600)%2)==1) - NFont_Write(screen, x+40+nf_standard_blue_font.getWidth( strHolder.c_str()),y+76,"|"); + SDL_Flip(screen); //Update screen + } //while(!done) + strcpy(name,rk.GetString()); + bScreenLocked = false; + showDialog = false; + return accept; +} - SDL_Event event; +//Draws the highscores +void DrawHighscores(int x, int y, bool endless) +{ + MakeBackground(xsize,ysize); + DrawIMG(background,screen,0,0); + if (endless) nf_standard_blue_font.draw(x+100,y+100,_("Endless:") ); + else nf_standard_blue_font.draw(x+100,y+100,_("Time Trial:") ); + for (int i =0; i<10; i++) + { + char playerScore[32]; + char playerName[32]; + if (endless) + { + sprintf(playerScore, "%i", theTopScoresEndless.getScoreNumber(i)); + } + else + { + sprintf(playerScore, "%i", theTopScoresTimeTrial.getScoreNumber(i)); + } + if (endless) + { + strcpy(playerName,theTopScoresEndless.getScoreName(i)); + } + else + { + strcpy(playerName,theTopScoresTimeTrial.getScoreName(i)); + } + nf_standard_blue_font.draw(x+420,y+150+i*35,playerScore); + nf_standard_blue_font.draw(x+60,y+150+i*35,playerName); + } +} - while ( SDL_PollEvent(&event) ) - { - if ( event.type == SDL_QUIT ) { - Config::getInstance()->setShuttingDown(5); - done = true; - accept = false; - } - - if ( event.type == SDL_KEYDOWN ) - { - if ( (event.key.keysym.sym == SDLK_RETURN)||(event.key.keysym.sym == SDLK_KP_ENTER) ) { - done = true; - accept = true; - } - else - if ( (event.key.keysym.sym == SDLK_ESCAPE) ) { - done = true; - accept = false; - } - else if (!(event.key.keysym.sym == SDLK_BACKSPACE)){ - if ((rk.ReadKey(event.key.keysym.sym))&&(SoundEnabled)&&(!NoSound))Mix_PlayChannel(1,typingChunk,0); - } - else if ((event.key.keysym.sym == SDLK_BACKSPACE)&&(!repeating)){ - if ((rk.ReadKey(event.key.keysym.sym))&&(SoundEnabled)&&(!NoSound))Mix_PlayChannel(1,typingChunk,0); - repeating = true; - time=SDL_GetTicks(); - } - } - - } //while(event) - - if (SDL_GetTicks()>(time+repeatDelay)) - { - time = SDL_GetTicks(); - keys = SDL_GetKeyState(NULL); - if ( (keys[SDLK_BACKSPACE])&&(repeating) ) - { - if ((rk.ReadKey(SDLK_BACKSPACE))&&(SoundEnabled)&&(!NoSound))Mix_PlayChannel(1,typingChunk,0); - } - else - repeating = false; - } - - SDL_Flip(screen); //Update screen - } //while(!done) - strcpy(name,rk.GetString()); - bScreenLocked = false; - showDialog = false; - return accept; -} - -//Draws the highscores -void DrawHighscores(int x, int y, bool endless) -{ - MakeBackground(xsize,ysize); - DrawIMG(background,screen,0,0); - if (endless) nf_standard_blue_font.draw(x+100,y+100,_("Endless:") ); - else nf_standard_blue_font.draw(x+100,y+100,_("Time Trial:") ); - for (int i =0;i<10;i++) - { - char playerScore[32]; - char playerName[32]; - if (endless) - { - sprintf(playerScore, "%i", theTopScoresEndless.getScoreNumber(i)); - } - else - { - sprintf(playerScore, "%i", theTopScoresTimeTrial.getScoreNumber(i)); - } - if (endless) - { - strcpy(playerName,theTopScoresEndless.getScoreName(i)); - } - else - { - strcpy(playerName,theTopScoresTimeTrial.getScoreName(i)); - } - nf_standard_blue_font.draw(x+420,y+150+i*35,playerScore); - nf_standard_blue_font.draw(x+60,y+150+i*35,playerName); - } -} - -void DrawStats() -{ - MakeBackground(xsize,ysize); - DrawIMG(background,screen,0,0); - int y = 5; - const int y_spacing = 30; - NFont_Write(screen, 10,y,_("Stats") ); - y+=y_spacing*2; - NFont_Write(screen, 10,y,_("Chains") ); - for(int i=2;i<13;i++) - { - y+=y_spacing; - NFont_Write(screen, 10,y,(itoa(i)+"X").c_str()); - string numberAsString = itoa(Stats::getInstance()->getNumberOf("chainX"+itoa(i))); - NFont_Write(screen, 300,y,numberAsString.c_str()); - } - y+=y_spacing*2; - NFont_Write(screen, 10,y,_("Lines Pushed: ") ); - string numberAsString = itoa(Stats::getInstance()->getNumberOf("linesPushed")); - NFont_Write(screen, 300,y,numberAsString.c_str()); - - y+=y_spacing; - NFont_Write(screen, 10,y, _("Puzzles solved: ") ); - numberAsString = itoa(Stats::getInstance()->getNumberOf("puzzlesSolved")); - NFont_Write(screen, 300,y,numberAsString.c_str()); - - y+=y_spacing*2; - NFont_Write(screen, 10,y, _("Run time: ") ); - commonTime ct = TimeHandler::peekTime("totalTime",TimeHandler::ms2ct(SDL_GetTicks())); - y+=y_spacing; - NFont_Write(screen, 10,y,((string)( _("Days: ")+itoa(ct.days))).c_str()); - y+=y_spacing; - NFont_Write(screen, 10,y,((string)( _("Hours: ")+itoa(ct.hours))).c_str()); - y+=y_spacing; - NFont_Write(screen, 10,y,((string)( _("Minutes: ")+itoa(ct.minutes))).c_str()); - y+=y_spacing; - NFont_Write(screen, 10,y,((string)( _("Seconds: ")+itoa(ct.seconds))).c_str()); - - y-=y_spacing*4; //Four rows back - const int x_offset3 = xsize/3+10; //Ofset for three rows - NFont_Write(screen, x_offset3,y, _("Play time: ") ); - ct = TimeHandler::getTime("playTime"); - y+=y_spacing; - NFont_Write(screen, x_offset3,y,((string)( _("Days: ")+itoa(ct.days))).c_str()); - y+=y_spacing; - NFont_Write(screen, x_offset3,y,((string)( _("Hours: ")+itoa(ct.hours))).c_str()); - y+=y_spacing; - NFont_Write(screen, x_offset3,y,((string)( _("Minutes: ")+itoa(ct.minutes))).c_str()); - y+=y_spacing; - NFont_Write(screen, x_offset3,y,((string)( _("Seconds: ")+itoa(ct.seconds))).c_str()); - - const int x_offset = xsize/2+10; - y = 5+y_spacing*2; - NFont_Write(screen, x_offset,y, _("VS CPU (win/loss)") ); - for(int i=0;i<7;i++) - { - y += y_spacing; - NFont_Write(screen, x_offset,y,("AI "+itoa(i+1)).c_str()); - numberAsString = itoa(Stats::getInstance()->getNumberOf("defeatedAI"+itoa(i))); - string numberAsString2 = itoa(Stats::getInstance()->getNumberOf("defeatedByAI"+itoa(i))); - string toPrint = numberAsString + "/" + numberAsString2; - NFont_Write(screen, x_offset+230,y,toPrint.c_str()); - } -} +void DrawStats() +{ + MakeBackground(xsize,ysize); + DrawIMG(background,screen,0,0); + int y = 5; + const int y_spacing = 30; + NFont_Write(screen, 10,y,_("Stats") ); + y+=y_spacing*2; + NFont_Write(screen, 10,y,_("Chains") ); + for(int i=2; i<13; i++) + { + y+=y_spacing; + NFont_Write(screen, 10,y,(itoa(i)+"X").c_str()); + string numberAsString = itoa(Stats::getInstance()->getNumberOf("chainX"+itoa(i))); + NFont_Write(screen, 300,y,numberAsString.c_str()); + } + y+=y_spacing*2; + NFont_Write(screen, 10,y,_("Lines Pushed: ") ); + string numberAsString = itoa(Stats::getInstance()->getNumberOf("linesPushed")); + NFont_Write(screen, 300,y,numberAsString.c_str()); + + y+=y_spacing; + NFont_Write(screen, 10,y, _("Puzzles solved: ") ); + numberAsString = itoa(Stats::getInstance()->getNumberOf("puzzlesSolved")); + NFont_Write(screen, 300,y,numberAsString.c_str()); + + y+=y_spacing*2; + NFont_Write(screen, 10,y, _("Run time: ") ); + commonTime ct = TimeHandler::peekTime("totalTime",TimeHandler::ms2ct(SDL_GetTicks())); + y+=y_spacing; + NFont_Write(screen, 10,y,((string)( _("Days: ")+itoa(ct.days))).c_str()); + y+=y_spacing; + NFont_Write(screen, 10,y,((string)( _("Hours: ")+itoa(ct.hours))).c_str()); + y+=y_spacing; + NFont_Write(screen, 10,y,((string)( _("Minutes: ")+itoa(ct.minutes))).c_str()); + y+=y_spacing; + NFont_Write(screen, 10,y,((string)( _("Seconds: ")+itoa(ct.seconds))).c_str()); + + y-=y_spacing*4; //Four rows back + const int x_offset3 = xsize/3+10; //Ofset for three rows + NFont_Write(screen, x_offset3,y, _("Play time: ") ); + ct = TimeHandler::getTime("playTime"); + y+=y_spacing; + NFont_Write(screen, x_offset3,y,((string)( _("Days: ")+itoa(ct.days))).c_str()); + y+=y_spacing; + NFont_Write(screen, x_offset3,y,((string)( _("Hours: ")+itoa(ct.hours))).c_str()); + y+=y_spacing; + NFont_Write(screen, x_offset3,y,((string)( _("Minutes: ")+itoa(ct.minutes))).c_str()); + y+=y_spacing; + NFont_Write(screen, x_offset3,y,((string)( _("Seconds: ")+itoa(ct.seconds))).c_str()); + + const int x_offset = xsize/2+10; + y = 5+y_spacing*2; + NFont_Write(screen, x_offset,y, _("VS CPU (win/loss)") ); + for(int i=0; i<7; i++) + { + y += y_spacing; + NFont_Write(screen, x_offset,y,("AI "+itoa(i+1)).c_str()); + numberAsString = itoa(Stats::getInstance()->getNumberOf("defeatedAI"+itoa(i))); + string numberAsString2 = itoa(Stats::getInstance()->getNumberOf("defeatedByAI"+itoa(i))); + string toPrint = numberAsString + "/" + numberAsString2; + NFont_Write(screen, x_offset+230,y,toPrint.c_str()); + } +} void OpenScoresDisplay() { - int mousex,mousey; - bool done = false; //We are done! - int page = 0; - const int numberOfPages = 3; - //button coodinates: - const int scoreX = buttonXsize*2; - const int scoreY = 0; - const int backX = 20; - const int backY = ysize-buttonYsize-20; - const int nextX = xsize-buttonXsize-20; - const int nextY = backY; - while (!done && !Config::getInstance()->isShuttingDown()) - { - switch(page) - { - case 0: - //Highscores, endless - DrawHighscores(100,100,true); - break; - case 1: - //Highscores, Time Trial - DrawHighscores(100,100,false); - break; - case 2: - default: - DrawStats(); - }; - - //Draw buttons: - DrawIMG(bHighScore,screen,scoreX,scoreY); - DrawIMG(bBack,screen,backX,backY); - DrawIMG(bNext,screen,nextX,nextY); - - //Draw page number - string pageXofY = (format(_("Page %1% of %2%") )%(page+1)%numberOfPages).str(); - NFont_Write(screen, xsize/2-nf_standard_blue_font.getWidth( pageXofY.c_str())/2,ysize-60,pageXofY.c_str()); - - SDL_Delay(10); - SDL_Event event; - - SDL_GetMouseState(&mousex,&mousey); - - while ( SDL_PollEvent(&event) ) - { - - - if ( event.type == SDL_QUIT ) { - Config::getInstance()->setShuttingDown(5); - done = true; - } - - if ( event.type == SDL_KEYDOWN ) - { - if( (event.key.keysym.sym == SDLK_RIGHT)) - { - page++; - if(page>=numberOfPages) - page = 0; - } - else - if( (event.key.keysym.sym == SDLK_LEFT)) - { - page--; - if(page<0) - page = numberOfPages-1; - } - else - done = true; - - if ( event.key.keysym.sym == SDLK_F9 ) { - writeScreenShot(); - } - - if ( (event.key.keysym.sym == SDLK_RETURN)||(event.key.keysym.sym == SDLK_KP_ENTER) ) { - done = true; - } - else - if ( (event.key.keysym.sym == SDLK_ESCAPE) ) { - done = true; - } - } - - } //while(event) - - // If the mouse button is released, make bMouseUp equal true - if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) - { - bMouseUp=true; - } - - if (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp) - { - bMouseUp = false; - - //The Score button: - if((mousex>scoreX) && (mousexscoreY) && (mouseybackX) && (mousexbackY) && (mouseyisShuttingDown()) + { + switch(page) + { + case 0: + //Highscores, endless + DrawHighscores(100,100,true); + break; + case 1: + //Highscores, Time Trial + DrawHighscores(100,100,false); + break; + case 2: + default: + DrawStats(); + }; + + //Draw buttons: + DrawIMG(bHighScore,screen,scoreX,scoreY); + DrawIMG(bBack,screen,backX,backY); + DrawIMG(bNext,screen,nextX,nextY); + + //Draw page number + string pageXofY = (format(_("Page %1% of %2%") )%(page+1)%numberOfPages).str(); + NFont_Write(screen, xsize/2-nf_standard_blue_font.getWidth( pageXofY.c_str())/2,ysize-60,pageXofY.c_str()); + + SDL_Delay(10); + SDL_Event event; + + SDL_GetMouseState(&mousex,&mousey); + + while ( SDL_PollEvent(&event) ) + { + + + if ( event.type == SDL_QUIT ) + { + Config::getInstance()->setShuttingDown(5); + done = true; + } + + if ( event.type == SDL_KEYDOWN ) + { + if( (event.key.keysym.sym == SDLK_RIGHT)) + { + page++; + if(page>=numberOfPages) + page = 0; + } + else if( (event.key.keysym.sym == SDLK_LEFT)) + { + page--; + if(page<0) + page = numberOfPages-1; + } + else + done = true; + + if ( event.key.keysym.sym == SDLK_F9 ) + { + writeScreenShot(); + } + + if ( (event.key.keysym.sym == SDLK_RETURN)||(event.key.keysym.sym == SDLK_KP_ENTER) ) + { + done = true; + } + else if ( (event.key.keysym.sym == SDLK_ESCAPE) ) + { + done = true; + } + } + + } //while(event) + + // If the mouse button is released, make bMouseUp equal true + if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) + { + bMouseUp=true; + } - //The next button: - if((mousex>nextX) && (mousexnextY) && (mousey=numberOfPages) - page = 0; - } - } + if (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp) + { + bMouseUp = false; + + //The Score button: + if((mousex>scoreX) && (mousexscoreY) && (mouseybackX) && (mousexbackY) && (mouseynextX) && (mousexnextY) && (mousey=numberOfPages) + page = 0; + } + } - //DrawIMG(mouse,screen,mousex,mousey); - mouse.PaintTo(screen,mousex,mousey); - SDL_Flip(screen); //Update screen - } + //DrawIMG(mouse,screen,mousex,mousey); + mouse.PaintTo(screen,mousex,mousey); + SDL_Flip(screen); //Update screen + } } @@ -2152,1243 +2209,1284 @@ void OpenScoresDisplay() //Open a puzzle file bool OpenFileDialogbox(int x, int y, char *name) { - bool done = false; //We are done! - int mousex, mousey; - ListFiles lf = ListFiles(); - string folder = (string)SHAREDIR+(string)"/puzzles"; - cout << "Looking in " << folder << endl; - lf.setDirectory(folder.c_str()); + bool done = false; //We are done! + int mousex, mousey; + ListFiles lf = ListFiles(); + string folder = (string)SHAREDIR+(string)"/puzzles"; + cout << "Looking in " << folder << endl; + lf.setDirectory(folder.c_str()); #ifdef __unix__ - string homeFolder = (string)getenv("HOME")+(string)"/.gamesaves/blockattack/puzzles"; - lf.setDirectory2(homeFolder.c_str()); + string homeFolder = (string)getenv("HOME")+(string)"/.gamesaves/blockattack/puzzles"; + lf.setDirectory2(homeFolder.c_str()); #endif - Uint8* keys; - string strHolder; - MakeBackground(xsize,ysize); - DrawIMG(background,screen,0,0); - DrawIMG(bForward,background,x+460,y+420); - DrawIMG(bBack,background,x+20,y+420); - while (!done && !Config::getInstance()->isShuttingDown()) - { - DrawIMG(background,screen,0,0); - const int nrOfFiles = 10; - DrawIMG(changeButtonsBack,screen,x,y); - for (int i=0;isetShuttingDown(5); - done = true; - } - - if ( event.type == SDL_KEYDOWN ) - { - if ( (event.key.keysym.sym == SDLK_ESCAPE) ) { - done = true; - } - - if ( (event.key.keysym.sym == SDLK_RIGHT) ) { - lf.forward(); - } - - if ( (event.key.keysym.sym == SDLK_LEFT) ) { - lf.back(); - } - } - - } //while(event) - - SDL_GetMouseState(&mousex,&mousey); - - // If the mouse button is released, make bMouseUp equal true - if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) - { - bMouseUp=true; - } - - if (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp) - { - bMouseUp = false; - - //The Forward Button: - if ( (mousex>x+460) && (mousexy+420) && (mouseyisShuttingDown()) + { + DrawIMG(background,screen,0,0); + const int nrOfFiles = 10; + DrawIMG(changeButtonsBack,screen,x,y); + for (int i=0; ix+20) && (mousexy+420) && (mouseysetShuttingDown(5); + done = true; + } + + if ( event.type == SDL_KEYDOWN ) + { + if ( (event.key.keysym.sym == SDLK_ESCAPE) ) + { + done = true; + } + + if ( (event.key.keysym.sym == SDLK_RIGHT) ) + { + lf.forward(); + } + + if ( (event.key.keysym.sym == SDLK_LEFT) ) + { + lf.back(); + } + } + + } //while(event) + + SDL_GetMouseState(&mousex,&mousey); + + // If the mouse button is released, make bMouseUp equal true + if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) + { + bMouseUp=true; + } - for (int i=0;i<10;i++) - { - if ( (mousex>x+10) && (mousexy+10+i*36) && (mouseyx+460) && (mousexy+420) && (mouseyx+20) && (mousexy+420) && (mouseyx+10) && (mousexy+10+i*36) && (mouseyisShuttingDown()) - { - DrawIMG(background,screen,0,0); - const int nrOfFiles = 10; - DrawIMG(changeButtonsBack,screen,x,y); - for (int i=0;isetShuttingDown(5); - done = true; - } - - if ( event.type == SDL_KEYDOWN ) - { - if ( (event.key.keysym.sym == SDLK_ESCAPE) ) { - done = true; - } - - if ( (event.key.keysym.sym == SDLK_RIGHT) ) { - lf.forward(); - } - - if ( (event.key.keysym.sym == SDLK_LEFT) ) { - lf.back(); - } - } - - } //while(event) - - SDL_GetMouseState(&mousex,&mousey); - - // If the mouse button is released, make bMouseUp equal true - if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) - { - bMouseUp=true; - } - - if (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp) - { - bMouseUp = false; - - //The Forward Button: - if ( (mousex>x+460) && (mousexy+420) && (mouseyisShuttingDown()) + { + DrawIMG(background,screen,0,0); + const int nrOfFiles = 10; + DrawIMG(changeButtonsBack,screen,x,y); + for (int i=0; ix+20) && (mousexy+420) && (mouseysetShuttingDown(5); + done = true; + } + + if ( event.type == SDL_KEYDOWN ) + { + if ( (event.key.keysym.sym == SDLK_ESCAPE) ) + { + done = true; + } + + if ( (event.key.keysym.sym == SDLK_RIGHT) ) + { + lf.forward(); + } + + if ( (event.key.keysym.sym == SDLK_LEFT) ) + { + lf.back(); + } + } + + } //while(event) + + SDL_GetMouseState(&mousex,&mousey); + + // If the mouse button is released, make bMouseUp equal true + if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) + { + bMouseUp=true; + } - for (int i=0;i<10;i++) - { - if ( (mousex>x+10) && (mousexy+10+i*36) && (mouseyx+460) && (mousexy+420) && (mouseyx+20) && (mousexy+420) && (mouseyx+10) && (mousexy+10+i*36) && (mouseyisShuttingDown()) - { - DrawIMG(background,screen,0,0); - const int nrOfFiles = 10; - DrawIMG(changeButtonsBack,screen,x,y); - for (int i=0;isetShuttingDown(5); - done = true; - return false; - } - - if ( event.type == SDL_KEYDOWN ) - { - if ( (event.key.keysym.sym == SDLK_ESCAPE) ) { - done = true; - return false; - } - - if ( (event.key.keysym.sym == SDLK_RIGHT) ) { - lf.forward(); - } - - if ( (event.key.keysym.sym == SDLK_LEFT) ) { - lf.back(); - } - } - - } //while(event) - - SDL_GetMouseState(&mousex,&mousey); - - // If the mouse button is released, make bMouseUp equal true - if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) - { - bMouseUp=true; - } - - if (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp) - { - bMouseUp = false; - - //The Forward Button: - if ( (mousex>x+460) && (mousexy+420) && (mouseyisShuttingDown()) + { + DrawIMG(background,screen,0,0); + const int nrOfFiles = 10; + DrawIMG(changeButtonsBack,screen,x,y); + for (int i=0; ix+20) && (mousexy+420) && (mouseysetShuttingDown(5); + done = true; + return false; + } + + if ( event.type == SDL_KEYDOWN ) + { + if ( (event.key.keysym.sym == SDLK_ESCAPE) ) + { + done = true; + return false; + } + + if ( (event.key.keysym.sym == SDLK_RIGHT) ) + { + lf.forward(); + } + + if ( (event.key.keysym.sym == SDLK_LEFT) ) + { + lf.back(); + } + } + + } //while(event) + + SDL_GetMouseState(&mousex,&mousey); + + // If the mouse button is released, make bMouseUp equal true + if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) + { + bMouseUp=true; + } - for (int i=0;i<10;i++) - { - if ( (mousex>x+10) && (mousexy+10+i*36) && (mouseyx+460) && (mousexy+420) && (mouseyx+20) && (mousexy+420) && (mouseyx+10) && (mousexy+10+i*36) && (mouseyGetTopX()-60,theGame->GetTopY()-68); - DrawIMG(theGame->sBoard,screen,theGame->GetTopX(),theGame->GetTopY()); - string strHolder; - strHolder = itoa(theGame->GetScore()+theGame->GetHandicap()); - NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+100,strHolder.c_str()); - if (theGame->GetAIenabled()) - NFont_Write(screen, theGame->GetTopX()+10,theGame->GetTopY()-34,_("AI") ); - else - if (editorMode) - NFont_Write(screen, theGame->GetTopX()+10,theGame->GetTopY()-34,_("Playing field") ); - else - if (!singlePuzzle) - NFont_Write(screen, theGame->GetTopX()+10,theGame->GetTopY()-34,player1name); - if (theGame->isTimeTrial()) - { - int tid = (int)SDL_GetTicks()-theGame->GetGameStartedAt(); - int minutes; - int seconds; - if (tid>=0) - { - minutes = (2*60*1000-(abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))/60/1000; - seconds = ((2*60*1000-(abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))%(60*1000))/1000; - } - else - { - minutes = ((abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))/60/1000; - seconds = (((abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))%(60*1000))/1000; - } - if (theGame->isGameOver()) minutes=0; - if (theGame->isGameOver()) seconds=0; - if (seconds>9) - strHolder = itoa(minutes)+":"+itoa(seconds); - else strHolder = itoa(minutes)+":0"+itoa(seconds); - //if ((SoundEnabled)&&(!NoSound)&&(tid>0)&&(seconds<5)&&(minutes == 0)&&(seconds>1)&&(!(Mix_Playing(6)))) Mix_PlayChannel(6,heartBeat,0); - NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+150,strHolder.c_str()); - } - else - { - int minutes = ((abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))/60/1000; - int seconds = (((abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))%(60*1000))/1000; - if (theGame->isGameOver()) minutes=(theGame->GetGameEndedAt()/1000/60)%100; - if (theGame->isGameOver()) seconds=(theGame->GetGameEndedAt()/1000)%60; - if (seconds>9) - strHolder = itoa(minutes)+":"+itoa(seconds); - else - strHolder = itoa(minutes)+":0"+itoa(seconds); - NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+150,strHolder.c_str()); - } - strHolder = itoa(theGame->GetChains()); - NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+200,strHolder.c_str()); - //drawspeedLevel: - strHolder = itoa(theGame->GetSpeedLevel()); - NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+250,strHolder.c_str()); - if ((theGame->isStageClear()) &&(theGame->GetTopY()+700+50*(theGame->GetStageClearLimit()-theGame->GetLinesCleared())-theGame->GetPixels()-1<600+theGame->GetTopY())) - { - oldBubleX = theGame->GetTopX()+280; - oldBubleY = theGame->GetTopY()+650+50*(theGame->GetStageClearLimit()-theGame->GetLinesCleared())-theGame->GetPixels()-1; - DrawIMG(stageBobble,screen,theGame->GetTopX()+280,theGame->GetTopY()+650+50*(theGame->GetStageClearLimit()-theGame->GetLinesCleared())-theGame->GetPixels()-1); - } - //player1 finnish, player2 start - //DrawIMG(boardBackBack,screen,theGame2->GetTopX()-60,theGame2->GetTopY()-68); - if (!editorMode) - { - /* - *If single player mode (and not VS) - */ - if(!twoPlayers && !theGame->isGameOver()) - { - //Blank player2's board: - DrawIMG(backBoard,screen,theGame2->GetTopX(),theGame2->GetTopY()); - //Write a description: - if(theGame->isTimeTrial()) - { - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+10,"Time Trial"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160,"Objective:"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32, "Score as much"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28, "as possible in"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*2,"2 minutes"); - } else if(theGame->isStageClear()) - { - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+10,"Stage Clear"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160,"Objective:"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32, "You must clear a"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28, "number of lines."); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*2,"Speed is rapidly"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*3,"increased."); - } else if(theGame->isPuzzleMode()) - { - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+10,"Puzzle"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160,"Objective:"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32, "Clear the entire"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28, "board with a"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*2,"limited number of"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*3,"moves."); - } else - { - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+10,"Endless"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160,"Objective:"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32, "Score as much as"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28, "possible. No time"); - NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*2,"limit."); - } - - //Write the keys that are in use - int y = theGame2->GetTopY()+400; - NFont_Write(screen, theGame2->GetTopX()+7,y,_("Movement keys:") ); - NFont_Write(screen, theGame2->GetTopX()+7,y+40,(getKeyName(keySettings[0].left)+", "+getKeyName(keySettings[0].right)+"," ).c_str() ); - NFont_Write(screen, theGame2->GetTopX()+7,y+76,(getKeyName(keySettings[0].up)+", "+getKeyName(keySettings[0].down)).c_str() ); - NFont_Write(screen, theGame2->GetTopX()+7,y+120,( _("Switch: ")+getKeyName(keySettings[0].change) ).c_str() ); - if(theGame->isPuzzleMode()) - NFont_Write(screen, theGame2->GetTopX()+7,y+160,( _("Restart: ")+getKeyName(keySettings[0].push) ).c_str() ); - else - NFont_Write(screen, theGame2->GetTopX()+7,y+160,( _("Push line: ")+getKeyName(keySettings[0].push) ).c_str() ); - } - else - DrawIMG(theGame2->sBoard,screen,theGame2->GetTopX(),theGame2->GetTopY()); - strHolder = itoa(theGame2->GetScore()+theGame2->GetHandicap()); - NFont_Write(screen, theGame2->GetTopX()+310,theGame2->GetTopY()+100,strHolder.c_str()); - if (theGame2->GetAIenabled()) - NFont_Write(screen, theGame2->GetTopX()+10,theGame2->GetTopY()-34,_("AI") ); - else - NFont_Write(screen, theGame2->GetTopX()+10,theGame2->GetTopY()-34,theGame2->name); - if (theGame2->isTimeTrial()) - { - int tid = (int)SDL_GetTicks()-theGame2->GetGameStartedAt(); - int minutes; - int seconds; - if (tid>=0) - { - minutes = (2*60*1000-(abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())))/60/1000; - seconds = ((2*60*1000-(abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())))%(60*1000))/1000; - } - else - { - minutes = ((abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())))/60/1000; - seconds = (((abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())))%(60*1000))/1000; - } - if (theGame2->isGameOver()) minutes=0; - if (theGame2->isGameOver()) seconds=0; - if (seconds>9) - strHolder = itoa(minutes)+":"+itoa(seconds); - else - strHolder = itoa(minutes)+":0"+itoa(seconds); - //if ((SoundEnabled)&&(!NoSound)&&(tid>0)&&(seconds<5)&&(minutes == 0)&&(seconds>1)&&(!(Mix_Playing(6)))) Mix_PlayChannel(6,heartBeat,0); - NFont_Write(screen, theGame2->GetTopX()+310,theGame2->GetTopY()+150,strHolder.c_str()); - } - else - { - int minutes = (abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt()))/60/1000; - int seconds = (abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())%(60*1000))/1000; - if (theGame2->isGameOver()) minutes=(theGame2->GetGameEndedAt()/1000/60)%100; - if (theGame2->isGameOver()) seconds=(theGame2->GetGameEndedAt()/1000)%60; - if (seconds>9) - strHolder = itoa(minutes)+":"+itoa(seconds); - else - strHolder = itoa(minutes)+":0"+itoa(seconds); - NFont_Write(screen, theGame2->GetTopX()+310,theGame2->GetTopY()+150,strHolder.c_str()); - } - strHolder = itoa(theGame2->GetChains()); - NFont_Write(screen, theGame2->GetTopX()+310,theGame2->GetTopY()+200,strHolder.c_str()); - strHolder = itoa(theGame2->GetSpeedLevel()); - NFont_Write(screen, theGame2->GetTopX()+310,theGame2->GetTopY()+250,strHolder.c_str()); - } - //player2 finnish + SDL_ShowCursor(SDL_DISABLE); + //draw background: + if (forceredraw != 1) + { + + UndrawBalls(); + DrawIMG(background,screen,oldMousex,oldMousey,32,32,oldMousex,oldMousey); + DrawIMG(background,screen,oldBubleX,oldBubleY,140,50,oldBubleX,oldBubleY); + + + DrawIMG(background,screen,350,200,120,200,350,200); + DrawIMG(background,screen,830,200,120,200,830,200); + DrawIMG(background,screen,800,0,140,50,800,0); + + DrawIMG(background,screen,50,60,300,50,50,60); + DrawIMG(background,screen,510,60,300,50,510,60); + } + else + DrawIMG(background,screen,0,0); + //draw bottons (should be moves and drawn directly to background once) + /*if (!editorMode) + #if NETWORK + if (!networkActive) //We don't show the menu while running server or connected to a server + #else + if(true) + #endif + { + //Here we draw the menu + bNewGame.PaintTo(screen,0,0); + DrawIMG(bOptions, screen, buttonXsize,0); + DrawIMG(bHighScore, screen, 2*buttonXsize,0); + DrawIMG(bReplay,screen,3*buttonXsize,0); + } + else + { //If network is active + DrawIMG(bBack, screen, 0, 0); //Display a disconnect button + } + if (!editorMode) + DrawIMG(bExit, screen, xsize-120,ysize-120);*/ + //DrawIMG(boardBackBack,screen,theGame->GetTopX()-60,theGame->GetTopY()-68); + DrawIMG(theGame->sBoard,screen,theGame->GetTopX(),theGame->GetTopY()); + string strHolder; + strHolder = itoa(theGame->GetScore()+theGame->GetHandicap()); + NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+100,strHolder.c_str()); + if (theGame->GetAIenabled()) + NFont_Write(screen, theGame->GetTopX()+10,theGame->GetTopY()-34,_("AI") ); + else if (editorMode) + NFont_Write(screen, theGame->GetTopX()+10,theGame->GetTopY()-34,_("Playing field") ); + else if (!singlePuzzle) + NFont_Write(screen, theGame->GetTopX()+10,theGame->GetTopY()-34,player1name); + if (theGame->isTimeTrial()) + { + int tid = (int)SDL_GetTicks()-theGame->GetGameStartedAt(); + int minutes; + int seconds; + if (tid>=0) + { + minutes = (2*60*1000-(abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))/60/1000; + seconds = ((2*60*1000-(abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))%(60*1000))/1000; + } + else + { + minutes = ((abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))/60/1000; + seconds = (((abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))%(60*1000))/1000; + } + if (theGame->isGameOver()) minutes=0; + if (theGame->isGameOver()) seconds=0; + if (seconds>9) + strHolder = itoa(minutes)+":"+itoa(seconds); + else strHolder = itoa(minutes)+":0"+itoa(seconds); + //if ((SoundEnabled)&&(!NoSound)&&(tid>0)&&(seconds<5)&&(minutes == 0)&&(seconds>1)&&(!(Mix_Playing(6)))) Mix_PlayChannel(6,heartBeat,0); + NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+150,strHolder.c_str()); + } + else + { + int minutes = ((abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))/60/1000; + int seconds = (((abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))%(60*1000))/1000; + if (theGame->isGameOver()) minutes=(theGame->GetGameEndedAt()/1000/60)%100; + if (theGame->isGameOver()) seconds=(theGame->GetGameEndedAt()/1000)%60; + if (seconds>9) + strHolder = itoa(minutes)+":"+itoa(seconds); + else + strHolder = itoa(minutes)+":0"+itoa(seconds); + NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+150,strHolder.c_str()); + } + strHolder = itoa(theGame->GetChains()); + NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+200,strHolder.c_str()); + //drawspeedLevel: + strHolder = itoa(theGame->GetSpeedLevel()); + NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+250,strHolder.c_str()); + if ((theGame->isStageClear()) &&(theGame->GetTopY()+700+50*(theGame->GetStageClearLimit()-theGame->GetLinesCleared())-theGame->GetPixels()-1<600+theGame->GetTopY())) + { + oldBubleX = theGame->GetTopX()+280; + oldBubleY = theGame->GetTopY()+650+50*(theGame->GetStageClearLimit()-theGame->GetLinesCleared())-theGame->GetPixels()-1; + DrawIMG(stageBobble,screen,theGame->GetTopX()+280,theGame->GetTopY()+650+50*(theGame->GetStageClearLimit()-theGame->GetLinesCleared())-theGame->GetPixels()-1); + } + //player1 finnish, player2 start + //DrawIMG(boardBackBack,screen,theGame2->GetTopX()-60,theGame2->GetTopY()-68); + if (!editorMode) + { + /* + *If single player mode (and not VS) + */ + if(!twoPlayers && !theGame->isGameOver()) + { + //Blank player2's board: + DrawIMG(backBoard,screen,theGame2->GetTopX(),theGame2->GetTopY()); + //Write a description: + if(theGame->isTimeTrial()) + { + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+10,"Time Trial"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160,"Objective:"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32, "Score as much"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28, "as possible in"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*2,"2 minutes"); + } + else if(theGame->isStageClear()) + { + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+10,"Stage Clear"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160,"Objective:"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32, "You must clear a"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28, "number of lines."); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*2,"Speed is rapidly"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*3,"increased."); + } + else if(theGame->isPuzzleMode()) + { + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+10,"Puzzle"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160,"Objective:"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32, "Clear the entire"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28, "board with a"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*2,"limited number of"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*3,"moves."); + } + else + { + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+10,"Endless"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160,"Objective:"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32, "Score as much as"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28, "possible. No time"); + NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32+28*2,"limit."); + } + + //Write the keys that are in use + int y = theGame2->GetTopY()+400; + NFont_Write(screen, theGame2->GetTopX()+7,y,_("Movement keys:") ); + NFont_Write(screen, theGame2->GetTopX()+7,y+40,(getKeyName(keySettings[0].left)+", "+getKeyName(keySettings[0].right)+"," ).c_str() ); + NFont_Write(screen, theGame2->GetTopX()+7,y+76,(getKeyName(keySettings[0].up)+", "+getKeyName(keySettings[0].down)).c_str() ); + NFont_Write(screen, theGame2->GetTopX()+7,y+120,( _("Switch: ")+getKeyName(keySettings[0].change) ).c_str() ); + if(theGame->isPuzzleMode()) + NFont_Write(screen, theGame2->GetTopX()+7,y+160,( _("Restart: ")+getKeyName(keySettings[0].push) ).c_str() ); + else + NFont_Write(screen, theGame2->GetTopX()+7,y+160,( _("Push line: ")+getKeyName(keySettings[0].push) ).c_str() ); + } + else + DrawIMG(theGame2->sBoard,screen,theGame2->GetTopX(),theGame2->GetTopY()); + strHolder = itoa(theGame2->GetScore()+theGame2->GetHandicap()); + NFont_Write(screen, theGame2->GetTopX()+310,theGame2->GetTopY()+100,strHolder.c_str()); + if (theGame2->GetAIenabled()) + NFont_Write(screen, theGame2->GetTopX()+10,theGame2->GetTopY()-34,_("AI") ); + else + NFont_Write(screen, theGame2->GetTopX()+10,theGame2->GetTopY()-34,theGame2->name); + if (theGame2->isTimeTrial()) + { + int tid = (int)SDL_GetTicks()-theGame2->GetGameStartedAt(); + int minutes; + int seconds; + if (tid>=0) + { + minutes = (2*60*1000-(abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())))/60/1000; + seconds = ((2*60*1000-(abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())))%(60*1000))/1000; + } + else + { + minutes = ((abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())))/60/1000; + seconds = (((abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())))%(60*1000))/1000; + } + if (theGame2->isGameOver()) minutes=0; + if (theGame2->isGameOver()) seconds=0; + if (seconds>9) + strHolder = itoa(minutes)+":"+itoa(seconds); + else + strHolder = itoa(minutes)+":0"+itoa(seconds); + //if ((SoundEnabled)&&(!NoSound)&&(tid>0)&&(seconds<5)&&(minutes == 0)&&(seconds>1)&&(!(Mix_Playing(6)))) Mix_PlayChannel(6,heartBeat,0); + NFont_Write(screen, theGame2->GetTopX()+310,theGame2->GetTopY()+150,strHolder.c_str()); + } + else + { + int minutes = (abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt()))/60/1000; + int seconds = (abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())%(60*1000))/1000; + if (theGame2->isGameOver()) minutes=(theGame2->GetGameEndedAt()/1000/60)%100; + if (theGame2->isGameOver()) seconds=(theGame2->GetGameEndedAt()/1000)%60; + if (seconds>9) + strHolder = itoa(minutes)+":"+itoa(seconds); + else + strHolder = itoa(minutes)+":0"+itoa(seconds); + NFont_Write(screen, theGame2->GetTopX()+310,theGame2->GetTopY()+150,strHolder.c_str()); + } + strHolder = itoa(theGame2->GetChains()); + NFont_Write(screen, theGame2->GetTopX()+310,theGame2->GetTopY()+200,strHolder.c_str()); + strHolder = itoa(theGame2->GetSpeedLevel()); + NFont_Write(screen, theGame2->GetTopX()+310,theGame2->GetTopY()+250,strHolder.c_str()); + } + //player2 finnish - DrawBalls(); + DrawBalls(); #if DEBUG - Frames++; - if (SDL_GetTicks() >= Ticks + 1000) - { - if (Frames > 999) Frames=999; - sprintf(FPS, "%lu fps", Frames); - Frames = 0; - Ticks = SDL_GetTicks(); - } - - //NFont_Write(screen, 800,4,FPS); - nf_standard_blue_font.draw(800,4,FPS); + Frames++; + if (SDL_GetTicks() >= Ticks + 1000) + { + if (Frames > 999) Frames=999; + sprintf(FPS, "%lu fps", Frames); + Frames = 0; + Ticks = SDL_GetTicks(); + } + + //NFont_Write(screen, 800,4,FPS); + nf_standard_blue_font.draw(800,4,FPS); #endif - //SDL_Flip(screen); Update screen is now called outside DrawEvrything, bacause the mouse needs to be painted + //SDL_Flip(screen); Update screen is now called outside DrawEvrything, bacause the mouse needs to be painted } //Generates the standard background static void MakeBackground(int xsize,int ysize) { - int w = backgroundImage->w; - int h = backgroundImage->h; - for(int i=0;i*ww; + int h = backgroundImage->h; + for(int i=0; i*wGetTopX()-60,theGame->GetTopY()-68); - DrawIMG(boardBackBack,background,theGame2->GetTopX()-60,theGame2->GetTopY()-68); - standardBackground = false; + MakeBackground(xsize,ysize); + DrawIMG(boardBackBack,background,theGame->GetTopX()-60,theGame->GetTopY()-68); + DrawIMG(boardBackBack,background,theGame2->GetTopX()-60,theGame2->GetTopY()-68); + standardBackground = false; } static void MakeBackground(int xsize, int ysize, BlockGame *theGame) { - MakeBackground(xsize,ysize); - DrawIMG(boardBackBack,background,theGame->GetTopX()-60,theGame->GetTopY()-68); - standardBackground = false; + MakeBackground(xsize,ysize); + DrawIMG(boardBackBack,background,theGame->GetTopX()-60,theGame->GetTopY()-68); + standardBackground = false; } //The function that allows the player to choose PuzzleLevel int PuzzleLevelSelect() { - const int xplace = 200; - const int yplace = 300; - Uint8 *keys; - int levelNr, mousex, mousey, oldmousex, oldmousey; - bool levelSelected = false; - bool tempBool; + const int xplace = 200; + const int yplace = 300; + Uint8 *keys; + int levelNr, mousex, mousey, oldmousex, oldmousey; + bool levelSelected = false; + bool tempBool; int selected = 0; - //Loads the levels, if they havn't been loaded: - LoadPuzzleStages(); - - //Keeps track of background; - int nowTime=SDL_GetTicks(); - - ifstream puzzleFile(puzzleSavePath.c_str(),ios::binary); - MakeBackground(xsize,ysize); - if (puzzleFile) - { - for (int i=0;(i(&tempBool),sizeof(bool)); - puzzleCleared[i] = tempBool; - } - puzzleFile.close(); - } - else - { - tempBool = false; - for (int i=0; i= nrOfPuzzles) - selected = 0; - cout << "Selected: "<< selected << endl; - } - if ( event.key.keysym.sym == SDLK_LEFT ) { - --selected; - if(selected < 0) - selected = nrOfPuzzles; - cout << "Selected: "<< selected << endl; + ifstream puzzleFile(puzzleSavePath.c_str(),ios::binary); + MakeBackground(xsize,ysize); + if (puzzleFile) + { + for (int i=0; (i(&tempBool),sizeof(bool)); + puzzleCleared[i] = tempBool; } - if ( event.key.keysym.sym == SDLK_DOWN ) { - selected+=10; - if(selected >= nrOfPuzzles) - selected-=10; - cout << "Selected: "<< selected << endl; + puzzleFile.close(); + } + else + { + tempBool = false; + for (int i=0; i= nrOfPuzzles) + selected = 0; + cout << "Selected: "<< selected << endl; + } + if ( event.key.keysym.sym == SDLK_LEFT ) + { + --selected; + if(selected < 0) + selected = nrOfPuzzles; + cout << "Selected: "<< selected << endl; + } + if ( event.key.keysym.sym == SDLK_DOWN ) + { + selected+=10; + if(selected >= nrOfPuzzles) + selected-=10; + cout << "Selected: "<< selected << endl; + } + if ( event.key.keysym.sym == SDLK_UP ) + { + selected-=10; + if(selected < 0) + selected+=10; + cout << "Selected: "<< selected << endl; + } + } + + keys = SDL_GetKeyState(NULL); + + SDL_GetMouseState(&mousex,&mousey); + if(mousex != oldmousex || mousey != oldmousey) + { int tmpSelected = -1; int j; for (j = 0; (j(&tempBool),sizeof(bool)); - stageCleared[i]=tempBool; - } - if(!stageFile.eof()) - { - for(int i=0; i(&tempUInt32),sizeof(Uint32)); - stageScores[i]=tempUInt32; - totalScore+=tempUInt32; - } - for(int i=0; i(&tempUInt32),sizeof(Uint32)); - stageTimes[i]=tempUInt32; - totalTime += tempUInt32; - } - } - else - { - for(int i=0; i0) - scoreString = _("Best score: ")+itoa(stageScores[overLevel]); - if(stageTimes[overLevel]>0) - timeString = _("Time used: ")+itoa(stageTimes[overLevel]/1000/60)+" : "+itoa2((stageTimes[overLevel]/1000)%60); - - NFont_Write(screen, 200,200,scoreString.c_str()); - NFont_Write(screen, 200,250,timeString.c_str()); - - overLevel; - } - string totalString = (format("Total score: %1% in %2%:%3%")%totalScore%(totalTime/1000/60)%((totalTime/1000)%60)).str(); //"Total score: " +itoa(totalScore) + " in " + itoa(totalTime/1000/60) + " : " + itoa2((totalTime/1000)%60); - NFont_Write(screen, 200,600,totalString.c_str()); + const int xplace = 200; + const int yplace = 300; + Uint8 *keys; + int levelNr, mousex, mousey; + bool levelSelected = false; + bool tempBool; + Uint32 tempUInt32; + Uint32 totalScore = 0; + Uint32 totalTime = 0; + + //Keeps track of background; + //int nowTime=SDL_GetTicks(); + + MakeBackground(xsize,ysize); + ifstream stageFile(stageClearSavePath.c_str(),ios::binary); + if (stageFile) + { + for (int i = 0; i(&tempBool),sizeof(bool)); + stageCleared[i]=tempBool; + } + if(!stageFile.eof()) + { + for(int i=0; i(&tempUInt32),sizeof(Uint32)); + stageScores[i]=tempUInt32; + totalScore+=tempUInt32; + } + for(int i=0; i(&tempUInt32),sizeof(Uint32)); + stageTimes[i]=tempUInt32; + totalTime += tempUInt32; + } + } + else + { + for(int i=0; i0) + scoreString = _("Best score: ")+itoa(stageScores[overLevel]); + if(stageTimes[overLevel]>0) + timeString = _("Time used: ")+itoa(stageTimes[overLevel]/1000/60)+" : "+itoa2((stageTimes[overLevel]/1000)%60); + + NFont_Write(screen, 200,200,scoreString.c_str()); + NFont_Write(screen, 200,250,timeString.c_str()); + + overLevel; + } + string totalString = (format("Total score: %1% in %2%:%3%")%totalScore%(totalTime/1000/60)%((totalTime/1000)%60)).str(); //"Total score: " +itoa(totalScore) + " in " + itoa(totalTime/1000/60) + " : " + itoa2((totalTime/1000)%60); + NFont_Write(screen, 200,600,totalString.c_str()); + + //DrawIMG(mouse,screen,mousex,mousey); + mouse.PaintTo(screen,mousex,mousey); + SDL_Flip(screen); //draws it all to the screen + + } + while (!levelSelected); + DrawIMG(background, screen, 0, 0); + return levelNr; } //Ask user for what AI level he will compete agains, return the number. Number must be 0..AIlevels int startSingleVs() { - //Where to place the windows - const int xplace = 200; - const int yplace = 100; - Uint8 *keys; //To take keyboard input - int mousex, mousey; //To allow mouse - bool done = false; //When are we done? - - MakeBackground(xsize,ysize); - DrawIMG(changeButtonsBack,background,xplace,yplace); - NFont_Write(background, xplace+10,yplace+10,_("1 : Very Easy") ); - NFont_Write(background, xplace+10,yplace+40,_("2 : Easy") ); - NFont_Write(background, xplace+10,yplace+70,_("3 : Below Normal") ); - NFont_Write(background, xplace+10,yplace+100,_("4 : Normal") ); - NFont_Write(background, xplace+10,yplace+130,_("5 : Above Normal") ); - NFont_Write(background, xplace+10,yplace+160,_("6 : Hard") ); - NFont_Write(background, xplace+10,yplace+190,_("7 : Hardest") ); - DrawIMG(background, screen, 0, 0); - SDL_Flip(screen); - do - { - - SDL_Delay(10); - SDL_Event event; - while ( SDL_PollEvent(&event) ) - if ( event.type == SDL_KEYDOWN ) - { - if ( event.key.keysym.sym == SDLK_KP_ENTER || event.key.keysym.sym == SDLK_ESCAPE || event.key.keysym.sym == SDLK_RETURN ) { - done = true; - } - if ( event.key.keysym.sym == SDLK_1 || event.key.keysym.sym == SDLK_KP1 ) { - return 0; - } - if ( event.key.keysym.sym == SDLK_2 || event.key.keysym.sym == SDLK_KP2 ) { - return 1; - } - if ( event.key.keysym.sym == SDLK_3 || event.key.keysym.sym == SDLK_KP3 ) { - return 2; - } - if ( event.key.keysym.sym == SDLK_4 || event.key.keysym.sym == SDLK_KP4 ) { - return 3; - } - if ( event.key.keysym.sym == SDLK_5 || event.key.keysym.sym == SDLK_KP5 ) { - return 4; - } - if ( event.key.keysym.sym == SDLK_6 || event.key.keysym.sym == SDLK_KP6 ) { - return 5; - } - if ( event.key.keysym.sym == SDLK_7 || event.key.keysym.sym == SDLK_KP7 ) { - return 6; - } - } - - // If the mouse button is released, make bMouseUp equal true - if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) - { - bMouseUp=true; - } + //Where to place the windows + const int xplace = 200; + const int yplace = 100; + Uint8 *keys; //To take keyboard input + int mousex, mousey; //To allow mouse + bool done = false; //When are we done? + + MakeBackground(xsize,ysize); + DrawIMG(changeButtonsBack,background,xplace,yplace); + NFont_Write(background, xplace+10,yplace+10,_("1 : Very Easy") ); + NFont_Write(background, xplace+10,yplace+40,_("2 : Easy") ); + NFont_Write(background, xplace+10,yplace+70,_("3 : Below Normal") ); + NFont_Write(background, xplace+10,yplace+100,_("4 : Normal") ); + NFont_Write(background, xplace+10,yplace+130,_("5 : Above Normal") ); + NFont_Write(background, xplace+10,yplace+160,_("6 : Hard") ); + NFont_Write(background, xplace+10,yplace+190,_("7 : Hardest") ); + DrawIMG(background, screen, 0, 0); + SDL_Flip(screen); + do + { + + SDL_Delay(10); + SDL_Event event; + while ( SDL_PollEvent(&event) ) + if ( event.type == SDL_KEYDOWN ) + { + if ( event.key.keysym.sym == SDLK_KP_ENTER || event.key.keysym.sym == SDLK_ESCAPE || event.key.keysym.sym == SDLK_RETURN ) + { + done = true; + } + if ( event.key.keysym.sym == SDLK_1 || event.key.keysym.sym == SDLK_KP1 ) + { + return 0; + } + if ( event.key.keysym.sym == SDLK_2 || event.key.keysym.sym == SDLK_KP2 ) + { + return 1; + } + if ( event.key.keysym.sym == SDLK_3 || event.key.keysym.sym == SDLK_KP3 ) + { + return 2; + } + if ( event.key.keysym.sym == SDLK_4 || event.key.keysym.sym == SDLK_KP4 ) + { + return 3; + } + if ( event.key.keysym.sym == SDLK_5 || event.key.keysym.sym == SDLK_KP5 ) + { + return 4; + } + if ( event.key.keysym.sym == SDLK_6 || event.key.keysym.sym == SDLK_KP6 ) + { + return 5; + } + if ( event.key.keysym.sym == SDLK_7 || event.key.keysym.sym == SDLK_KP7 ) + { + return 6; + } + } + + // If the mouse button is released, make bMouseUp equal true + if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) + { + bMouseUp=true; + } - if (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp) - { - bMouseUp = false; + if (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp) + { + bMouseUp = false; - for (int i=0; i<7;i++) - { - if ((mousex>xplace+10)&&(mousexyplace+10+i*30)&&(mouseyxplace+10)&&(mousexyplace+10+i*30)&&(mouseyisShuttingDown()); + SDL_GetMouseState(&mousex,&mousey); + DrawIMG(background, screen, 0, 0); + //DrawIMG(mouse,screen,mousex,mousey); + mouse.PaintTo(screen,mousex,mousey); + SDL_Flip(screen); //draws it all to the screen + } + while (!done && !Config::getInstance()->isShuttingDown()); - return 3; //Returns normal + return 3; //Returns normal } //The function that allows the player to choose Level number void startVsMenu() { - const int xplace = 200; - const int yplace = 100; - Uint8 *keys; - int mousex, mousey; - bool done = false; - - //Keeps track of background; - //int nowTime=SDL_GetTicks(); - - MakeBackground(xsize,ysize); - NFont_Write(background, 360,650, _("Press ESC to accept") ); - DrawIMG(bBack,background,xsize/2-120/2,600); - do - { - //nowTime=SDL_GetTicks(); - DrawIMG(background, screen, 0, 0); - DrawIMG(changeButtonsBack,screen,xplace,yplace); - NFont_Write(screen, xplace+50,yplace+20,"Player 1"); - NFont_Write(screen, xplace+300+50,yplace+20,"Player 2"); - NFont_Write(screen, xplace+50,yplace+70,"Speed:"); - NFont_Write(screen, xplace+50+300,yplace+70,"Speed:"); - for (int i=0; i<5;i++) - { - char levelS[2]; //level string; - levelS[0]='1'+i; - levelS[1]=0; - NFont_Write(screen, xplace+50+i*40,yplace+110,levelS); - DrawIMG(iLevelCheckBox,screen,xplace+50+i*40,yplace+150); - if (player1Speed==i) - DrawIMG(iLevelCheck,screen,xplace+50+i*40,yplace+150); - } - for (int i=0; i<5;i++) - { - char levelS[2]; //level string; - levelS[0]='1'+i; - levelS[1]=0; - NFont_Write(screen, xplace+300+50+i*40,yplace+110,levelS); - DrawIMG(iLevelCheckBox,screen,xplace+300+50+i*40,yplace+150); - if (player2Speed==i) - DrawIMG(iLevelCheck,screen,xplace+300+50+i*40,yplace+150); - } - NFont_Write(screen, xplace+50,yplace+200,"AI: "); - DrawIMG(iLevelCheckBox,screen,xplace+50+70,yplace+200); - if (player1AI) - DrawIMG(iLevelCheck,screen,xplace+50+70,yplace+200); - NFont_Write(screen, xplace+50,yplace+250,"TT Handicap: "); - NFont_Write(screen, xplace+50+300,yplace+200,"AI: "); - DrawIMG(iLevelCheckBox,screen,xplace+50+70+300,yplace+200); - if (player2AI) - DrawIMG(iLevelCheck,screen,xplace+50+70+300,yplace+200); - NFont_Write(screen, xplace+50+300,yplace+250,"TT Handicap: "); - for (int i=0; i<5;i++) - { - char levelS[2]; //level string; - levelS[0]='1'+i; - levelS[1]=0; - NFont_Write(screen, xplace+50+i*40,yplace+290,levelS); - DrawIMG(iLevelCheckBox,screen,xplace+50+i*40,yplace+330); - if (player1handicap==i) - DrawIMG(iLevelCheck,screen,xplace+50+i*40,yplace+330); - } - for (int i=0; i<5;i++) - { - char levelS[2]; //level string; - levelS[0]='1'+i; - levelS[1]=0; - NFont_Write(screen, xplace+50+i*40+300,yplace+290,levelS); - DrawIMG(iLevelCheckBox,screen,xplace+50+i*40+300,yplace+330); - if (player2handicap==i) - DrawIMG(iLevelCheck,screen,xplace+50+i*40+300,yplace+330); - } - - SDL_Event event; - while ( SDL_PollEvent(&event) ) - if ( event.type == SDL_KEYDOWN ) - { - if ( event.key.keysym.sym == SDLK_ESCAPE ) { - done = true; - } - if ( event.key.keysym.sym == SDLK_RETURN ) { - done = true; - } - if ( event.key.keysym.sym == SDLK_KP_ENTER ) { - done = true; - } - } - - keys = SDL_GetKeyState(NULL); - - SDL_GetMouseState(&mousex,&mousey); - - // If the mouse button is released, make bMouseUp equal true - if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) - { - bMouseUp=true; - } + const int xplace = 200; + const int yplace = 100; + Uint8 *keys; + int mousex, mousey; + bool done = false; + + //Keeps track of background; + //int nowTime=SDL_GetTicks(); + + MakeBackground(xsize,ysize); + NFont_Write(background, 360,650, _("Press ESC to accept") ); + DrawIMG(bBack,background,xsize/2-120/2,600); + do + { + //nowTime=SDL_GetTicks(); + DrawIMG(background, screen, 0, 0); + DrawIMG(changeButtonsBack,screen,xplace,yplace); + NFont_Write(screen, xplace+50,yplace+20,"Player 1"); + NFont_Write(screen, xplace+300+50,yplace+20,"Player 2"); + NFont_Write(screen, xplace+50,yplace+70,"Speed:"); + NFont_Write(screen, xplace+50+300,yplace+70,"Speed:"); + for (int i=0; i<5; i++) + { + char levelS[2]; //level string; + levelS[0]='1'+i; + levelS[1]=0; + NFont_Write(screen, xplace+50+i*40,yplace+110,levelS); + DrawIMG(iLevelCheckBox,screen,xplace+50+i*40,yplace+150); + if (player1Speed==i) + DrawIMG(iLevelCheck,screen,xplace+50+i*40,yplace+150); + } + for (int i=0; i<5; i++) + { + char levelS[2]; //level string; + levelS[0]='1'+i; + levelS[1]=0; + NFont_Write(screen, xplace+300+50+i*40,yplace+110,levelS); + DrawIMG(iLevelCheckBox,screen,xplace+300+50+i*40,yplace+150); + if (player2Speed==i) + DrawIMG(iLevelCheck,screen,xplace+300+50+i*40,yplace+150); + } + NFont_Write(screen, xplace+50,yplace+200,"AI: "); + DrawIMG(iLevelCheckBox,screen,xplace+50+70,yplace+200); + if (player1AI) + DrawIMG(iLevelCheck,screen,xplace+50+70,yplace+200); + NFont_Write(screen, xplace+50,yplace+250,"TT Handicap: "); + NFont_Write(screen, xplace+50+300,yplace+200,"AI: "); + DrawIMG(iLevelCheckBox,screen,xplace+50+70+300,yplace+200); + if (player2AI) + DrawIMG(iLevelCheck,screen,xplace+50+70+300,yplace+200); + NFont_Write(screen, xplace+50+300,yplace+250,"TT Handicap: "); + for (int i=0; i<5; i++) + { + char levelS[2]; //level string; + levelS[0]='1'+i; + levelS[1]=0; + NFont_Write(screen, xplace+50+i*40,yplace+290,levelS); + DrawIMG(iLevelCheckBox,screen,xplace+50+i*40,yplace+330); + if (player1handicap==i) + DrawIMG(iLevelCheck,screen,xplace+50+i*40,yplace+330); + } + for (int i=0; i<5; i++) + { + char levelS[2]; //level string; + levelS[0]='1'+i; + levelS[1]=0; + NFont_Write(screen, xplace+50+i*40+300,yplace+290,levelS); + DrawIMG(iLevelCheckBox,screen,xplace+50+i*40+300,yplace+330); + if (player2handicap==i) + DrawIMG(iLevelCheck,screen,xplace+50+i*40+300,yplace+330); + } - if (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp) - { - bMouseUp = false; + SDL_Event event; + while ( SDL_PollEvent(&event) ) + if ( event.type == SDL_KEYDOWN ) + { + if ( event.key.keysym.sym == SDLK_ESCAPE ) + { + done = true; + } + if ( event.key.keysym.sym == SDLK_RETURN ) + { + done = true; + } + if ( event.key.keysym.sym == SDLK_KP_ENTER ) + { + done = true; + } + } + + keys = SDL_GetKeyState(NULL); + + SDL_GetMouseState(&mousex,&mousey); + + // If the mouse button is released, make bMouseUp equal true + if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) + { + bMouseUp=true; + } - if ((mousex>xplace+50+70)&&(mousey>yplace+200)&&(mousexxplace+50+70+300)&&(mousey>yplace+200)&&(mousexxplace+50+i*40)&&(mousexyplace+150)&&(mouseyxplace+50+i*40+300)&&(mousexyplace+150)&&(mouseyxplace+50+i*40)&&(mousexyplace+330)&&(mouseyxplace+50+i*40+300)&&(mousexyplace+330)&&(mouseyxsize/2-120/2)&&(mousex600)&&(mousey<640)) - done = true; - } + if (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp) + { + bMouseUp = false; + + if ((mousex>xplace+50+70)&&(mousey>yplace+200)&&(mousexxplace+50+70+300)&&(mousey>yplace+200)&&(mousexxplace+50+i*40)&&(mousexyplace+150)&&(mouseyxplace+50+i*40+300)&&(mousexyplace+150)&&(mouseyxplace+50+i*40)&&(mousexyplace+330)&&(mouseyxplace+50+i*40+300)&&(mousexyplace+330)&&(mouseyxsize/2-120/2)&&(mousex600)&&(mousey<640)) + done = true; + } - //DrawIMG(mouse,screen,mousex,mousey); - mouse.PaintTo(screen,mousex,mousey); - SDL_Flip(screen); //draws it all to the screen - SDL_Delay(10); + //DrawIMG(mouse,screen,mousex,mousey); + mouse.PaintTo(screen,mousex,mousey); + SDL_Flip(screen); //draws it all to the screen + SDL_Delay(10); - } while (!done && !Config::getInstance()->isShuttingDown()); - DrawIMG(background, screen, 0, 0); + } + while (!done && !Config::getInstance()->isShuttingDown()); + DrawIMG(background, screen, 0, 0); } //This function will promt for the user to select another file for puzzle mode void changePuzzleLevels() { - char theFileName[30]; - strcpy(theFileName,puzzleName.c_str()); - for (int i=puzzleName.length();i<30;i++) - theFileName[i]=' '; - theFileName[29]=0; - if (OpenFileDialogbox(200,100,theFileName)) - { - for (int i=28;((theFileName[i]==' ')&&(i>0));i--) - theFileName[i]=0; - puzzleName = theFileName; + char theFileName[30]; + strcpy(theFileName,puzzleName.c_str()); + for (int i=puzzleName.length(); i<30; i++) + theFileName[i]=' '; + theFileName[29]=0; + if (OpenFileDialogbox(200,100,theFileName)) + { + for (int i=28; ((theFileName[i]==' ')&&(i>0)); i--) + theFileName[i]=0; + puzzleName = theFileName; #if defined(__unix__) - string home = getenv("HOME"); - puzzleSavePath = home+"/.gamesaves/blockattack/"+puzzleName+".save"; + string home = getenv("HOME"); + puzzleSavePath = home+"/.gamesaves/blockattack/"+puzzleName+".save"; #elif defined(_WIN32) - string home = getMyDocumentsPath(); - if (&home!=NULL) - { - puzzleSavePath = home+"/My Games/blockattack/"+puzzleName+".save"; - } - else - { - puzzleSavePath = puzzleName+".save"; - } + string home = getMyDocumentsPath(); + if (&home!=NULL) + { + puzzleSavePath = home+"/My Games/blockattack/"+puzzleName+".save"; + } + else + { + puzzleSavePath = puzzleName+".save"; + } #else - puzzleSavePath = puzzleName+".save"; + puzzleSavePath = puzzleName+".save"; #endif - } + } } static BlockGameSdl *player1; static BlockGameSdl *player2; -void StartSinglePlayerEndless() { - //1 player - endless - player1->NewGame(50,100,SDL_GetTicks()); - player1->putStartBlocks(time(0)); - bNewGameOpen = false; - b1playerOpen = false; - twoPlayers =false; - player2->SetGameOver(); - showGame = true; - strcpy(player1->name, player1name); - strcpy(player2->name, player2name); +void StartSinglePlayerEndless() +{ + //1 player - endless + player1->NewGame(50,100,SDL_GetTicks()); + player1->putStartBlocks(time(0)); + bNewGameOpen = false; + b1playerOpen = false; + twoPlayers =false; + player2->SetGameOver(); + showGame = true; + strcpy(player1->name, player1name); + strcpy(player2->name, player2name); } -void StartSinglePlayerTimeTrial() { - player1->NewTimeTrialGame(50,100,SDL_GetTicks()); - closeAllMenus(); - twoPlayers =false; - player2->SetGameOver(); - showGame = true; - //vsMode = false; - strcpy(player1->name, player1name); - strcpy(player2->name, player2name); +void StartSinglePlayerTimeTrial() +{ + player1->NewTimeTrialGame(50,100,SDL_GetTicks()); + closeAllMenus(); + twoPlayers =false; + player2->SetGameOver(); + showGame = true; + //vsMode = false; + strcpy(player1->name, player1name); + strcpy(player2->name, player2name); } -void StartSinglePlayerPuzzle() { - int myLevel = PuzzleLevelSelect(); - player1->NewPuzzleGame(myLevel,50,100,SDL_GetTicks()); - MakeBackground(xsize,ysize,player1,player2); - DrawIMG(background, screen, 0, 0); - closeAllMenus(); - twoPlayers = false; - player2->SetGameOver(); - showGame = true; - //vsMode = true; - strcpy(player1->name, player1name); - strcpy(player2->name, player2name); +void StartSinglePlayerPuzzle() +{ + int myLevel = PuzzleLevelSelect(); + player1->NewPuzzleGame(myLevel,50,100,SDL_GetTicks()); + MakeBackground(xsize,ysize,player1,player2); + DrawIMG(background, screen, 0, 0); + closeAllMenus(); + twoPlayers = false; + player2->SetGameOver(); + showGame = true; + //vsMode = true; + strcpy(player1->name, player1name); + strcpy(player2->name, player2name); } -void StarTwoPlayerTimeTrial() { - player1->NewTimeTrialGame(50,100,SDL_GetTicks()); - player2->NewTimeTrialGame(xsize-500,100,SDL_GetTicks()); - int theTime = time(0); - player1->putStartBlocks(theTime); - player2->putStartBlocks(theTime); - closeAllMenus(); - twoPlayers = true; - player1->setGameSpeed(player1Speed); - player2->setGameSpeed(player2Speed); - player1->setHandicap(player1handicap); - player2->setHandicap(player2handicap); - if(player1AI) - player1->setAIlevel(player1AIlevel); - if(player2AI) - player2->setAIlevel(player2AIlevel); - strcpy(player1->name, player1name); - strcpy(player2->name, player2name); +void StarTwoPlayerTimeTrial() +{ + player1->NewTimeTrialGame(50,100,SDL_GetTicks()); + player2->NewTimeTrialGame(xsize-500,100,SDL_GetTicks()); + int theTime = time(0); + player1->putStartBlocks(theTime); + player2->putStartBlocks(theTime); + closeAllMenus(); + twoPlayers = true; + player1->setGameSpeed(player1Speed); + player2->setGameSpeed(player2Speed); + player1->setHandicap(player1handicap); + player2->setHandicap(player2handicap); + if(player1AI) + player1->setAIlevel(player1AIlevel); + if(player2AI) + player2->setAIlevel(player2AIlevel); + strcpy(player1->name, player1name); + strcpy(player2->name, player2name); } -void StartTwoPlayerVs() { - //2 player - VsMode - player1->NewVsGame(50,100,player2,SDL_GetTicks()); - player2->NewVsGame(xsize-500,100,player1,SDL_GetTicks()); - bNewGameOpen = false; - //vsMode = true; - twoPlayers = true; - b2playersOpen = false; - player1->setGameSpeed(player1Speed); - player2->setGameSpeed(player2Speed); - player1->setHandicap(player1handicap); - player2->setHandicap(player2handicap); - if(player1AI) - player1->setAIlevel(player1AIlevel); - if(player2AI) - player2->setAIlevel(player2AIlevel); - int theTime = time(0); - player1->putStartBlocks(theTime); - player2->putStartBlocks(theTime); - strcpy(player1->name, player1name); - strcpy(player2->name, player2name); +void StartTwoPlayerVs() +{ + //2 player - VsMode + player1->NewVsGame(50,100,player2,SDL_GetTicks()); + player2->NewVsGame(xsize-500,100,player1,SDL_GetTicks()); + bNewGameOpen = false; + //vsMode = true; + twoPlayers = true; + b2playersOpen = false; + player1->setGameSpeed(player1Speed); + player2->setGameSpeed(player2Speed); + player1->setHandicap(player1handicap); + player2->setHandicap(player2handicap); + if(player1AI) + player1->setAIlevel(player1AIlevel); + if(player2AI) + player2->setAIlevel(player2AIlevel); + int theTime = time(0); + player1->putStartBlocks(theTime); + player2->putStartBlocks(theTime); + strcpy(player1->name, player1name); + strcpy(player2->name, player2name); } #if NETWORK @@ -3399,1325 +3497,1351 @@ void StartTwoPlayerVs() { //The main function, quite big... too big int main(int argc, char *argv[]) { - //We first create the folder there we will save (only on UNIX systems) - //we call the external command "mkdir"... the user might have renamed this, but we hope he hasn't + //We first create the folder there we will save (only on UNIX systems) + //we call the external command "mkdir"... the user might have renamed this, but we hope he hasn't #if defined(__unix__) - //Compiler warns about unused result. The users envisonment should normally give the user all the information he needs - if(system("mkdir -p ~/.gamesaves/blockattack/screenshots")) - cout << "mkdir error creating ~/.gamesaves/blockattack/screenshots" << endl; - if(system("mkdir -p ~/.gamesaves/blockattack/replays")) - cout << "mkdir error creating ~/.gamesaves/blockattack/replays" << endl; - if(system("mkdir -p ~/.gamesaves/blockattack/puzzles")) - cout << "mkdir error creating ~/.gamesaves/blockattack/puzzles" << endl; + //Compiler warns about unused result. The users envisonment should normally give the user all the information he needs + if(system("mkdir -p ~/.gamesaves/blockattack/screenshots")) + cout << "mkdir error creating ~/.gamesaves/blockattack/screenshots" << endl; + if(system("mkdir -p ~/.gamesaves/blockattack/replays")) + cout << "mkdir error creating ~/.gamesaves/blockattack/replays" << endl; + if(system("mkdir -p ~/.gamesaves/blockattack/puzzles")) + cout << "mkdir error creating ~/.gamesaves/blockattack/puzzles" << endl; #elif defined(_WIN32) - //Now for Windows NT/2k/xp/2k3 etc. - string tempA = getMyDocumentsPath()+"\\My Games"; - CreateDirectory(tempA.c_str(),NULL); - tempA = getMyDocumentsPath()+"\\My Games\\blockattack"; - CreateDirectory(tempA.c_str(),NULL); - tempA = getMyDocumentsPath()+"\\My Games\\blockattack\\replays"; - CreateDirectory(tempA.c_str(),NULL); - tempA = getMyDocumentsPath()+"\\My Games\\blockattack\\screenshots"; - CreateDirectory(tempA.c_str(),NULL); + //Now for Windows NT/2k/xp/2k3 etc. + string tempA = getMyDocumentsPath()+"\\My Games"; + CreateDirectory(tempA.c_str(),NULL); + tempA = getMyDocumentsPath()+"\\My Games\\blockattack"; + CreateDirectory(tempA.c_str(),NULL); + tempA = getMyDocumentsPath()+"\\My Games\\blockattack\\replays"; + CreateDirectory(tempA.c_str(),NULL); + tempA = getMyDocumentsPath()+"\\My Games\\blockattack\\screenshots"; + CreateDirectory(tempA.c_str(),NULL); #endif - highPriority = false; //if true the game will take most resources, but increase framerate. - bFullscreen = false; - //Set default Config variables: - Config::getInstance()->setDefault("themename","default"); - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - if (argc > 1) - { - int argumentNr = 1; - forceredraw = 2; - while (argc>argumentNr) - { - char helpString[] = "--help"; - char priorityString[] = "-priority"; - char forceRedrawString[] = "-forceredraw"; - char forcepartdrawString[] = "-forcepartdraw"; - char singlePuzzleString[] = "-SP"; - char noSoundAtAll[] = "-nosound"; - char IntegratedEditor[] = "-editor"; - char selectTheme[] = "-theme"; - if (!(strncmp(argv[argumentNr],helpString,6))) - { - cout << "Block Attack Help" << endl << "--help " << _("Displays this message") << - endl << "-priority " << _("Starts game in high priority") << endl << - "-forceredraw " << _("Redraw the whole screen every frame, prevents garbage") << endl << - "-forcepartdraw " << _("Only draw what is changed, sometimes cause garbage") << endl << - "-nosound " << _("No sound will be played at all, and sound hardware will not be loaded (use this if game crashes because of sound)") << endl << - "-theme <" << _("THEMENAME") << "> " << _("Changes to the theme on startup") << endl << - "-editor " << _("Starts the build-in editor (not yet integrated)") << endl; + highPriority = false; //if true the game will take most resources, but increase framerate. + bFullscreen = false; + //Set default Config variables: + Config::getInstance()->setDefault("themename","default"); + setlocale (LC_ALL, ""); + bindtextdomain (PACKAGE, LOCALEDIR); + textdomain (PACKAGE); + if (argc > 1) + { + int argumentNr = 1; + forceredraw = 2; + while (argc>argumentNr) + { + char helpString[] = "--help"; + char priorityString[] = "-priority"; + char forceRedrawString[] = "-forceredraw"; + char forcepartdrawString[] = "-forcepartdraw"; + char singlePuzzleString[] = "-SP"; + char noSoundAtAll[] = "-nosound"; + char IntegratedEditor[] = "-editor"; + char selectTheme[] = "-theme"; + if (!(strncmp(argv[argumentNr],helpString,6))) + { + cout << "Block Attack Help" << endl << "--help " << _("Displays this message") << + endl << "-priority " << _("Starts game in high priority") << endl << + "-forceredraw " << _("Redraw the whole screen every frame, prevents garbage") << endl << + "-forcepartdraw " << _("Only draw what is changed, sometimes cause garbage") << endl << + "-nosound " << _("No sound will be played at all, and sound hardware will not be loaded (use this if game crashes because of sound)") << endl << + "-theme <" << _("THEMENAME") << "> " << _("Changes to the theme on startup") << endl << + "-editor " << _("Starts the build-in editor (not yet integrated)") << endl; #ifdef WIN32 - system("Pause"); + system("Pause"); #endif - return 0; - } - if (!(strncmp(argv[argumentNr],priorityString,9))) - { - cout << "Priority mode" << endl; - highPriority = true; - } - if (!(strncmp(argv[argumentNr],forceRedrawString,12))) - { - forceredraw = 1; - } - if (!(strncmp(argv[argumentNr],forcepartdrawString,14))) - { - forceredraw = 2; - } - if (!(strncmp(argv[argumentNr],singlePuzzleString,3))) - { - singlePuzzle = true; //We will just have one puzzle - if (argv[argumentNr+1][1]!=0) - singlePuzzleNr = (argv[argumentNr+1][1]-'0')+(argv[argumentNr+1][0]-'0')*10; - else - singlePuzzleNr = (argv[argumentNr+1][0]-'0'); - singlePuzzleFile = argv[argumentNr+2]; - argumentNr+=2; - cout << "SinglePuzzleMode, File: " << singlePuzzleFile << " and Level: " << singlePuzzleNr << endl; - } - if (!(strncmp(argv[argumentNr],noSoundAtAll,8))) - { - NoSound = true; - } - if (!(strncmp(argv[argumentNr],IntegratedEditor,7))) - { - #if LEVELEDITOR - editorMode = true; - cout << "Integrated Puzzle Editor Activated" << endl; - #else - cout << "Integrated Puzzle Editor was disabled at compile time" << endl; - return -1; - #endif - } - if(!(strncmp(argv[argumentNr],selectTheme,6))) - { - argumentNr++; //Go to themename (the next argument) - cout << "Theme set to \"" << argv[argumentNr] << '"' << endl; - Config::getInstance()->setString("themename",argv[argumentNr]); - } - argumentNr++; - } //while - } //if - - SoundEnabled = true; - MusicEnabled = true; - int mousex, mousey; //Mouse coordinates - showOptions = false; - b1playerOpen = false; - b2playersOpen = false; - bReplayOpen = false; - bScreenLocked = false; - twoPlayers = false; //true if two players splitscreen - bool vsMode = false; - theTopScoresEndless = Highscore(1); - theTopScoresTimeTrial = Highscore(2); - drawBalls = true; - puzzleLoaded = false; - bool weWhereConnected = false; - - //Things used for repeating keystrokes: - /*bool repeatingS[2] = {false,false}; - bool repeatingW[2] = {false,false}; - bool repeatingN[2] = {false,false}; - bool repeatingE[2] = {false,false}; - const int startRepeat = 200; - const int repeatDelay = 100; //Repeating - unsigned long timeHeldP1N = 0; - unsigned long timeHeldP1S = 0; - unsigned long timeHeldP1E = 0; - unsigned long timeHeldP1W = 0; - unsigned long timeHeldP2N = 0; - unsigned long timeHeldP2S = 0; - unsigned long timeHeldP2E = 0; - unsigned long timeHeldP2W = 0; - unsigned long timesRepeatedP1N = 0; - unsigned long timesRepeatedP1S = 0; - unsigned long timesRepeatedP1E = 0; - unsigned long timesRepeatedP1W = 0; - unsigned long timesRepeatedP2N = 0; - unsigned long timesRepeatedP2S = 0; - unsigned long timesRepeatedP2E = 0; - unsigned long timesRepeatedP2W = 0;*/ - - theBallManeger = ballManeger(); - theExplosionManeger = explosionManeger(); - -//We now set the paths were we are saving, we are using the keyword __unix__ . I hope that all UNIX systems has a home folder -#if defined(__unix__) - string home = getenv("HOME"); - string optionsPath = home+"/.gamesaves/blockattack/options.dat"; -#elif defined(_WIN32) - string home = getMyDocumentsPath(); - string optionsPath; - if (&home!=NULL) //Null if no APPDATA dir exists (win 9x) - optionsPath = home+"/My Games/blockattack/options.dat"; - else - optionsPath = "options.dat"; + return 0; + } + if (!(strncmp(argv[argumentNr],priorityString,9))) + { + cout << "Priority mode" << endl; + highPriority = true; + } + if (!(strncmp(argv[argumentNr],forceRedrawString,12))) + { + forceredraw = 1; + } + if (!(strncmp(argv[argumentNr],forcepartdrawString,14))) + { + forceredraw = 2; + } + if (!(strncmp(argv[argumentNr],singlePuzzleString,3))) + { + singlePuzzle = true; //We will just have one puzzle + if (argv[argumentNr+1][1]!=0) + singlePuzzleNr = (argv[argumentNr+1][1]-'0')+(argv[argumentNr+1][0]-'0')*10; + else + singlePuzzleNr = (argv[argumentNr+1][0]-'0'); + singlePuzzleFile = argv[argumentNr+2]; + argumentNr+=2; + cout << "SinglePuzzleMode, File: " << singlePuzzleFile << " and Level: " << singlePuzzleNr << endl; + } + if (!(strncmp(argv[argumentNr],noSoundAtAll,8))) + { + NoSound = true; + } + if (!(strncmp(argv[argumentNr],IntegratedEditor,7))) + { +#if LEVELEDITOR + editorMode = true; + cout << "Integrated Puzzle Editor Activated" << endl; #else - string optionsPath = "options.dat"; + cout << "Integrated Puzzle Editor was disabled at compile time" << endl; + return -1; #endif + } + if(!(strncmp(argv[argumentNr],selectTheme,6))) + { + argumentNr++; //Go to themename (the next argument) + cout << "Theme set to \"" << argv[argumentNr] << '"' << endl; + Config::getInstance()->setString("themename",argv[argumentNr]); + } + argumentNr++; + } //while + } //if + + SoundEnabled = true; + MusicEnabled = true; + int mousex, mousey; //Mouse coordinates + showOptions = false; + b1playerOpen = false; + b2playersOpen = false; + bReplayOpen = false; + bScreenLocked = false; + twoPlayers = false; //true if two players splitscreen + bool vsMode = false; + theTopScoresEndless = Highscore(1); + theTopScoresTimeTrial = Highscore(2); + drawBalls = true; + puzzleLoaded = false; + bool weWhereConnected = false; + + //Things used for repeating keystrokes: + /*bool repeatingS[2] = {false,false}; + bool repeatingW[2] = {false,false}; + bool repeatingN[2] = {false,false}; + bool repeatingE[2] = {false,false}; + const int startRepeat = 200; + const int repeatDelay = 100; //Repeating + unsigned long timeHeldP1N = 0; + unsigned long timeHeldP1S = 0; + unsigned long timeHeldP1E = 0; + unsigned long timeHeldP1W = 0; + unsigned long timeHeldP2N = 0; + unsigned long timeHeldP2S = 0; + unsigned long timeHeldP2E = 0; + unsigned long timeHeldP2W = 0; + unsigned long timesRepeatedP1N = 0; + unsigned long timesRepeatedP1S = 0; + unsigned long timesRepeatedP1E = 0; + unsigned long timesRepeatedP1W = 0; + unsigned long timesRepeatedP2N = 0; + unsigned long timesRepeatedP2S = 0; + unsigned long timesRepeatedP2E = 0; + unsigned long timesRepeatedP2W = 0;*/ + + theBallManeger = ballManeger(); + theExplosionManeger = explosionManeger(); +//We now set the paths were we are saving, we are using the keyword __unix__ . I hope that all UNIX systems has a home folder #if defined(__unix__) - stageClearSavePath = home+"/.gamesaves/blockattack/stageClear.SCsave"; - puzzleSavePath = home+"/.gamesaves/blockattack/puzzle.levels.save"; + string home = getenv("HOME"); + string optionsPath = home+"/.gamesaves/blockattack/options.dat"; #elif defined(_WIN32) - if (&home!=NULL) - { - stageClearSavePath = home+"/My Games/blockattack/stageClear.SCsave"; - puzzleSavePath = home+"/My Games/blockattack/puzzle.levels.save"; - } - else - { - stageClearSavePath = "stageClear.SCsave"; - puzzleSavePath = "puzzle.levels.save"; - } + string home = getMyDocumentsPath(); + string optionsPath; + if (&home!=NULL) //Null if no APPDATA dir exists (win 9x) + optionsPath = home+"/My Games/blockattack/options.dat"; + else + optionsPath = "options.dat"; #else - stageClearSavePath = "stageClear.SCsave"; - puzzleSavePath = "puzzle.levels.save"; + string optionsPath = "options.dat"; #endif - puzzleName="puzzle.levels"; - - Uint8 *keys; - - - - //Init SDL - if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) - { - cout << "Unable to init SDL: " << SDL_GetError() << endl; - exit(1); - } - atexit(SDL_Quit); //quits SDL when the game stops for some reason (like you hit exit or Esc) - - SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); - - Joypad_init(); //Prepare the joysticks - - Joypad joypad1 = Joypad(); //Creates a joypad - Joypad joypad2 = Joypad(); //Creates a joypad - - theTextManeger = textManeger(); - - //Open Audio - if (!NoSound) //If sound has not been disabled, then load the sound system - if (Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 2048) < 0) - { - cout << "Warning: Couldn't set 44100 Hz 16-bit audio - Reason: " << SDL_GetError() << endl - << "Sound will be disabled!" << endl; - NoSound = true; //Tries to stop all sound from playing/loading - } - - SDL_WM_SetCaption("Block Attack - Rise of the Blocks", NULL); //Sets title line - - //Copyright notice: - cout << "Block Attack - Rise of the Blocks (" << VERSION_NUMBER << ")" << endl << "http://blockattack.sf.net" << endl << "Copyright 2004-2011 Poul Sander" << endl << - "A SDL based game (see www.libsdl.org)" << endl << - "The game is availeble under the GPL, see COPYING for details." << endl; -#if defined(_WIN32) - cout << "Windows build" << endl; -#elif defined(__linux__) - cout << "Linux build" << endl; -#elif defined(__unix__) - cout << "Unix build" << endl; +#if defined(__unix__) + stageClearSavePath = home+"/.gamesaves/blockattack/stageClear.SCsave"; + puzzleSavePath = home+"/.gamesaves/blockattack/puzzle.levels.save"; +#elif defined(_WIN32) + if (&home!=NULL) + { + stageClearSavePath = home+"/My Games/blockattack/stageClear.SCsave"; + puzzleSavePath = home+"/My Games/blockattack/puzzle.levels.save"; + } + else + { + stageClearSavePath = "stageClear.SCsave"; + puzzleSavePath = "puzzle.levels.save"; + } #else - cout << "Alternative build" << endl; + stageClearSavePath = "stageClear.SCsave"; + puzzleSavePath = "puzzle.levels.save"; #endif - cout << "-------------------------------------------" << endl; + puzzleName="puzzle.levels"; + Uint8 *keys; - keySettings[0].up= SDLK_UP; - keySettings[0].down = SDLK_DOWN; - keySettings[0].left = SDLK_LEFT; - keySettings[0].right = SDLK_RIGHT; - keySettings[0].change = SDLK_RCTRL; - keySettings[0].push = SDLK_RSHIFT; - keySettings[2].up= SDLK_w; - keySettings[2].down = SDLK_s; - keySettings[2].left = SDLK_a; - keySettings[2].right = SDLK_d; - keySettings[2].change = SDLK_LCTRL; - keySettings[2].push = SDLK_LSHIFT; - player1keys=0; - player2keys=2; + //Init SDL + if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) + { + cout << "Unable to init SDL: " << SDL_GetError() << endl; + exit(1); + } + atexit(SDL_Quit); //quits SDL when the game stops for some reason (like you hit exit or Esc) - strcpy(player1name, "Player 1 \0"); - strcpy(player2name, "Player 2 \0"); + SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); - Config *configSettings = Config::getInstance(); - //configSettings->setString("aNumber"," A string"); - //configSettings->save(); - if(configSettings->exists("fullscreen")) //Test if an configFile exists - { - bFullscreen = (bool)configSettings->getInt("fullscreen"); - MusicEnabled = (bool)configSettings->getInt("musicenabled"); - SoundEnabled = (bool)configSettings->getInt("soundenabled"); - mouseplay1 = (bool)configSettings->getInt("mouseplay1"); - mouseplay2 = (bool)configSettings->getInt("mouseplay2"); - joyplay1 = (bool)configSettings->getInt("joypad1"); - joyplay2 = (bool)configSettings->getInt("joypad2"); - - if(configSettings->exists("player1keyup")) keySettings[0].up = (SDLKey)configSettings->getInt("player1keyup"); - if(configSettings->exists("player1keydown")) keySettings[0].down = (SDLKey)configSettings->getInt("player1keydown"); - if(configSettings->exists("player1keyleft")) keySettings[0].left = (SDLKey)configSettings->getInt("player1keyleft"); - if(configSettings->exists("player1keyright")) keySettings[0].right = (SDLKey)configSettings->getInt("player1keyright"); - if(configSettings->exists("player1keychange")) keySettings[0].change = (SDLKey)configSettings->getInt("player1keychange"); - if(configSettings->exists("player1keypush")) keySettings[0].push = (SDLKey)configSettings->getInt("player1keypush"); - - if(configSettings->exists("player2keyup")) keySettings[2].up = (SDLKey)configSettings->getInt("player2keyup"); - if(configSettings->exists("player2keydown")) keySettings[2].down = (SDLKey)configSettings->getInt("player2keydown"); - if(configSettings->exists("player2keyleft")) keySettings[2].left = (SDLKey)configSettings->getInt("player2keyleft"); - if(configSettings->exists("player2keyright")) keySettings[2].right = (SDLKey)configSettings->getInt("player2keyright"); - if(configSettings->exists("player2keychange")) keySettings[2].change = (SDLKey)configSettings->getInt("player2keychange"); - if(configSettings->exists("player2keypush")) keySettings[2].push = (SDLKey)configSettings->getInt("player2keypush"); - if(configSettings->exists("player1name")) - strncpy(player1name,(configSettings->getString("player1name")).c_str(),28); - if(configSettings->exists("player2name")) - strncpy(player2name,(configSettings->getString("player2name")).c_str(),28); - cout << "Data loaded from config file" << endl; - } - else - { - //Reads options from file: - ifstream optionsFile(optionsPath.c_str(), ios::binary); - if (optionsFile) - { - //reads data: xsize,ysize,fullescreen, player1keys, player2keys, MusicEnabled, SoundEnabled,player1name,player2name - optionsFile.read(reinterpret_cast(&xsize), sizeof(int)); - optionsFile.read(reinterpret_cast(&ysize), sizeof(int)); - optionsFile.read(reinterpret_cast(&bFullscreen), sizeof(bool)); - optionsFile.read(reinterpret_cast(&keySettings[0].up), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&keySettings[0].down), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&keySettings[0].left), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&keySettings[0].right), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&keySettings[0].change), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&keySettings[0].push), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&keySettings[2].up), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&keySettings[2].down), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&keySettings[2].left), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&keySettings[2].right), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&keySettings[2].change), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&keySettings[2].push), sizeof(SDLKey)); - optionsFile.read(reinterpret_cast(&MusicEnabled), sizeof(bool)); - optionsFile.read(reinterpret_cast(&SoundEnabled), sizeof(bool)); - optionsFile.read(player1name, 30*sizeof(char)); - optionsFile.read(player2name, 30*sizeof(char)); - //mouseplay? - if (!optionsFile.eof()) - { - optionsFile.read(reinterpret_cast(&mouseplay1), sizeof(bool)); - optionsFile.read(reinterpret_cast(&mouseplay2), sizeof(bool)); - optionsFile.read(reinterpret_cast(&joyplay1),sizeof(bool)); - optionsFile.read(reinterpret_cast(&joyplay2),sizeof(bool)); - } - optionsFile.close(); - cout << "Data loaded from oldstyle options file" << endl; - } - else - { - cout << "Unable to load options file, using default values" << endl; - } - } - -#if NETWORK - strcpy(serverAddress, "192.168.0.2 \0"); - if(configSettings->exists("address0")) - { - strcpy(serverAddress, " \0"); - strncpy(serverAddress,configSettings->getString("address0").c_str(),sizeof(serverAddress)-1); - } -#endif + Joypad_init(); //Prepare the joysticks - if (singlePuzzle) - { - xsize=300; - ysize=600; - } - - - //Open video - if ((bFullscreen)&&(!singlePuzzle)) screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_FULLSCREEN|SDL_ANYFORMAT); - else screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_ANYFORMAT); - - if ( screen == NULL ) - { - cout << "Unable to set " << xsize << "x" << ysize << " video: " << SDL_GetError() << endl; - exit(1); - } - - //Init the file system abstraction layer - PHYSFS_init(argv[0]); - //Load default theme - loadTheme(Config::getInstance()->getString("themename")); - //Now sets the icon: - SDL_Surface *icon = IMG_Load2("gfx/icon.png"); - SDL_WM_SetIcon(icon,NULL); - - cout << "Images loaded" << endl; - - //InitMenues(); - - BlockGameSdl theGame = BlockGameSdl(50,100); //creates game objects - BlockGameSdl theGame2 = BlockGameSdl(xsize-500,100); - player1 = &theGame; - player2 = &theGame2; - /*if (singlePuzzle) - { - theGame.GetTopY()=0; - theGame.GetTopX()=0; - theGame2.GetTopY()=10000; - theGame2.GetTopX()=10000; - }*/ - theGame.DoPaintJob(); //Makes sure what there is something to paint - theGame2.DoPaintJob(); - theGame.SetGameOver(); //sets the game over in the beginning - theGame2.SetGameOver(); + Joypad joypad1 = Joypad(); //Creates a joypad + Joypad joypad2 = Joypad(); //Creates a joypad + theTextManeger = textManeger(); - //Takes names from file instead - strcpy(theGame.name, player1name); - strcpy(theGame2.name, player2name); + //Open Audio + if (!NoSound) //If sound has not been disabled, then load the sound system + if (Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 2048) < 0) + { + cout << "Warning: Couldn't set 44100 Hz 16-bit audio - Reason: " << SDL_GetError() << endl + << "Sound will be disabled!" << endl; + NoSound = true; //Tries to stop all sound from playing/loading + } + + SDL_WM_SetCaption("Block Attack - Rise of the Blocks", NULL); //Sets title line - //Keeps track of background; - int nowTime=SDL_GetTicks(); + //Copyright notice: + cout << "Block Attack - Rise of the Blocks (" << VERSION_NUMBER << ")" << endl << "http://blockattack.sf.net" << endl << "Copyright 2004-2011 Poul Sander" << endl << + "A SDL based game (see www.libsdl.org)" << endl << + "The game is availeble under the GPL, see COPYING for details." << endl; +#if defined(_WIN32) + cout << "Windows build" << endl; +#elif defined(__linux__) + cout << "Linux build" << endl; +#elif defined(__unix__) + cout << "Unix build" << endl; +#else + cout << "Alternative build" << endl; +#endif + cout << "-------------------------------------------" << endl; + + + keySettings[0].up= SDLK_UP; + keySettings[0].down = SDLK_DOWN; + keySettings[0].left = SDLK_LEFT; + keySettings[0].right = SDLK_RIGHT; + keySettings[0].change = SDLK_RCTRL; + keySettings[0].push = SDLK_RSHIFT; + + keySettings[2].up= SDLK_w; + keySettings[2].down = SDLK_s; + keySettings[2].left = SDLK_a; + keySettings[2].right = SDLK_d; + keySettings[2].change = SDLK_LCTRL; + keySettings[2].push = SDLK_LSHIFT; + + player1keys=0; + player2keys=2; + + strcpy(player1name, "Player 1 \0"); + strcpy(player2name, "Player 2 \0"); + + Config *configSettings = Config::getInstance(); + //configSettings->setString("aNumber"," A string"); + //configSettings->save(); + if(configSettings->exists("fullscreen")) //Test if an configFile exists + { + bFullscreen = (bool)configSettings->getInt("fullscreen"); + MusicEnabled = (bool)configSettings->getInt("musicenabled"); + SoundEnabled = (bool)configSettings->getInt("soundenabled"); + mouseplay1 = (bool)configSettings->getInt("mouseplay1"); + mouseplay2 = (bool)configSettings->getInt("mouseplay2"); + joyplay1 = (bool)configSettings->getInt("joypad1"); + joyplay2 = (bool)configSettings->getInt("joypad2"); + + if(configSettings->exists("player1keyup")) keySettings[0].up = (SDLKey)configSettings->getInt("player1keyup"); + if(configSettings->exists("player1keydown")) keySettings[0].down = (SDLKey)configSettings->getInt("player1keydown"); + if(configSettings->exists("player1keyleft")) keySettings[0].left = (SDLKey)configSettings->getInt("player1keyleft"); + if(configSettings->exists("player1keyright")) keySettings[0].right = (SDLKey)configSettings->getInt("player1keyright"); + if(configSettings->exists("player1keychange")) keySettings[0].change = (SDLKey)configSettings->getInt("player1keychange"); + if(configSettings->exists("player1keypush")) keySettings[0].push = (SDLKey)configSettings->getInt("player1keypush"); + + if(configSettings->exists("player2keyup")) keySettings[2].up = (SDLKey)configSettings->getInt("player2keyup"); + if(configSettings->exists("player2keydown")) keySettings[2].down = (SDLKey)configSettings->getInt("player2keydown"); + if(configSettings->exists("player2keyleft")) keySettings[2].left = (SDLKey)configSettings->getInt("player2keyleft"); + if(configSettings->exists("player2keyright")) keySettings[2].right = (SDLKey)configSettings->getInt("player2keyright"); + if(configSettings->exists("player2keychange")) keySettings[2].change = (SDLKey)configSettings->getInt("player2keychange"); + if(configSettings->exists("player2keypush")) keySettings[2].push = (SDLKey)configSettings->getInt("player2keypush"); + if(configSettings->exists("player1name")) + strncpy(player1name,(configSettings->getString("player1name")).c_str(),28); + if(configSettings->exists("player2name")) + strncpy(player2name,(configSettings->getString("player2name")).c_str(),28); + cout << "Data loaded from config file" << endl; + } + else + { + //Reads options from file: + ifstream optionsFile(optionsPath.c_str(), ios::binary); + if (optionsFile) + { + //reads data: xsize,ysize,fullescreen, player1keys, player2keys, MusicEnabled, SoundEnabled,player1name,player2name + optionsFile.read(reinterpret_cast(&xsize), sizeof(int)); + optionsFile.read(reinterpret_cast(&ysize), sizeof(int)); + optionsFile.read(reinterpret_cast(&bFullscreen), sizeof(bool)); + optionsFile.read(reinterpret_cast(&keySettings[0].up), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&keySettings[0].down), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&keySettings[0].left), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&keySettings[0].right), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&keySettings[0].change), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&keySettings[0].push), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&keySettings[2].up), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&keySettings[2].down), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&keySettings[2].left), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&keySettings[2].right), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&keySettings[2].change), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&keySettings[2].push), sizeof(SDLKey)); + optionsFile.read(reinterpret_cast(&MusicEnabled), sizeof(bool)); + optionsFile.read(reinterpret_cast(&SoundEnabled), sizeof(bool)); + optionsFile.read(player1name, 30*sizeof(char)); + optionsFile.read(player2name, 30*sizeof(char)); + //mouseplay? + if (!optionsFile.eof()) + { + optionsFile.read(reinterpret_cast(&mouseplay1), sizeof(bool)); + optionsFile.read(reinterpret_cast(&mouseplay2), sizeof(bool)); + optionsFile.read(reinterpret_cast(&joyplay1),sizeof(bool)); + optionsFile.read(reinterpret_cast(&joyplay2),sizeof(bool)); + } + optionsFile.close(); + cout << "Data loaded from oldstyle options file" << endl; + } + else + { + cout << "Unable to load options file, using default values" << endl; + } + } #if NETWORK - NetworkThing nt = NetworkThing(); - nt.setBGpointers(&theGame,&theGame2); + strcpy(serverAddress, "192.168.0.2 \0"); + if(configSettings->exists("address0")) + { + strcpy(serverAddress, " \0"); + strncpy(serverAddress,configSettings->getString("address0").c_str(),sizeof(serverAddress)-1); + } #endif - if (singlePuzzle) - { - LoadPuzzleStages(); - theGame.NewPuzzleGame(singlePuzzleNr,0,0,SDL_GetTicks()); - showGame = true; - vsMode = true; - } - //Draws everything to screen - if (!editorMode) - MakeBackground(xsize,ysize,&theGame,&theGame2); - else - MakeBackground(xsize,ysize,&theGame); - DrawIMG(background, screen, 0, 0); - DrawEverything(xsize,ysize,&theGame,&theGame2); - SDL_Flip(screen); - //game loop - MainMenu(); + if (singlePuzzle) + { + xsize=300; + ysize=600; + } + //Open video + if ((bFullscreen)&&(!singlePuzzle)) screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_FULLSCREEN|SDL_ANYFORMAT); + else screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_ANYFORMAT); - //Saves options - if (!editorMode) - { - configSettings->setInt("fullscreen",(int)bFullscreen); - configSettings->setInt("musicenabled",(int)MusicEnabled); - configSettings->setInt("soundenabled",(int)SoundEnabled); - configSettings->setInt("mouseplay1",(int)mouseplay1); - configSettings->setInt("mouseplay2",(int)mouseplay2); - configSettings->setInt("joypad1",(int)joyplay1); - configSettings->setInt("joypad2",(int)joyplay2); - - configSettings->setInt("player1keyup",(int)keySettings[0].up); - configSettings->setInt("player1keydown",(int)keySettings[0].down); - configSettings->setInt("player1keyleft",(int)keySettings[0].left); - configSettings->setInt("player1keyright",(int)keySettings[0].right); - configSettings->setInt("player1keychange",(int)keySettings[0].change); - configSettings->setInt("player1keypush",(int)keySettings[0].push); - - configSettings->setInt("player2keyup",(int)keySettings[2].up); - configSettings->setInt("player2keydown",(int)keySettings[2].down); - configSettings->setInt("player2keyleft",(int)keySettings[2].left); - configSettings->setInt("player2keyright",(int)keySettings[2].right); - configSettings->setInt("player2keychange",(int)keySettings[2].change); - configSettings->setInt("player2keypush",(int)keySettings[2].push); - - configSettings->setString("player1name",player1name); - configSettings->setString("player2name",player2name); - configSettings->save(); - } - - //calculate uptime: - //int hours, mins, secs, - commonTime ct = TimeHandler::ms2ct(SDL_GetTicks()); - - //cout << "Block Attack - Rise of the Blocks ran for: " << ct.hours << " hours " << ct.minutes << " mins and " << ct.seconds << " secs" << endl; - cout << boost::format("Block Attack - Rise of the Blocks ran for: %1% hours %2% mins and %3% secs") % ct.hours % ct.minutes % ct.seconds << endl; - - ct = TimeHandler::addTime("totalTime",ct); - - cout << "Total run time is now: " << ct.days << " days " << ct.hours << " hours " << ct.minutes << " mins and " << ct.seconds << " secs" << endl; - - Stats::getInstance()->save(); - - Config::getInstance()->save(); - - //Frees memory from music and fonts - //This is done after writing of configurations and stats since it often crashes the program :( - UnloadImages(); - - //Close file system Apstraction layer! - PHYSFS_deinit(); - return 0; -} + if ( screen == NULL ) + { + cout << "Unable to set " << xsize << "x" << ysize << " video: " << SDL_GetError() << endl; + exit(1); + } + //Init the file system abstraction layer + PHYSFS_init(argv[0]); + //Load default theme + loadTheme(Config::getInstance()->getString("themename")); + //Now sets the icon: + SDL_Surface *icon = IMG_Load2("gfx/icon.png"); + SDL_WM_SetIcon(icon,NULL); -void runGame(int gametype) { - Uint8 *keys; - int mousex, mousey; //Mouse coordinates - showOptions = false; - b1playerOpen = false; - b2playersOpen = false; - bReplayOpen = false; - bScreenLocked = false; - bool vsMode = false; - theTopScoresEndless = Highscore(1); - theTopScoresTimeTrial = Highscore(2); - drawBalls = true; - puzzleLoaded = false; - bool weWhereConnected = false; - - //Things used for repeating keystrokes: - bool repeatingS[2] = {false,false}; - bool repeatingW[2] = {false,false}; - bool repeatingN[2] = {false,false}; - bool repeatingE[2] = {false,false}; - const int startRepeat = 200; - const int repeatDelay = 100; //Repeating - unsigned long timeHeldP1N = 0; - unsigned long timeHeldP1S = 0; - unsigned long timeHeldP1E = 0; - unsigned long timeHeldP1W = 0; - unsigned long timeHeldP2N = 0; - unsigned long timeHeldP2S = 0; - unsigned long timeHeldP2E = 0; - unsigned long timeHeldP2W = 0; - unsigned long timesRepeatedP1N = 0; - unsigned long timesRepeatedP1S = 0; - unsigned long timesRepeatedP1E = 0; - unsigned long timesRepeatedP1W = 0; - unsigned long timesRepeatedP2N = 0; - unsigned long timesRepeatedP2S = 0; - unsigned long timesRepeatedP2E = 0; - unsigned long timesRepeatedP2W = 0; - - theBallManeger = ballManeger(); - theExplosionManeger = explosionManeger(); - BlockGameSdl theGame = BlockGameSdl(50,100); //creates game objects - BlockGameSdl theGame2 = BlockGameSdl(xsize-500,100); - player1 = &theGame; - player2 = &theGame2; - /*if (singlePuzzle) - { - theGame.GetTopY()=0; - theGame.GetTopX()=0; - theGame2.GetTopY()=10000; - theGame2.GetTopX()=10000; - }*/ - theGame.DoPaintJob(); //Makes sure what there is something to paint - theGame2.DoPaintJob(); - theGame.SetGameOver(); //sets the game over in the beginning - theGame2.SetGameOver(); + cout << "Images loaded" << endl; + //InitMenues(); - //Takes names from file instead - strcpy(theGame.name, player1name); - strcpy(theGame2.name, player2name); + BlockGameSdl theGame = BlockGameSdl(50,100); //creates game objects + BlockGameSdl theGame2 = BlockGameSdl(xsize-500,100); + player1 = &theGame; + player2 = &theGame2; + /*if (singlePuzzle) + { + theGame.GetTopY()=0; + theGame.GetTopX()=0; + theGame2.GetTopY()=10000; + theGame2.GetTopX()=10000; + }*/ + theGame.DoPaintJob(); //Makes sure what there is something to paint + theGame2.DoPaintJob(); + theGame.SetGameOver(); //sets the game over in the beginning + theGame2.SetGameOver(); - Joypad joypad1 = Joypad(); //Creates a joypad - Joypad joypad2 = Joypad(); //Creates a joypad + //Takes names from file instead + strcpy(theGame.name, player1name); + strcpy(theGame2.name, player2name); - //Keeps track of background; - int nowTime=SDL_GetTicks(); + //Keeps track of background; + int nowTime=SDL_GetTicks(); #if NETWORK - NetworkThing nt = NetworkThing(); - nt.setBGpointers(&theGame,&theGame2); + NetworkThing nt = NetworkThing(); + nt.setBGpointers(&theGame,&theGame2); #endif - if (singlePuzzle) - { - LoadPuzzleStages(); - theGame.NewPuzzleGame(singlePuzzleNr,0,0,SDL_GetTicks()); - showGame = true; - vsMode = true; - } - //Draws everything to screen - if (!editorMode) - MakeBackground(xsize,ysize,&theGame,&theGame2); - else - MakeBackground(xsize,ysize,&theGame); - DrawIMG(background, screen, 0, 0); - DrawEverything(xsize,ysize,&theGame,&theGame2); - SDL_Flip(screen); - //game loop - int done = 0; - cout << "Starting game loop" << endl; - - - bool mustsetupgame = true; - - while (done == 0) - { - if(mustsetupgame) { - switch(gametype) { - case 1: - StartSinglePlayerTimeTrial(); - break; - case 3: - StartSinglePlayerPuzzle(); - break; - case 4: - { - //1 player - Vs mode - bNewGameOpen = false; - b1playerOpen = false; - int theAIlevel = startSingleVs(); - theGame.NewVsGame(50,100,&theGame2,SDL_GetTicks()); - theGame2.NewVsGame(xsize-500,100,&theGame,SDL_GetTicks()); - MakeBackground(xsize,ysize,&theGame,&theGame2); - DrawIMG(background, screen, 0, 0); - twoPlayers = true; //Single player, but AI plays - showGame = true; - vsMode = true; - theGame2.setAIlevel((Uint8)theAIlevel); - int theTime = time(0); - theGame.putStartBlocks(theTime); - theGame2.putStartBlocks(theTime); - strcpy(theGame.name, player1name); - strcpy(theGame2.name, player2name); - } - break; - case 0: - default: - StartSinglePlayerEndless(); - break; - }; - mustsetupgame = false; - } - - if (!(highPriority)) SDL_Delay(10); + if (singlePuzzle) + { + LoadPuzzleStages(); + theGame.NewPuzzleGame(singlePuzzleNr,0,0,SDL_GetTicks()); + showGame = true; + vsMode = true; + } + //Draws everything to screen + if (!editorMode) + MakeBackground(xsize,ysize,&theGame,&theGame2); + else + MakeBackground(xsize,ysize,&theGame); + DrawIMG(background, screen, 0, 0); + DrawEverything(xsize,ysize,&theGame,&theGame2); + SDL_Flip(screen); + //game loop + MainMenu(); + + + + //Saves options + if (!editorMode) + { + configSettings->setInt("fullscreen",(int)bFullscreen); + configSettings->setInt("musicenabled",(int)MusicEnabled); + configSettings->setInt("soundenabled",(int)SoundEnabled); + configSettings->setInt("mouseplay1",(int)mouseplay1); + configSettings->setInt("mouseplay2",(int)mouseplay2); + configSettings->setInt("joypad1",(int)joyplay1); + configSettings->setInt("joypad2",(int)joyplay2); + + configSettings->setInt("player1keyup",(int)keySettings[0].up); + configSettings->setInt("player1keydown",(int)keySettings[0].down); + configSettings->setInt("player1keyleft",(int)keySettings[0].left); + configSettings->setInt("player1keyright",(int)keySettings[0].right); + configSettings->setInt("player1keychange",(int)keySettings[0].change); + configSettings->setInt("player1keypush",(int)keySettings[0].push); + + configSettings->setInt("player2keyup",(int)keySettings[2].up); + configSettings->setInt("player2keydown",(int)keySettings[2].down); + configSettings->setInt("player2keyleft",(int)keySettings[2].left); + configSettings->setInt("player2keyright",(int)keySettings[2].right); + configSettings->setInt("player2keychange",(int)keySettings[2].change); + configSettings->setInt("player2keypush",(int)keySettings[2].push); + + configSettings->setString("player1name",player1name); + configSettings->setString("player2name",player2name); + configSettings->save(); + } + + //calculate uptime: + //int hours, mins, secs, + commonTime ct = TimeHandler::ms2ct(SDL_GetTicks()); + + //cout << "Block Attack - Rise of the Blocks ran for: " << ct.hours << " hours " << ct.minutes << " mins and " << ct.seconds << " secs" << endl; + cout << boost::format("Block Attack - Rise of the Blocks ran for: %1% hours %2% mins and %3% secs") % ct.hours % ct.minutes % ct.seconds << endl; + + ct = TimeHandler::addTime("totalTime",ct); + + cout << "Total run time is now: " << ct.days << " days " << ct.hours << " hours " << ct.minutes << " mins and " << ct.seconds << " secs" << endl; + + Stats::getInstance()->save(); + + Config::getInstance()->save(); + + //Frees memory from music and fonts + //This is done after writing of configurations and stats since it often crashes the program :( + UnloadImages(); + + //Close file system Apstraction layer! + PHYSFS_deinit(); + return 0; +} - if ((standardBackground)&&(!editorMode)) - { - MakeBackground(xsize,ysize,&theGame,&theGame2); - DrawIMG(background, screen, 0, 0); - } - if ((standardBackground)&&(editorMode)) - { - DrawIMG(backgroundImage, screen, 0, 0); - MakeBackground(xsize,ysize,&theGame); - DrawIMG(background, screen, 0, 0); - } +void runGame(int gametype) +{ + Uint8 *keys; + int mousex, mousey; //Mouse coordinates + showOptions = false; + b1playerOpen = false; + b2playersOpen = false; + bReplayOpen = false; + bScreenLocked = false; + bool vsMode = false; + theTopScoresEndless = Highscore(1); + theTopScoresTimeTrial = Highscore(2); + drawBalls = true; + puzzleLoaded = false; + bool weWhereConnected = false; + + //Things used for repeating keystrokes: + bool repeatingS[2] = {false,false}; + bool repeatingW[2] = {false,false}; + bool repeatingN[2] = {false,false}; + bool repeatingE[2] = {false,false}; + const int startRepeat = 200; + const int repeatDelay = 100; //Repeating + unsigned long timeHeldP1N = 0; + unsigned long timeHeldP1S = 0; + unsigned long timeHeldP1E = 0; + unsigned long timeHeldP1W = 0; + unsigned long timeHeldP2N = 0; + unsigned long timeHeldP2S = 0; + unsigned long timeHeldP2E = 0; + unsigned long timeHeldP2W = 0; + unsigned long timesRepeatedP1N = 0; + unsigned long timesRepeatedP1S = 0; + unsigned long timesRepeatedP1E = 0; + unsigned long timesRepeatedP1W = 0; + unsigned long timesRepeatedP2N = 0; + unsigned long timesRepeatedP2S = 0; + unsigned long timesRepeatedP2E = 0; + unsigned long timesRepeatedP2W = 0; + + theBallManeger = ballManeger(); + theExplosionManeger = explosionManeger(); + BlockGameSdl theGame = BlockGameSdl(50,100); //creates game objects + BlockGameSdl theGame2 = BlockGameSdl(xsize-500,100); + player1 = &theGame; + player2 = &theGame2; + /*if (singlePuzzle) + { + theGame.GetTopY()=0; + theGame.GetTopX()=0; + theGame2.GetTopY()=10000; + theGame2.GetTopX()=10000; + }*/ + theGame.DoPaintJob(); //Makes sure what there is something to paint + theGame2.DoPaintJob(); + theGame.SetGameOver(); //sets the game over in the beginning + theGame2.SetGameOver(); + + + //Takes names from file instead + strcpy(theGame.name, player1name); + strcpy(theGame2.name, player2name); + + + Joypad joypad1 = Joypad(); //Creates a joypad + Joypad joypad2 = Joypad(); //Creates a joypad + + //Keeps track of background; + int nowTime=SDL_GetTicks(); - //updates the balls and explosions: - theBallManeger.update(); - theExplosionManeger.update(); - theTextManeger.update(); #if NETWORK - if (nt.isConnected()) - { - nt.updateNetwork(); - networkActive = true; - if (!nt.isConnectedToPeer()) - DrawIMG(background, screen, 0, 0); - } - else - networkActive = false; - if (nt.isConnectedToPeer()) - { - networkPlay=true; - if (!weWhereConnected) //We have just connected - { - theGame.NewVsGame(50,100,&theGame2,SDL_GetTicks()); - theGame.putStartBlocks(nt.theSeed); - theGame2.playNetwork(xsize-500,100,SDL_GetTicks()); - nt.theGameHasStarted(); - DrawIMG(background, screen, 0, 0); - } - weWhereConnected = true; - } - else - { - networkPlay=false; - weWhereConnected = false; - } + NetworkThing nt = NetworkThing(); + nt.setBGpointers(&theGame,&theGame2); #endif - if (!bScreenLocked) - { - SDL_Event event; + if (singlePuzzle) + { + LoadPuzzleStages(); + theGame.NewPuzzleGame(singlePuzzleNr,0,0,SDL_GetTicks()); + showGame = true; + vsMode = true; + } + //Draws everything to screen + if (!editorMode) + MakeBackground(xsize,ysize,&theGame,&theGame2); + else + MakeBackground(xsize,ysize,&theGame); + DrawIMG(background, screen, 0, 0); + DrawEverything(xsize,ysize,&theGame,&theGame2); + SDL_Flip(screen); + //game loop + int done = 0; + cout << "Starting game loop" << endl; + + + bool mustsetupgame = true; + + while (done == 0) + { + if(mustsetupgame) + { + switch(gametype) + { + case 1: + StartSinglePlayerTimeTrial(); + break; + case 3: + StartSinglePlayerPuzzle(); + break; + case 4: + { + //1 player - Vs mode + bNewGameOpen = false; + b1playerOpen = false; + int theAIlevel = startSingleVs(); + theGame.NewVsGame(50,100,&theGame2,SDL_GetTicks()); + theGame2.NewVsGame(xsize-500,100,&theGame,SDL_GetTicks()); + MakeBackground(xsize,ysize,&theGame,&theGame2); + DrawIMG(background, screen, 0, 0); + twoPlayers = true; //Single player, but AI plays + showGame = true; + vsMode = true; + theGame2.setAIlevel((Uint8)theAIlevel); + int theTime = time(0); + theGame.putStartBlocks(theTime); + theGame2.putStartBlocks(theTime); + strcpy(theGame.name, player1name); + strcpy(theGame2.name, player2name); + } + break; + case 0: + default: + StartSinglePlayerEndless(); + break; + }; + mustsetupgame = false; + } - while ( SDL_PollEvent(&event) ) - { - if ( event.type == SDL_QUIT ) { - Config::getInstance()->setShuttingDown(5); - done = 1; - } + if (!(highPriority)) SDL_Delay(10); - if ( event.type == SDL_KEYDOWN ) - { - if ( event.key.keysym.sym == SDLK_ESCAPE || ( event.key.keysym.sym == SDLK_RETURN && theGame.isGameOver() ) ) - { - if (showOptions) - { - showOptions = false; - } - else - done=1; - DrawIMG(background, screen, 0, 0); + if ((standardBackground)&&(!editorMode)) + { + MakeBackground(xsize,ysize,&theGame,&theGame2); + DrawIMG(background, screen, 0, 0); + } - } - if ((!editorMode)&&(!editorModeTest)&&(!theGame.GetAIenabled())) - { - //player1: - if ( event.key.keysym.sym == keySettings[player1keys].up ) { - theGame.MoveCursor('N'); - repeatingN[0]=true; - timeHeldP1N=SDL_GetTicks(); - timesRepeatedP1N=0; - } - if ( event.key.keysym.sym == keySettings[player1keys].down ) { - theGame.MoveCursor('S'); - repeatingS[0]=true; - timeHeldP1S=SDL_GetTicks(); - timesRepeatedP1S=0; - } - if ( (event.key.keysym.sym == keySettings[player1keys].left) && (showGame) ) { - theGame.MoveCursor('W'); - repeatingW[0]=true; - timeHeldP1W=SDL_GetTicks(); - timesRepeatedP1W=0; - } - if ( (event.key.keysym.sym == keySettings[player1keys].right) && (showGame) ) { - theGame.MoveCursor('E'); - repeatingE[0]=true; - timeHeldP1E=SDL_GetTicks(); - timesRepeatedP1E=0; - } - if ( event.key.keysym.sym == keySettings[player1keys].push ) { - theGame.PushLine(); - } - if ( event.key.keysym.sym == keySettings[player1keys].change ) { - theGame.SwitchAtCursor(); - } - } - if (!editorMode && !theGame2.GetAIenabled()) - { - //player2: - if ( event.key.keysym.sym == keySettings[player2keys].up ) { - theGame2.MoveCursor('N'); - repeatingN[1]=true; - timeHeldP2N=SDL_GetTicks(); - timesRepeatedP2N=0; - } - if ( event.key.keysym.sym == keySettings[player2keys].down ) { - theGame2.MoveCursor('S'); - repeatingS[1]=true; - timeHeldP2S=SDL_GetTicks(); - timesRepeatedP2S=0; - } - if ( (event.key.keysym.sym == keySettings[player2keys].left) && (showGame) ) { - theGame2.MoveCursor('W'); - repeatingW[1]=true; - timeHeldP2W=SDL_GetTicks(); - timesRepeatedP2W=0; - } - if ( (event.key.keysym.sym == keySettings[player2keys].right) && (showGame) ) { - theGame2.MoveCursor('E'); - repeatingE[1]=true; - timeHeldP2E=SDL_GetTicks(); - timesRepeatedP2E=0; - } - if ( event.key.keysym.sym == keySettings[player2keys].push ) { - theGame2.PushLine(); - } - if ( event.key.keysym.sym == keySettings[player2keys].change ) { - theGame2.SwitchAtCursor(); - } - } - //common: - if ((!singlePuzzle)&&(!editorMode)) - { - if ( event.key.keysym.sym == SDLK_F2 ) { - /*#if NETWORK - if ((!showOptions)&&(!networkActive)){ - #else - if ((!showOptions)){ - #endif - StartSinglePlayerEndless(); - } - */ - mustsetupgame = true; - } - if ( event.key.keysym.sym == SDLK_F3 ) { - #if NETWORK - if ((!showOptions)&&(!networkActive)){ - #else - if ((!showOptions)){ - #endif - StartSinglePlayerTimeTrial(); - }} - if ( event.key.keysym.sym == SDLK_F5 ) - { - #if NETWORK - if ((!showOptions)&&(!networkActive)) - #else - if ((!showOptions)) - #endif - { - int myLevel = StageLevelSelect(); - theGame.NewStageGame(myLevel,50,100,SDL_GetTicks()); - MakeBackground(xsize,ysize,&theGame,&theGame2); - DrawIMG(background, screen, 0, 0); - closeAllMenus(); - twoPlayers =false; - theGame2.SetGameOver(); - showGame = true; - vsMode = false; - strcpy(theGame.name, player1name); - strcpy(theGame2.name, player2name); - } - } - if ( event.key.keysym.sym == SDLK_F6 ) - { - #if NETWORK - if ((!showOptions)&&(!networkActive)) - #else - if ((!showOptions)) - #endif - { - StartTwoPlayerVs(); - } - } - if ( event.key.keysym.sym == SDLK_F4 ) - { - #if NETWORK - if ((!showOptions)&&(!networkActive)) - #else - if ((!showOptions)) - #endif - { - StarTwoPlayerTimeTrial(); - } - } - if ( event.key.keysym.sym == SDLK_F7 ) - { - #if NETWORK - if ((!showOptions)&&(!networkActive)) - #else - if ((!showOptions)) - #endif - { - int myLevel = PuzzleLevelSelect(); - theGame.NewPuzzleGame(myLevel,50,100,SDL_GetTicks()); - MakeBackground(xsize,ysize,&theGame,&theGame2); - DrawIMG(background, screen, 0, 0); - closeAllMenus(); - twoPlayers = false; - theGame2.SetGameOver(); - showGame = true; - vsMode = true; - strcpy(theGame.name, player1name); - strcpy(theGame2.name, player2name); - } - } - if ( event.key.keysym.sym == SDLK_F8 ) - { - } - if ( event.key.keysym.sym == SDLK_F9 ) { - writeScreenShot(); - } - if ( event.key.keysym.sym == SDLK_F11 ) { - /*This is the test place, place function to test here*/ - - //theGame.CreateGreyGarbage(); - //char mitNavn[30]; - //SelectThemeDialogbox(300,400,mitNavn); - MainMenu(); - //OpenScoresDisplay(); - } //F11 - } - if ( event.key.keysym.sym == SDLK_F12 ) { - done=1; - } - } - } //while event PollEvent - read keys + if ((standardBackground)&&(editorMode)) + { + DrawIMG(backgroundImage, screen, 0, 0); + MakeBackground(xsize,ysize,&theGame); + DrawIMG(background, screen, 0, 0); + } - /********************************************************************** - **************************** Repeating start ************************** - **********************************************************************/ + //updates the balls and explosions: + theBallManeger.update(); + theExplosionManeger.update(); + theTextManeger.update(); + +#if NETWORK + if (nt.isConnected()) + { + nt.updateNetwork(); + networkActive = true; + if (!nt.isConnectedToPeer()) + DrawIMG(background, screen, 0, 0); + } + else + networkActive = false; + if (nt.isConnectedToPeer()) + { + networkPlay=true; + if (!weWhereConnected) //We have just connected + { + theGame.NewVsGame(50,100,&theGame2,SDL_GetTicks()); + theGame.putStartBlocks(nt.theSeed); + theGame2.playNetwork(xsize-500,100,SDL_GetTicks()); + nt.theGameHasStarted(); + DrawIMG(background, screen, 0, 0); + } + weWhereConnected = true; + } + else + { + networkPlay=false; + weWhereConnected = false; + } +#endif - keys = SDL_GetKeyState(NULL); + if (!bScreenLocked) + { + SDL_Event event; + + while ( SDL_PollEvent(&event) ) + { + if ( event.type == SDL_QUIT ) + { + Config::getInstance()->setShuttingDown(5); + done = 1; + } + + if ( event.type == SDL_KEYDOWN ) + { + if ( event.key.keysym.sym == SDLK_ESCAPE || ( event.key.keysym.sym == SDLK_RETURN && theGame.isGameOver() ) ) + { + if (showOptions) + { + showOptions = false; + } + else + done=1; + DrawIMG(background, screen, 0, 0); + + } + if ((!editorMode)&&(!editorModeTest)&&(!theGame.GetAIenabled())) + { + //player1: + if ( event.key.keysym.sym == keySettings[player1keys].up ) + { + theGame.MoveCursor('N'); + repeatingN[0]=true; + timeHeldP1N=SDL_GetTicks(); + timesRepeatedP1N=0; + } + if ( event.key.keysym.sym == keySettings[player1keys].down ) + { + theGame.MoveCursor('S'); + repeatingS[0]=true; + timeHeldP1S=SDL_GetTicks(); + timesRepeatedP1S=0; + } + if ( (event.key.keysym.sym == keySettings[player1keys].left) && (showGame) ) + { + theGame.MoveCursor('W'); + repeatingW[0]=true; + timeHeldP1W=SDL_GetTicks(); + timesRepeatedP1W=0; + } + if ( (event.key.keysym.sym == keySettings[player1keys].right) && (showGame) ) + { + theGame.MoveCursor('E'); + repeatingE[0]=true; + timeHeldP1E=SDL_GetTicks(); + timesRepeatedP1E=0; + } + if ( event.key.keysym.sym == keySettings[player1keys].push ) + { + theGame.PushLine(); + } + if ( event.key.keysym.sym == keySettings[player1keys].change ) + { + theGame.SwitchAtCursor(); + } + } + if (!editorMode && !theGame2.GetAIenabled()) + { + //player2: + if ( event.key.keysym.sym == keySettings[player2keys].up ) + { + theGame2.MoveCursor('N'); + repeatingN[1]=true; + timeHeldP2N=SDL_GetTicks(); + timesRepeatedP2N=0; + } + if ( event.key.keysym.sym == keySettings[player2keys].down ) + { + theGame2.MoveCursor('S'); + repeatingS[1]=true; + timeHeldP2S=SDL_GetTicks(); + timesRepeatedP2S=0; + } + if ( (event.key.keysym.sym == keySettings[player2keys].left) && (showGame) ) + { + theGame2.MoveCursor('W'); + repeatingW[1]=true; + timeHeldP2W=SDL_GetTicks(); + timesRepeatedP2W=0; + } + if ( (event.key.keysym.sym == keySettings[player2keys].right) && (showGame) ) + { + theGame2.MoveCursor('E'); + repeatingE[1]=true; + timeHeldP2E=SDL_GetTicks(); + timesRepeatedP2E=0; + } + if ( event.key.keysym.sym == keySettings[player2keys].push ) + { + theGame2.PushLine(); + } + if ( event.key.keysym.sym == keySettings[player2keys].change ) + { + theGame2.SwitchAtCursor(); + } + } + //common: + if ((!singlePuzzle)&&(!editorMode)) + { + if ( event.key.keysym.sym == SDLK_F2 ) + { + /*#if NETWORK + if ((!showOptions)&&(!networkActive)){ + #else + if ((!showOptions)){ + #endif + StartSinglePlayerEndless(); + } + */ + mustsetupgame = true; + } + if ( event.key.keysym.sym == SDLK_F3 ) + { +#if NETWORK + if ((!showOptions)&&(!networkActive)) + { +#else + if ((!showOptions)) + { +#endif + StartSinglePlayerTimeTrial(); + } + } + if ( event.key.keysym.sym == SDLK_F5 ) + { +#if NETWORK + if ((!showOptions)&&(!networkActive)) +#else + if ((!showOptions)) +#endif + { + int myLevel = StageLevelSelect(); + theGame.NewStageGame(myLevel,50,100,SDL_GetTicks()); + MakeBackground(xsize,ysize,&theGame,&theGame2); + DrawIMG(background, screen, 0, 0); + closeAllMenus(); + twoPlayers =false; + theGame2.SetGameOver(); + showGame = true; + vsMode = false; + strcpy(theGame.name, player1name); + strcpy(theGame2.name, player2name); + } + } + if ( event.key.keysym.sym == SDLK_F6 ) + { +#if NETWORK + if ((!showOptions)&&(!networkActive)) +#else + if ((!showOptions)) +#endif + { + StartTwoPlayerVs(); + } + } + if ( event.key.keysym.sym == SDLK_F4 ) + { +#if NETWORK + if ((!showOptions)&&(!networkActive)) +#else + if ((!showOptions)) +#endif + { + StarTwoPlayerTimeTrial(); + } + } + if ( event.key.keysym.sym == SDLK_F7 ) + { +#if NETWORK + if ((!showOptions)&&(!networkActive)) +#else + if ((!showOptions)) +#endif + { + int myLevel = PuzzleLevelSelect(); + theGame.NewPuzzleGame(myLevel,50,100,SDL_GetTicks()); + MakeBackground(xsize,ysize,&theGame,&theGame2); + DrawIMG(background, screen, 0, 0); + closeAllMenus(); + twoPlayers = false; + theGame2.SetGameOver(); + showGame = true; + vsMode = true; + strcpy(theGame.name, player1name); + strcpy(theGame2.name, player2name); + } + } + if ( event.key.keysym.sym == SDLK_F8 ) + { + } + if ( event.key.keysym.sym == SDLK_F9 ) + { + writeScreenShot(); + } + if ( event.key.keysym.sym == SDLK_F11 ) + { + /*This is the test place, place function to test here*/ + + //theGame.CreateGreyGarbage(); + //char mitNavn[30]; + //SelectThemeDialogbox(300,400,mitNavn); + MainMenu(); + //OpenScoresDisplay(); + } //F11 + } + if ( event.key.keysym.sym == SDLK_F12 ) + { + done=1; + } + } + } //while event PollEvent - read keys + + /********************************************************************** + **************************** Repeating start ************************** + **********************************************************************/ + + keys = SDL_GetKeyState(NULL); //Also the joysticks: //Repeating not implemented //Player 1 start - if (!(keys[keySettings[player1keys].up])) - repeatingN[0]=false; - while ((repeatingN[0])&&(keys[keySettings[player1keys].up])&&(SDL_GetTicks()>timeHeldP1N+timesRepeatedP1N*repeatDelay+startRepeat)) - { - theGame.MoveCursor('N'); - timesRepeatedP1N++; - } - - if (!(keys[keySettings[player1keys].down])) - repeatingS[0]=false; - while ((repeatingS[0])&&(keys[keySettings[player1keys].down])&&(SDL_GetTicks()>timeHeldP1S+timesRepeatedP1S*repeatDelay+startRepeat)) - { - theGame.MoveCursor('S'); - timesRepeatedP1S++; - } - - if (!(keys[keySettings[player1keys].left])) - repeatingW[0]=false; - while ((repeatingW[0])&&(keys[keySettings[player1keys].left])&&(SDL_GetTicks()>timeHeldP1W+timesRepeatedP1W*repeatDelay+startRepeat)) - { - timesRepeatedP1W++; - theGame.MoveCursor('W'); - } - - if (!(keys[keySettings[player1keys].right])) - repeatingE[0]=false; - while ((repeatingE[0])&&(keys[keySettings[player1keys].right])&&(SDL_GetTicks()>timeHeldP1E+timesRepeatedP1E*repeatDelay+startRepeat)) - { - timesRepeatedP1E++; - theGame.MoveCursor('E'); - } + if (!(keys[keySettings[player1keys].up])) + repeatingN[0]=false; + while ((repeatingN[0])&&(keys[keySettings[player1keys].up])&&(SDL_GetTicks()>timeHeldP1N+timesRepeatedP1N*repeatDelay+startRepeat)) + { + theGame.MoveCursor('N'); + timesRepeatedP1N++; + } + + if (!(keys[keySettings[player1keys].down])) + repeatingS[0]=false; + while ((repeatingS[0])&&(keys[keySettings[player1keys].down])&&(SDL_GetTicks()>timeHeldP1S+timesRepeatedP1S*repeatDelay+startRepeat)) + { + theGame.MoveCursor('S'); + timesRepeatedP1S++; + } + + if (!(keys[keySettings[player1keys].left])) + repeatingW[0]=false; + while ((repeatingW[0])&&(keys[keySettings[player1keys].left])&&(SDL_GetTicks()>timeHeldP1W+timesRepeatedP1W*repeatDelay+startRepeat)) + { + timesRepeatedP1W++; + theGame.MoveCursor('W'); + } + + if (!(keys[keySettings[player1keys].right])) + repeatingE[0]=false; + while ((repeatingE[0])&&(keys[keySettings[player1keys].right])&&(SDL_GetTicks()>timeHeldP1E+timesRepeatedP1E*repeatDelay+startRepeat)) + { + timesRepeatedP1E++; + theGame.MoveCursor('E'); + } //Player 1 end //Player 2 start - if (!(keys[keySettings[player2keys].up])) - repeatingN[1]=false; - while ((repeatingN[1])&&(keys[keySettings[player2keys].up])&&(SDL_GetTicks()>timeHeldP2N+timesRepeatedP2N*repeatDelay+startRepeat)) - { - theGame2.MoveCursor('N'); - timesRepeatedP2N++; - } - - if (!(keys[keySettings[player2keys].down])) - repeatingS[1]=false; - while ((repeatingS[1])&&(keys[keySettings[player2keys].down])&&(SDL_GetTicks()>timeHeldP2S+timesRepeatedP2S*repeatDelay+startRepeat)) - { - theGame2.MoveCursor('S'); - timesRepeatedP2S++; - } - - if (!(keys[keySettings[player2keys].left])) - repeatingW[1]=false; - while ((repeatingW[1])&&(keys[keySettings[player2keys].left])&&(SDL_GetTicks()>timeHeldP2W+timesRepeatedP2W*repeatDelay+startRepeat)) - { - theGame2.MoveCursor('W'); - timesRepeatedP2W++; - } - - if (!(keys[keySettings[player2keys].right])) - repeatingE[1]=false; - while ((repeatingE[1])&&(keys[keySettings[player2keys].right])&&(SDL_GetTicks()>timeHeldP2E+timesRepeatedP2E*repeatDelay+startRepeat)) - { - theGame2.MoveCursor('E'); - timesRepeatedP2E++; - } + if (!(keys[keySettings[player2keys].up])) + repeatingN[1]=false; + while ((repeatingN[1])&&(keys[keySettings[player2keys].up])&&(SDL_GetTicks()>timeHeldP2N+timesRepeatedP2N*repeatDelay+startRepeat)) + { + theGame2.MoveCursor('N'); + timesRepeatedP2N++; + } + + if (!(keys[keySettings[player2keys].down])) + repeatingS[1]=false; + while ((repeatingS[1])&&(keys[keySettings[player2keys].down])&&(SDL_GetTicks()>timeHeldP2S+timesRepeatedP2S*repeatDelay+startRepeat)) + { + theGame2.MoveCursor('S'); + timesRepeatedP2S++; + } + + if (!(keys[keySettings[player2keys].left])) + repeatingW[1]=false; + while ((repeatingW[1])&&(keys[keySettings[player2keys].left])&&(SDL_GetTicks()>timeHeldP2W+timesRepeatedP2W*repeatDelay+startRepeat)) + { + theGame2.MoveCursor('W'); + timesRepeatedP2W++; + } + + if (!(keys[keySettings[player2keys].right])) + repeatingE[1]=false; + while ((repeatingE[1])&&(keys[keySettings[player2keys].right])&&(SDL_GetTicks()>timeHeldP2E+timesRepeatedP2E*repeatDelay+startRepeat)) + { + theGame2.MoveCursor('E'); + timesRepeatedP2E++; + } //Player 2 end - /********************************************************************** - **************************** Repeating end **************************** - **********************************************************************/ - - /********************************************************************** - ***************************** Joypad start **************************** - **********************************************************************/ - - //Gameplay - if (joyplay1||joyplay2) - { - if (joypad1.working && !theGame.GetAIenabled()) - if (joyplay1) - { - joypad1.update(); - if (joypad1.up) - { - theGame.MoveCursor('N'); - repeatingN[0]=true; - timeHeldP1N=SDL_GetTicks(); - timesRepeatedP1N=0; - } - if (joypad1.down) - { - theGame.MoveCursor('S'); - repeatingS[0]=true; - timeHeldP1S=SDL_GetTicks(); - timesRepeatedP1S=0; - } - if (joypad1.left) - { - theGame.MoveCursor('W'); - repeatingW[0]=true; - timeHeldP1W=SDL_GetTicks(); - timesRepeatedP1W=0; - } - if (joypad1.right) - { - theGame.MoveCursor('E'); - repeatingE[0]=true; - timeHeldP1E=SDL_GetTicks(); - timesRepeatedP1E=0; - } - if (joypad1.but1) - theGame.SwitchAtCursor(); - if (joypad1.but2) - theGame.PushLine(); - } - else - { - joypad1.update(); - if (joypad1.up) - { - theGame2.MoveCursor('N'); - repeatingN[1]=true; - timeHeldP2N=SDL_GetTicks(); - timesRepeatedP2N=0; - } - if (joypad1.down) - { - theGame2.MoveCursor('S'); - repeatingS[1]=true; - timeHeldP2S=SDL_GetTicks(); - timesRepeatedP2S=0; - } - if (joypad1.left) - { - theGame2.MoveCursor('W'); - repeatingW[1]=true; - timeHeldP2W=SDL_GetTicks(); - timesRepeatedP2W=0; - } - if (joypad1.right) - { - theGame2.MoveCursor('E'); - repeatingE[1]=true; - timeHeldP2E=SDL_GetTicks(); - timesRepeatedP2E=0; - } - if (joypad1.but1) - theGame2.SwitchAtCursor(); - if (joypad1.but2) - theGame2.PushLine(); - } - if (joypad2.working && !theGame2.GetAIenabled()) - if (!joyplay2) - { - joypad2.update(); - if (joypad2.up) - { - theGame.MoveCursor('N'); - repeatingN[0]=true; - timeHeldP1N=SDL_GetTicks(); - timesRepeatedP1N=0; - } - if (joypad2.down) - { - theGame.MoveCursor('S'); - repeatingS[0]=true; - timeHeldP1S=SDL_GetTicks(); - timesRepeatedP1S=0; - } - if (joypad2.left) - { - theGame.MoveCursor('W'); - repeatingW[0]=true; - timeHeldP1W=SDL_GetTicks(); - timesRepeatedP1W=0; - } - if (joypad2.right) - { - theGame.MoveCursor('E'); - repeatingE[0]=true; - timeHeldP1E=SDL_GetTicks(); - timesRepeatedP1E=0; - } - if (joypad2.but1) - theGame.SwitchAtCursor(); - if (joypad2.but2) - theGame.PushLine(); - } - else - { - joypad2.update(); - if (joypad2.up) - { - theGame2.MoveCursor('N'); - repeatingN[1]=true; - timeHeldP2N=SDL_GetTicks(); - timesRepeatedP2N=0; - } - if (joypad2.down) - { - theGame2.MoveCursor('S'); - repeatingS[1]=true; - timeHeldP2S=SDL_GetTicks(); - timesRepeatedP2S=0; - } - if (joypad2.left) - { - theGame2.MoveCursor('W'); - repeatingW[1]=true; - timeHeldP2W=SDL_GetTicks(); - timesRepeatedP2W=0; - } - if (joypad2.right) - { - theGame2.MoveCursor('E'); - repeatingE[1]=true; - timeHeldP2E=SDL_GetTicks(); - timesRepeatedP2E=0; - } - if (joypad2.but1) - theGame2.SwitchAtCursor(); - if (joypad2.but2) - theGame2.PushLine(); - } - } - - /********************************************************************** - ***************************** Joypad end ****************************** - **********************************************************************/ - - - keys = SDL_GetKeyState(NULL); - - SDL_GetMouseState(&mousex,&mousey); - - /******************************************************************** - **************** Here comes mouse play ****************************** - ********************************************************************/ - - if ((mouseplay1)&&((!editorMode)&&(!theGame.GetAIenabled())||(editorModeTest))) //player 1 - if ((mousex > 50)&&(mousey>100)&&(mousex<50+300)&&(mousey<100+600)) - { - int yLine, xLine; - yLine = ((100+600)-(mousey-100+theGame.GetPixels()))/50; - xLine = (mousex-50+25)/50; - yLine-=2; - xLine-=1; - if ((yLine>10)&&(theGame.GetTowerHeight()<12)) - yLine=10; - if (((theGame.GetPixels()==50)||(theGame.GetPixels()==0)) && (yLine>11)) - yLine=11; - if (yLine<0) - yLine=0; - if (xLine<0) - xLine=0; - if (xLine>4) - xLine=4; - theGame.MoveCursorTo(xLine,yLine); - } - - if ((mouseplay2)&&(!editorMode)&&(!theGame2.GetAIenabled())) //player 2 - if ((mousex > xsize-500)&&(mousey>100)&&(mousex10)&&(theGame2.GetTowerHeight()<12)) - yLine=10; - if (((theGame2.GetPixels()==50)||(theGame2.GetPixels()==0)) && (yLine>11)) - yLine=11; - if (yLine<0) - yLine=0; - if (xLine<0) - xLine=0; - if (xLine>4) - xLine=4; - theGame2.MoveCursorTo(xLine,yLine); - } - - /******************************************************************** - **************** Here ends mouse play ******************************* - ********************************************************************/ - - // If the mouse button is released, make bMouseUp equal true - if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) - { - bMouseUp=true; - } - - // If the mouse button 2 is released, make bMouseUp2 equal true - if ((SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(3))!=SDL_BUTTON(3)) - { - bMouseUp2=true; - } - - if ((!singlePuzzle)&&(!editorMode)) - { - //read mouse events - if (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp) - { - bMouseUp = false; - DrawIMG(background, screen, 0, 0); - - - /******************************************************************** - **************** Here comes mouse play ****************************** - ********************************************************************/ - if ((!showOptions)) - { - if (mouseplay1 && !theGame.GetAIenabled()) //player 1 - if ((mousex > 50)&&(mousey>100)&&(mousex<50+300)&&(mousey<100+600)) - { - theGame.SwitchAtCursor(); - } - if (mouseplay2 && !theGame2.GetAIenabled()) //player 2 - if ((mousex > xsize-500)&&(mousey>100)&&(mousex theGame.GetTopX()+cordNextButton.x) - &&(mousex < theGame.GetTopX()+cordNextButton.x+cordNextButton.xsize) - &&(mousey > theGame.GetTopY()+cordNextButton.y)&&(mousey < theGame.GetTopY()+cordNextButton.y+cordNextButton.ysize)) - { - //Clicked the next button after a stage clear or puzzle - theGame.nextLevel(SDL_GetTicks()); - } - if(stageButtonStatus != SBdontShow && (mousex > theGame.GetTopX()+cordRetryButton .x) - &&(mousex < theGame.GetTopX()+cordRetryButton.x+cordRetryButton.xsize) - &&(mousey > theGame.GetTopY()+cordRetryButton.y)&&(mousey < theGame.GetTopY()+cordRetryButton.y+cordRetryButton.ysize)) - { - //Clicked the retry button - theGame.retryLevel(SDL_GetTicks()); - } - - - //cout << "Mouse x: " << mousex << ", mouse y: " << mousey << endl; - } - - //Mouse button 2: - if ((SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(3))==SDL_BUTTON(3) && bMouseUp2) - { - bMouseUp2=false; //The button is pressed - /******************************************************************** - **************** Here comes mouse play ****************************** - ********************************************************************/ - if (!showOptions) - { - if (mouseplay1 && !theGame.GetAIenabled()) //player 1 - if ((mousex > 50)&&(mousey>100)&&(mousex<50+300)&&(mousey<100+600)) - { - theGame.PushLine(); - } - if (mouseplay2 && !theGame2.GetAIenabled()) //player 2 - if ((mousex > xsize-500)&&(mousey>100)&&(mousex 50)&&(mousey>100)&&(mousex<50+300)&&(mousey<100+600)) + { + int yLine, xLine; + yLine = ((100+600)-(mousey-100+theGame.GetPixels()))/50; + xLine = (mousex-50+25)/50; + yLine-=2; + xLine-=1; + if ((yLine>10)&&(theGame.GetTowerHeight()<12)) + yLine=10; + if (((theGame.GetPixels()==50)||(theGame.GetPixels()==0)) && (yLine>11)) + yLine=11; + if (yLine<0) + yLine=0; + if (xLine<0) + xLine=0; + if (xLine>4) + xLine=4; + theGame.MoveCursorTo(xLine,yLine); + } + + if ((mouseplay2)&&(!editorMode)&&(!theGame2.GetAIenabled())) //player 2 + if ((mousex > xsize-500)&&(mousey>100)&&(mousex10)&&(theGame2.GetTowerHeight()<12)) + yLine=10; + if (((theGame2.GetPixels()==50)||(theGame2.GetPixels()==0)) && (yLine>11)) + yLine=11; + if (yLine<0) + yLine=0; + if (xLine<0) + xLine=0; + if (xLine>4) + xLine=4; + theGame2.MoveCursorTo(xLine,yLine); + } + + /******************************************************************** + **************** Here ends mouse play ******************************* + ********************************************************************/ + + // If the mouse button is released, make bMouseUp equal true + if (!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) + { + bMouseUp=true; + } + + // If the mouse button 2 is released, make bMouseUp2 equal true + if ((SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(3))!=SDL_BUTTON(3)) + { + bMouseUp2=true; + } + + if ((!singlePuzzle)&&(!editorMode)) + { + //read mouse events + if (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp) + { + bMouseUp = false; + DrawIMG(background, screen, 0, 0); + + + /******************************************************************** + **************** Here comes mouse play ****************************** + ********************************************************************/ + if ((!showOptions)) + { + if (mouseplay1 && !theGame.GetAIenabled()) //player 1 + if ((mousex > 50)&&(mousey>100)&&(mousex<50+300)&&(mousey<100+600)) + { + theGame.SwitchAtCursor(); + } + if (mouseplay2 && !theGame2.GetAIenabled()) //player 2 + if ((mousex > xsize-500)&&(mousey>100)&&(mousex theGame.GetTopX()+cordNextButton.x) + &&(mousex < theGame.GetTopX()+cordNextButton.x+cordNextButton.xsize) + &&(mousey > theGame.GetTopY()+cordNextButton.y)&&(mousey < theGame.GetTopY()+cordNextButton.y+cordNextButton.ysize)) + { + //Clicked the next button after a stage clear or puzzle + theGame.nextLevel(SDL_GetTicks()); + } + if(stageButtonStatus != SBdontShow && (mousex > theGame.GetTopX()+cordRetryButton .x) + &&(mousex < theGame.GetTopX()+cordRetryButton.x+cordRetryButton.xsize) + &&(mousey > theGame.GetTopY()+cordRetryButton.y)&&(mousey < theGame.GetTopY()+cordRetryButton.y+cordRetryButton.ysize)) + { + //Clicked the retry button + theGame.retryLevel(SDL_GetTicks()); + } + + + //cout << "Mouse x: " << mousex << ", mouse y: " << mousey << endl; + } + + //Mouse button 2: + if ((SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(3))==SDL_BUTTON(3) && bMouseUp2) + { + bMouseUp2=false; //The button is pressed + /******************************************************************** + **************** Here comes mouse play ****************************** + ********************************************************************/ + if (!showOptions) + { + if (mouseplay1 && !theGame.GetAIenabled()) //player 1 + if ((mousex > 50)&&(mousey>100)&&(mousex<50+300)&&(mousey<100+600)) + { + theGame.PushLine(); + } + if (mouseplay2 && !theGame2.GetAIenabled()) //player 2 + if ((mousex > xsize-500)&&(mousey>100)&&(mousextheGame2.GetScore()+theGame2.GetHandicap()) - theGame.setPlayerWon(); - else - if (theGame.GetScore()+theGame.GetHandicap()theGame2.GetScore()+theGame2.GetHandicap()) + theGame.setPlayerWon(); + else if (theGame.GetScore()+theGame.GetHandicap()setLabel(MusicEnabled? "Music: On" : "Music: Off"); +void runSinglePlayerVs(Button* b) +{ + runGame(4); } -void buttonActionSound(Button* b) { - SoundEnabled = !SoundEnabled; - b->setLabel(SoundEnabled? _("Sound: On") : _("Sound: Off") ); +void buttonActionMusic(Button* b) +{ + MusicEnabled = !MusicEnabled; + b->setLabel(MusicEnabled? "Music: On" : "Music: Off"); } -void buttonActionFullscreen(Button* b) { - bFullscreen = !bFullscreen; - b->setLabel(bFullscreen? _("Fullscreen: On") : _("Fullscreen: Off") ); - ResetFullscreen(); +void buttonActionSound(Button* b) +{ + SoundEnabled = !SoundEnabled; + b->setLabel(SoundEnabled? _("Sound: On") : _("Sound: Off") ); } -void buttonActionPlayer1Name(Button *b) { - if (OpenDialogbox(200,100,player1name)) - return; //must save if true +void buttonActionFullscreen(Button* b) +{ + bFullscreen = !bFullscreen; + b->setLabel(bFullscreen? _("Fullscreen: On") : _("Fullscreen: Off") ); + ResetFullscreen(); } -void buttonActionPlayer2Name(Button *b) { - if (OpenDialogbox(200,100,player2name)) - return; //must save if true +void buttonActionPlayer1Name(Button *b) +{ + if (OpenDialogbox(200,100,player1name)) + return; //must save if true } -void buttonActionHighscores(Button *b) { - OpenScoresDisplay(); +void buttonActionPlayer2Name(Button *b) +{ + if (OpenDialogbox(200,100,player2name)) + return; //must save if true } -static void ChangeKeysMenu(long playernumber) { - Menu km(&screen,_("Change key bindings"),true); - Button_changekey bLeft(&keySettings[playernumber].left,_("Left") ); - Button_changekey bRight(&keySettings[playernumber].right,_("Right") ); - Button_changekey bUp(&keySettings[playernumber].up,_("Up") ); - Button_changekey bDown(&keySettings[playernumber].down,_("Down") ); - Button_changekey bPush(&keySettings[playernumber].push,_("Push") ); - Button_changekey bSwitch(&keySettings[playernumber].change,_("Change") ); - km.addButton(&bLeft); - km.addButton(&bRight); - km.addButton(&bUp); - km.addButton(&bDown); - km.addButton(&bPush); - km.addButton(&bSwitch); - km.run(); +void buttonActionHighscores(Button *b) +{ + OpenScoresDisplay(); } -static void ChangeKeysMenu1(Button *b) { - ChangeKeysMenu(0); +static void ChangeKeysMenu(long playernumber) +{ + Menu km(&screen,_("Change key bindings"),true); + Button_changekey bLeft(&keySettings[playernumber].left,_("Left") ); + Button_changekey bRight(&keySettings[playernumber].right,_("Right") ); + Button_changekey bUp(&keySettings[playernumber].up,_("Up") ); + Button_changekey bDown(&keySettings[playernumber].down,_("Down") ); + Button_changekey bPush(&keySettings[playernumber].push,_("Push") ); + Button_changekey bSwitch(&keySettings[playernumber].change,_("Change") ); + km.addButton(&bLeft); + km.addButton(&bRight); + km.addButton(&bUp); + km.addButton(&bDown); + km.addButton(&bPush); + km.addButton(&bSwitch); + km.run(); +} + +static void ChangeKeysMenu1(Button *b) +{ + ChangeKeysMenu(0); } -static void ChangeKeysMenu2(Button *b) { - ChangeKeysMenu(2); +static void ChangeKeysMenu2(Button *b) +{ + ChangeKeysMenu(2); } -void ConfigureMenu(Button *b) { - Menu cm(&screen,_("Configuration"),true); - Button bMusic,bSound,buttonFullscreen,bPlayer1Name,bPlayer2Name; - Button bPlayer1Keys, bPlayer2Keys; - bMusic.setLabel(MusicEnabled? _("Music: On") : _("Music: Off") ); - bMusic.setAction(buttonActionMusic); - bSound.setLabel(SoundEnabled? _("Music: On") : _("Music: Off") ); - bSound.setAction(buttonActionSound); - buttonFullscreen.setLabel(bFullscreen? _("Fullscreen: On") : _("Fullscreen: Off") ); - buttonFullscreen.setAction(buttonActionFullscreen); - bPlayer1Name.setAction(buttonActionPlayer1Name); - bPlayer1Name.setLabel(_("Change player 1's name") ); - bPlayer2Name.setAction(buttonActionPlayer2Name); - bPlayer2Name.setLabel(_("Change player 2's name") ); - bPlayer1Keys.setAction(ChangeKeysMenu1); - bPlayer1Keys.setLabel(_("Change player 1's keys") ); - bPlayer2Keys.setAction(ChangeKeysMenu2); - bPlayer2Keys.setLabel(_("Change player 2's keys") ); - cm.addButton(&bMusic); - cm.addButton(&bSound); - cm.addButton(&buttonFullscreen); - cm.addButton(&bPlayer1Name); - cm.addButton(&bPlayer2Name); - cm.addButton(&bPlayer1Keys); - cm.addButton(&bPlayer2Keys); - cm.run(); +void ConfigureMenu(Button *b) +{ + Menu cm(&screen,_("Configuration"),true); + Button bMusic,bSound,buttonFullscreen,bPlayer1Name,bPlayer2Name; + Button bPlayer1Keys, bPlayer2Keys; + bMusic.setLabel(MusicEnabled? _("Music: On") : _("Music: Off") ); + bMusic.setAction(buttonActionMusic); + bSound.setLabel(SoundEnabled? _("Music: On") : _("Music: Off") ); + bSound.setAction(buttonActionSound); + buttonFullscreen.setLabel(bFullscreen? _("Fullscreen: On") : _("Fullscreen: Off") ); + buttonFullscreen.setAction(buttonActionFullscreen); + bPlayer1Name.setAction(buttonActionPlayer1Name); + bPlayer1Name.setLabel(_("Change player 1's name") ); + bPlayer2Name.setAction(buttonActionPlayer2Name); + bPlayer2Name.setLabel(_("Change player 2's name") ); + bPlayer1Keys.setAction(ChangeKeysMenu1); + bPlayer1Keys.setLabel(_("Change player 1's keys") ); + bPlayer2Keys.setAction(ChangeKeysMenu2); + bPlayer2Keys.setLabel(_("Change player 2's keys") ); + cm.addButton(&bMusic); + cm.addButton(&bSound); + cm.addButton(&buttonFullscreen); + cm.addButton(&bPlayer1Name); + cm.addButton(&bPlayer2Name); + cm.addButton(&bPlayer1Keys); + cm.addButton(&bPlayer2Keys); + cm.run(); } void MainMenu() { - InitMenues(); - Menu m(&screen,_("Block Attack - Rise of the blocks"),false); - Button bHi,bTimetrial1, bPuzzle, bVs1, bConfigure,bHighscore; - bHi.setLabel(_("Single player - endless") ); - bHi.setAction(runSinglePlayerEndless); - bTimetrial1.setLabel(_("Single player - time trial") ); - bTimetrial1.setAction(runSinglePlayerTimeTrial); - bPuzzle.setLabel(_("Single player - puzzle mode") ); - bPuzzle.setAction(runSinglePlayerPuzzle); - bVs1.setLabel(_("Single player - vs") ); - bVs1.setAction(runSinglePlayerVs); - bConfigure.setLabel(_("Configure") ); - bConfigure.setAction(ConfigureMenu); - bHighscore.setLabel(_("Highscores") ); - bHighscore.setAction(buttonActionHighscores); - m.addButton(&bHi); - m.addButton(&bTimetrial1); - m.addButton(&bPuzzle); - m.addButton(&bVs1); - m.addButton(&bConfigure); - m.addButton(&bHighscore); - m.run(); + InitMenues(); + Menu m(&screen,_("Block Attack - Rise of the blocks"),false); + Button bHi,bTimetrial1, bPuzzle, bVs1, bConfigure,bHighscore; + bHi.setLabel(_("Single player - endless") ); + bHi.setAction(runSinglePlayerEndless); + bTimetrial1.setLabel(_("Single player - time trial") ); + bTimetrial1.setAction(runSinglePlayerTimeTrial); + bPuzzle.setLabel(_("Single player - puzzle mode") ); + bPuzzle.setAction(runSinglePlayerPuzzle); + bVs1.setLabel(_("Single player - vs") ); + bVs1.setAction(runSinglePlayerVs); + bConfigure.setLabel(_("Configure") ); + bConfigure.setAction(ConfigureMenu); + bHighscore.setLabel(_("Highscores") ); + bHighscore.setAction(buttonActionHighscores); + m.addButton(&bHi); + m.addButton(&bTimetrial1); + m.addButton(&bPuzzle); + m.addButton(&bVs1); + m.addButton(&bConfigure); + m.addButton(&bHighscore); + m.run(); } diff --git a/source/code/physfs_stream.hpp b/source/code/physfs_stream.hpp index 0a6f232..0513a34 100644 --- a/source/code/physfs_stream.hpp +++ b/source/code/physfs_stream.hpp @@ -53,382 +53,382 @@ physfs_stream.hpp */ namespace PhysFS { - /** Typedefinitions mandated by the C++ standard in section 27.8.1 - */ - template > - class physfs_filebuf; - typedef physfs_filebuf filebuf; - typedef physfs_filebuf wfilebuf; - - template > - class physfs_ifstream; - typedef physfs_ifstream ifstream; - typedef physfs_ifstream wifstream; - - template > - class physfs_ofstream; - typedef physfs_ofstream ofstream; - typedef physfs_ofstream wofstream; - - /** This class implements a C++ streambuf object for physfs files. - * So that you can use normal istream and ostream operations on them. - * This class is similar to std::basic_filebuf as defined in - * section 27.8.1.1, except in name. - */ - template - class physfs_filebuf : public std::basic_streambuf<_CharT, _Traits> - { - public: - // Types: - typedef _CharT char_type; - typedef _Traits traits_type; - typedef typename traits_type::int_type int_type; - typedef typename traits_type::pos_type pos_type; - typedef typename traits_type::off_type off_type; - - typedef std::basic_streambuf<_CharT, _Traits> __streambuf_type; - typedef physfs_filebuf<_CharT, _Traits> __filebuf_type; - - physfs_filebuf() : - _file(0) - { - _buf.resize(BUF_SIZE); - } - - virtual ~physfs_filebuf() - { - close(); - } - - bool is_open() const throw() - { - return (_file != 0); - } - - __filebuf_type* open(const char* fileName, std::ios_base::openmode mode) - { - // Return failure if this file buf is open already - if (is_open() != false) - return 0; - - // Return failure if we are requested to open a file in an unsupported mode - if (!(mode & std::ios_base::binary) || - (mode & std::ios_base::in && - mode & std::ios_base::out)) - return 0; - - // Open the file - if (mode & std::ios_base::out && - mode & std::ios_base::app) - { - _file = PHYSFS_openAppend(fileName); - _writeStream = true; - } - else if (mode & std::ios_base::out) - { - _file = PHYSFS_openWrite(fileName); - _writeStream = true; - } - else if (mode & std::ios_base::in) - { - _file = PHYSFS_openRead(fileName); - _writeStream = false; - } - else - { - return 0; - } - - if (!_file) - return 0; - - if (mode & std::ios_base::ate && - mode & std::ios_base::in) - { - if (!PHYSFS_seek(_file, PHYSFS_fileLength(_file))) - { - close(); - return 0; - } - } - - return this; - } - - __filebuf_type* close() - { - // Return failure if this file buf is closed already - if (is_open() == false) - return 0; - - sync(); - - if (!PHYSFS_close(_file)) - { - return 0; - } - - _file = 0; - - return this; - } - - protected: - // Read stuff: - virtual int_type underflow() - { - if (!is_open() || _writeStream) - return traits_type::eof(); - - if(PHYSFS_eof(_file)) - { - return traits_type::eof(); - } - - PHYSFS_sint64 objectsRead = PHYSFS_read(_file, &*_buf.begin(), sizeof(char_type), BUF_SIZE); - - if(objectsRead <= 0) - { - return traits_type::eof(); - } - - char_type* xend = (static_cast (objectsRead) == BUF_SIZE) ? &*_buf.end() : &_buf[objectsRead]; - setg(&*_buf.begin(), &*_buf.begin(), xend); - - return traits_type::to_int_type(_buf.front()); - } - - virtual pos_type seekpos(pos_type pos, std::ios_base::openmode) - { - if (!is_open() || _writeStream) - return pos_type(off_type(-1)); - - if(PHYSFS_seek(_file, static_cast (pos)) == 0) - { - return pos_type(off_type(-1)); - } - - // the seek invalidated the buffer - setg(&*_buf.begin(), &*_buf.begin(), &*_buf.begin()); - return pos; - } - - virtual pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode mode) - { - if (!is_open() || _writeStream) - return pos_type(off_type(-1)); - - off_type pos = off; - - switch (dir) - { - case std::ios_base::beg: - break; - - case std::ios_base::cur: - { - PHYSFS_sint64 ptell = PHYSFS_tell(_file); - pos_type buf_tell = static_cast (ptell) - static_cast (__streambuf_type::egptr() - __streambuf_type::gptr()); - if(off == 0) - { - return buf_tell; - } - - pos += static_cast (buf_tell); - break; - } - - case std::ios_base::end: - pos = static_cast (PHYSFS_fileLength(_file)) - pos; - break; - - default: - //assert(!"invalid seekdirection"); - return pos_type(off_type(-1)); - } - - return seekpos(static_cast (pos), mode); - } - - // Write stuff: - virtual int_type overflow(int_type c = traits_type::eof()) - { - if (!is_open() || !_writeStream) - return traits_type::eof(); - - size_t size = __streambuf_type::pptr() - __streambuf_type::pbase(); - if(size == 0) - return 0; - - PHYSFS_sint64 res = PHYSFS_write(_file, __streambuf_type::pbase(), sizeof(char_type), size); - - if(res <= 0) - return traits_type::eof(); - - if(!traits_type::eq_int_type(c, traits_type::eof())) - { - PHYSFS_sint64 res = PHYSFS_write(_file, &c, sizeof(char_type), 1); - - if(res <= 0) - return traits_type::eof(); - } - - char_type* xend = (static_cast (res) == BUF_SIZE) ? &*_buf.end() : &_buf[res]; - setp(&*_buf.begin(), xend); - return 0; - } - - virtual int sync() - { - if (!is_open() || !_writeStream) - return -1; - - return overflow(traits_type::eof()); - } - - virtual std::streamsize showmanyc() - { - if (!is_open() || _writeStream) - return -1; - - PHYSFS_sint64 fileSize = PHYSFS_fileLength(_file); - - return static_cast (fileSize); - } - - private: - PHYSFS_file* _file; - bool _writeStream; - vector _buf; - }; - - /** This class implements a C++ istream object for physfs files. - * This class is similar to std::basic_ifstream as defined in - * section 27.8.1.5, except in name. - */ - template - class physfs_ifstream : public std::basic_istream<_CharT, _Traits> - { - public: - // Types: - typedef _CharT char_type; - typedef _Traits traits_type; - typedef typename traits_type::int_type int_type; - typedef typename traits_type::pos_type pos_type; - typedef typename traits_type::off_type off_type; - - typedef physfs_filebuf<_CharT, _Traits> __filebuf_type; - typedef std::basic_istream<_CharT, _Traits> __istream_type; - - physfs_ifstream() throw() : - __istream_type(&_sb) - { - } - - explicit physfs_ifstream(const char* fileName, std::ios_base::openmode mode = std::ios_base::binary) : - __istream_type(&_sb) - { - open(fileName, mode); - } - - const __filebuf_type* rdbuf() const throw() - { - return &_sb; - } - - __filebuf_type* rdbuf() throw() - { - return &_sb; - } - - bool is_open() const throw() - { - return rdbuf()->is_open(); - } - - void open(const char* fileName, std::ios_base::openmode mode = std::ios_base::binary) - { - if (!rdbuf()->open(fileName, mode | std::ios_base::in)) - { - __istream_type::setstate(std::ios_base::failbit); - } - } - - void close() - { - if (!rdbuf()->close()) - { - __istream_type::setstate(std::ios_base::failbit); - } - } - - private: - __filebuf_type _sb; - }; - - /** This class implements a C++ ostream object for physfs files. - * This class is similar to std::basic_ofstream as defined in - * section 27.8.1.8, except in name. - */ - template - class physfs_ofstream : public std::basic_ostream<_CharT, _Traits> - { - public: - // Types: - typedef _CharT char_type; - typedef _Traits traits_type; - typedef typename traits_type::int_type int_type; - typedef typename traits_type::pos_type pos_type; - typedef typename traits_type::off_type off_type; - - typedef physfs_filebuf<_CharT, _Traits> __filebuf_type; - typedef std::basic_ostream<_CharT, _Traits> __ostream_type; - - physfs_ofstream() throw() : - __ostream_type(&_sb) - { - } - - explicit physfs_ofstream(const char* fileName, std::ios_base::openmode mode = std::ios_base::binary) : - __ostream_type(&_sb) - { - open(fileName, mode); - } - - const __filebuf_type* rdbuf() const throw() - { - return &_sb; - } - - __filebuf_type* rdbuf() throw() - { - return &_sb; - } - - bool is_open() const throw() - { - return rdbuf()->is_open(); - } - - void open(const char* fileName, std::ios_base::openmode mode = std::ios_base::binary) - { - if (!rdbuf()->open(fileName, mode | std::ios_base::out)) - { - __ostream_type::setstate(std::ios_base::failbit); - } - } - - void close() - { - if (!rdbuf()->close()) - { - __ostream_type::setstate(std::ios_base::failbit); - } - } - - private: - __filebuf_type _sb; - }; +/** Typedefinitions mandated by the C++ standard in section 27.8.1 + */ +template > +class physfs_filebuf; +typedef physfs_filebuf filebuf; +typedef physfs_filebuf wfilebuf; + +template > +class physfs_ifstream; +typedef physfs_ifstream ifstream; +typedef physfs_ifstream wifstream; + +template > +class physfs_ofstream; +typedef physfs_ofstream ofstream; +typedef physfs_ofstream wofstream; + +/** This class implements a C++ streambuf object for physfs files. + * So that you can use normal istream and ostream operations on them. + * This class is similar to std::basic_filebuf as defined in + * section 27.8.1.1, except in name. + */ +template +class physfs_filebuf : public std::basic_streambuf<_CharT, _Traits> +{ +public: + // Types: + typedef _CharT char_type; + typedef _Traits traits_type; + typedef typename traits_type::int_type int_type; + typedef typename traits_type::pos_type pos_type; + typedef typename traits_type::off_type off_type; + + typedef std::basic_streambuf<_CharT, _Traits> __streambuf_type; + typedef physfs_filebuf<_CharT, _Traits> __filebuf_type; + + physfs_filebuf() : + _file(0) + { + _buf.resize(BUF_SIZE); + } + + virtual ~physfs_filebuf() + { + close(); + } + + bool is_open() const throw() + { + return (_file != 0); + } + + __filebuf_type* open(const char* fileName, std::ios_base::openmode mode) + { + // Return failure if this file buf is open already + if (is_open() != false) + return 0; + + // Return failure if we are requested to open a file in an unsupported mode + if (!(mode & std::ios_base::binary) || + (mode & std::ios_base::in && + mode & std::ios_base::out)) + return 0; + + // Open the file + if (mode & std::ios_base::out && + mode & std::ios_base::app) + { + _file = PHYSFS_openAppend(fileName); + _writeStream = true; + } + else if (mode & std::ios_base::out) + { + _file = PHYSFS_openWrite(fileName); + _writeStream = true; + } + else if (mode & std::ios_base::in) + { + _file = PHYSFS_openRead(fileName); + _writeStream = false; + } + else + { + return 0; + } + + if (!_file) + return 0; + + if (mode & std::ios_base::ate && + mode & std::ios_base::in) + { + if (!PHYSFS_seek(_file, PHYSFS_fileLength(_file))) + { + close(); + return 0; + } + } + + return this; + } + + __filebuf_type* close() + { + // Return failure if this file buf is closed already + if (is_open() == false) + return 0; + + sync(); + + if (!PHYSFS_close(_file)) + { + return 0; + } + + _file = 0; + + return this; + } + +protected: + // Read stuff: + virtual int_type underflow() + { + if (!is_open() || _writeStream) + return traits_type::eof(); + + if(PHYSFS_eof(_file)) + { + return traits_type::eof(); + } + + PHYSFS_sint64 objectsRead = PHYSFS_read(_file, &*_buf.begin(), sizeof(char_type), BUF_SIZE); + + if(objectsRead <= 0) + { + return traits_type::eof(); + } + + char_type* xend = (static_cast (objectsRead) == BUF_SIZE) ? &*_buf.end() : &_buf[objectsRead]; + setg(&*_buf.begin(), &*_buf.begin(), xend); + + return traits_type::to_int_type(_buf.front()); + } + + virtual pos_type seekpos(pos_type pos, std::ios_base::openmode) + { + if (!is_open() || _writeStream) + return pos_type(off_type(-1)); + + if(PHYSFS_seek(_file, static_cast (pos)) == 0) + { + return pos_type(off_type(-1)); + } + + // the seek invalidated the buffer + setg(&*_buf.begin(), &*_buf.begin(), &*_buf.begin()); + return pos; + } + + virtual pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode mode) + { + if (!is_open() || _writeStream) + return pos_type(off_type(-1)); + + off_type pos = off; + + switch (dir) + { + case std::ios_base::beg: + break; + + case std::ios_base::cur: + { + PHYSFS_sint64 ptell = PHYSFS_tell(_file); + pos_type buf_tell = static_cast (ptell) - static_cast (__streambuf_type::egptr() - __streambuf_type::gptr()); + if(off == 0) + { + return buf_tell; + } + + pos += static_cast (buf_tell); + break; + } + + case std::ios_base::end: + pos = static_cast (PHYSFS_fileLength(_file)) - pos; + break; + + default: + //assert(!"invalid seekdirection"); + return pos_type(off_type(-1)); + } + + return seekpos(static_cast (pos), mode); + } + + // Write stuff: + virtual int_type overflow(int_type c = traits_type::eof()) + { + if (!is_open() || !_writeStream) + return traits_type::eof(); + + size_t size = __streambuf_type::pptr() - __streambuf_type::pbase(); + if(size == 0) + return 0; + + PHYSFS_sint64 res = PHYSFS_write(_file, __streambuf_type::pbase(), sizeof(char_type), size); + + if(res <= 0) + return traits_type::eof(); + + if(!traits_type::eq_int_type(c, traits_type::eof())) + { + PHYSFS_sint64 res = PHYSFS_write(_file, &c, sizeof(char_type), 1); + + if(res <= 0) + return traits_type::eof(); + } + + char_type* xend = (static_cast (res) == BUF_SIZE) ? &*_buf.end() : &_buf[res]; + setp(&*_buf.begin(), xend); + return 0; + } + + virtual int sync() + { + if (!is_open() || !_writeStream) + return -1; + + return overflow(traits_type::eof()); + } + + virtual std::streamsize showmanyc() + { + if (!is_open() || _writeStream) + return -1; + + PHYSFS_sint64 fileSize = PHYSFS_fileLength(_file); + + return static_cast (fileSize); + } + +private: + PHYSFS_file* _file; + bool _writeStream; + vector _buf; +}; + +/** This class implements a C++ istream object for physfs files. + * This class is similar to std::basic_ifstream as defined in + * section 27.8.1.5, except in name. + */ +template +class physfs_ifstream : public std::basic_istream<_CharT, _Traits> +{ +public: + // Types: + typedef _CharT char_type; + typedef _Traits traits_type; + typedef typename traits_type::int_type int_type; + typedef typename traits_type::pos_type pos_type; + typedef typename traits_type::off_type off_type; + + typedef physfs_filebuf<_CharT, _Traits> __filebuf_type; + typedef std::basic_istream<_CharT, _Traits> __istream_type; + + physfs_ifstream() throw() : + __istream_type(&_sb) + { + } + + explicit physfs_ifstream(const char* fileName, std::ios_base::openmode mode = std::ios_base::binary) : + __istream_type(&_sb) + { + open(fileName, mode); + } + + const __filebuf_type* rdbuf() const throw() + { + return &_sb; + } + + __filebuf_type* rdbuf() throw() + { + return &_sb; + } + + bool is_open() const throw() + { + return rdbuf()->is_open(); + } + + void open(const char* fileName, std::ios_base::openmode mode = std::ios_base::binary) + { + if (!rdbuf()->open(fileName, mode | std::ios_base::in)) + { + __istream_type::setstate(std::ios_base::failbit); + } + } + + void close() + { + if (!rdbuf()->close()) + { + __istream_type::setstate(std::ios_base::failbit); + } + } + +private: + __filebuf_type _sb; +}; + +/** This class implements a C++ ostream object for physfs files. + * This class is similar to std::basic_ofstream as defined in + * section 27.8.1.8, except in name. + */ +template +class physfs_ofstream : public std::basic_ostream<_CharT, _Traits> +{ +public: + // Types: + typedef _CharT char_type; + typedef _Traits traits_type; + typedef typename traits_type::int_type int_type; + typedef typename traits_type::pos_type pos_type; + typedef typename traits_type::off_type off_type; + + typedef physfs_filebuf<_CharT, _Traits> __filebuf_type; + typedef std::basic_ostream<_CharT, _Traits> __ostream_type; + + physfs_ofstream() throw() : + __ostream_type(&_sb) + { + } + + explicit physfs_ofstream(const char* fileName, std::ios_base::openmode mode = std::ios_base::binary) : + __ostream_type(&_sb) + { + open(fileName, mode); + } + + const __filebuf_type* rdbuf() const throw() + { + return &_sb; + } + + __filebuf_type* rdbuf() throw() + { + return &_sb; + } + + bool is_open() const throw() + { + return rdbuf()->is_open(); + } + + void open(const char* fileName, std::ios_base::openmode mode = std::ios_base::binary) + { + if (!rdbuf()->open(fileName, mode | std::ios_base::out)) + { + __ostream_type::setstate(std::ios_base::failbit); + } + } + + void close() + { + if (!rdbuf()->close()) + { + __ostream_type::setstate(std::ios_base::failbit); + } + } + +private: + __filebuf_type _sb; +}; } #endif // __INCLUDED_PHYSFS_STREAM_HPP__ diff --git a/source/code/replay.cpp b/source/code/replay.cpp index c3e199b..877ceb5 100644 --- a/source/code/replay.cpp +++ b/source/code/replay.cpp @@ -1,26 +1,24 @@ /* -replay.cpp -Copyright (C) 2005 Poul Sander +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ - Poul Sander - R�veh�jvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ /* @@ -33,255 +31,258 @@ Handles replay Replay::Replay() { - nrOfFrames=0; - isLoaded = false; + nrOfFrames=0; + isLoaded = false; } Replay::Replay(const Replay& r) { - bps = r.bps; - finalPack = r.finalPack; - nrOfFrames = r.nrOfFrames; - isLoaded = r.isLoaded; - theResult = r.theResult; - strncpy(name,r.name,sizeof(name)); + bps = r.bps; + finalPack = r.finalPack; + nrOfFrames = r.nrOfFrames; + isLoaded = r.isLoaded; + theResult = r.theResult; + strncpy(name,r.name,sizeof(name)); } Uint32 Replay::getNumberOfFrames() { - return nrOfFrames; + return nrOfFrames; } void Replay::setFrameSecTo(Uint32 miliseconds, boardPackage bp) { - if (isLoaded) - return; - int framesToSet = (miliseconds*FRAMESPERSEC)/1000; - for (int i=nrOfFrames;i(&version),sizeof(Uint32)); //Fileversion - Uint8 nrOfReplays = 1; - saveFile.write(reinterpret_cast(&nrOfReplays),sizeof(Uint8)); //nrOfReplaysIn File - saveFile.write(reinterpret_cast(&nrOfFrames),sizeof(Uint32)); //Nr of frames in file - for (int i=0; i(&bp),sizeof(bp)); - - } - saveFile.write(reinterpret_cast(&finalPack),sizeof(finalPack)); - saveFile.write(reinterpret_cast(&theResult),sizeof(theResult)); - saveFile.write(reinterpret_cast(&name),sizeof(name)); - saveFile.close(); - return true; - } - else - { - return false; - } + //Saving as fileversion 3 + cout << "Saving as version 3 save file" << endl; + ofstream saveFile; + saveFile.open(filename.c_str(),ios::binary|ios::trunc); + if (saveFile) + { + Uint32 version = 3; + boardPackage bp; + saveFile.write(reinterpret_cast(&version),sizeof(Uint32)); //Fileversion + Uint8 nrOfReplays = 1; + saveFile.write(reinterpret_cast(&nrOfReplays),sizeof(Uint8)); //nrOfReplaysIn File + saveFile.write(reinterpret_cast(&nrOfFrames),sizeof(Uint32)); //Nr of frames in file + for (int i=0; i(&bp),sizeof(bp)); + + } + saveFile.write(reinterpret_cast(&finalPack),sizeof(finalPack)); + saveFile.write(reinterpret_cast(&theResult),sizeof(theResult)); + saveFile.write(reinterpret_cast(&name),sizeof(name)); + saveFile.close(); + return true; + } + else + { + return false; + } } bool Replay::saveReplay(string filename,Replay p2) { - //Saving as fileversion 3 - cout << "Saving as version 3 save file (2 players)" << endl; - ofstream saveFile; - saveFile.open(filename.c_str(),ios::binary|ios::trunc); - if (saveFile) - { - Uint32 version = 3; - boardPackage bp; - saveFile.write(reinterpret_cast(&version),sizeof(Uint32)); //Fileversion - Uint8 nrOfReplays = 2; - saveFile.write(reinterpret_cast(&nrOfReplays),sizeof(Uint8)); //nrOfReplaysIn File - saveFile.write(reinterpret_cast(&nrOfFrames),sizeof(Uint32)); //Nr of frames in file - for (int i=0; i(&bp),sizeof(bp)); - } - saveFile.write(reinterpret_cast(&finalPack),sizeof(finalPack)); - saveFile.write(reinterpret_cast(&theResult),sizeof(theResult)); - saveFile.write(reinterpret_cast(&name),sizeof(name)); - ///Player 2 starts here!!!!!!!!!!!!!!!!!!!!!! - saveFile.write(reinterpret_cast(&p2.nrOfFrames),sizeof(Uint32)); //Nr of frames in file - for (int i=0; (i(&bp),sizeof(bp)); - } - saveFile.write(reinterpret_cast(&p2.finalPack),sizeof(finalPack)); - saveFile.write(reinterpret_cast(&p2.theResult),sizeof(theResult)); - saveFile.write(reinterpret_cast(&p2.name),sizeof(name)); - saveFile.close(); - return true; - } - else - { - return false; - } + //Saving as fileversion 3 + cout << "Saving as version 3 save file (2 players)" << endl; + ofstream saveFile; + saveFile.open(filename.c_str(),ios::binary|ios::trunc); + if (saveFile) + { + Uint32 version = 3; + boardPackage bp; + saveFile.write(reinterpret_cast(&version),sizeof(Uint32)); //Fileversion + Uint8 nrOfReplays = 2; + saveFile.write(reinterpret_cast(&nrOfReplays),sizeof(Uint8)); //nrOfReplaysIn File + saveFile.write(reinterpret_cast(&nrOfFrames),sizeof(Uint32)); //Nr of frames in file + for (int i=0; i(&bp),sizeof(bp)); + } + saveFile.write(reinterpret_cast(&finalPack),sizeof(finalPack)); + saveFile.write(reinterpret_cast(&theResult),sizeof(theResult)); + saveFile.write(reinterpret_cast(&name),sizeof(name)); + ///Player 2 starts here!!!!!!!!!!!!!!!!!!!!!! + saveFile.write(reinterpret_cast(&p2.nrOfFrames),sizeof(Uint32)); //Nr of frames in file + for (int i=0; (i(&bp),sizeof(bp)); + } + saveFile.write(reinterpret_cast(&p2.finalPack),sizeof(finalPack)); + saveFile.write(reinterpret_cast(&p2.theResult),sizeof(theResult)); + saveFile.write(reinterpret_cast(&p2.name),sizeof(name)); + saveFile.close(); + return true; + } + else + { + return false; + } } bool Replay::loadReplay(string filename) { - isLoaded = true; - ifstream loadFile; - loadFile.open(filename.c_str(),ios::binary); - if (loadFile) - { - Uint32 version; - loadFile.read(reinterpret_cast(&version),sizeof(Uint32)); - switch (version) - { - case 3: - cout << "Loading a version 3 save game" << endl; - Uint8 nrOfPlayers; - boardPackage bp; - loadFile.read(reinterpret_cast(&nrOfPlayers),sizeof(Uint8)); - loadFile.read(reinterpret_cast(&nrOfFrames),sizeof(Uint32)); - bps.clear(); - for (int i=0; (i(&bp),sizeof(bp)); - bps.push_back(bp); - } - loadFile.read(reinterpret_cast(&finalPack),sizeof(finalPack)); - loadFile.read(reinterpret_cast(&theResult),sizeof(theResult)); - loadFile.read(reinterpret_cast(&name),sizeof(name)); - break; - default: - cout << "Unknown version" << endl; - return false; - }; - loadFile.close(); - cout << "Loaded 1 player" << endl; - } - else - { - cout << "File not found or couldn't open: " << filename << endl; - return false; - } + isLoaded = true; + ifstream loadFile; + loadFile.open(filename.c_str(),ios::binary); + if (loadFile) + { + Uint32 version; + loadFile.read(reinterpret_cast(&version),sizeof(Uint32)); + switch (version) + { + case 3: + cout << "Loading a version 3 save game" << endl; + Uint8 nrOfPlayers; + boardPackage bp; + loadFile.read(reinterpret_cast(&nrOfPlayers),sizeof(Uint8)); + loadFile.read(reinterpret_cast(&nrOfFrames),sizeof(Uint32)); + bps.clear(); + for (int i=0; (i(&bp),sizeof(bp)); + bps.push_back(bp); + } + loadFile.read(reinterpret_cast(&finalPack),sizeof(finalPack)); + loadFile.read(reinterpret_cast(&theResult),sizeof(theResult)); + loadFile.read(reinterpret_cast(&name),sizeof(name)); + break; + default: + cout << "Unknown version" << endl; + return false; + }; + loadFile.close(); + cout << "Loaded 1 player" << endl; + } + else + { + cout << "File not found or couldn't open: " << filename << endl; + return false; + } } bool Replay::loadReplay2(string filename) { - isLoaded = true; - ifstream loadFile; - loadFile.open(filename.c_str(),ios::binary); - if (loadFile) - { - Uint32 version; - loadFile.read(reinterpret_cast(&version),sizeof(Uint32)); - switch (version) - { - case 3: - Uint8 nrOfPlayers; - boardPackage bp; - loadFile.read(reinterpret_cast(&nrOfPlayers),sizeof(Uint8)); - if (nrOfPlayers<2) - { - loadFile.close(); - cout << "Only one player in replay" << endl; - return false; - } - cout << "loading player 2" << endl; - loadFile.read(reinterpret_cast(&nrOfFrames),sizeof(Uint32)); - for (int i=0; (i(&bp),sizeof(bp)); - //bps.push_back(bp); We have already read player 1 with another function - } - loadFile.read(reinterpret_cast(&finalPack),sizeof(finalPack)); - loadFile.read(reinterpret_cast(&theResult),sizeof(theResult)); - loadFile.read(reinterpret_cast(&name),sizeof(name)); - loadFile.read(reinterpret_cast(&nrOfFrames),sizeof(Uint32)); - bps.reserve(nrOfFrames); - for (int i=0; (i(&bp),sizeof(bp)); - bps.push_back(bp); - } - loadFile.read(reinterpret_cast(&finalPack),sizeof(finalPack)); - loadFile.read(reinterpret_cast(&theResult),sizeof(theResult)); - loadFile.read(reinterpret_cast(&name),sizeof(name)); - break; - default: - cout << "Unknown version: " << version << endl; - return false; - }; - loadFile.close(); - } - else - { - cout << "File not found or couldn't open: " << filename << endl; - return false; - } + isLoaded = true; + ifstream loadFile; + loadFile.open(filename.c_str(),ios::binary); + if (loadFile) + { + Uint32 version; + loadFile.read(reinterpret_cast(&version),sizeof(Uint32)); + switch (version) + { + case 3: + Uint8 nrOfPlayers; + boardPackage bp; + loadFile.read(reinterpret_cast(&nrOfPlayers),sizeof(Uint8)); + if (nrOfPlayers<2) + { + loadFile.close(); + cout << "Only one player in replay" << endl; + return false; + } + cout << "loading player 2" << endl; + loadFile.read(reinterpret_cast(&nrOfFrames),sizeof(Uint32)); + for (int i=0; (i(&bp),sizeof(bp)); + //bps.push_back(bp); We have already read player 1 with another function + } + loadFile.read(reinterpret_cast(&finalPack),sizeof(finalPack)); + loadFile.read(reinterpret_cast(&theResult),sizeof(theResult)); + loadFile.read(reinterpret_cast(&name),sizeof(name)); + loadFile.read(reinterpret_cast(&nrOfFrames),sizeof(Uint32)); + bps.reserve(nrOfFrames); + for (int i=0; (i(&bp),sizeof(bp)); + bps.push_back(bp); + } + loadFile.read(reinterpret_cast(&finalPack),sizeof(finalPack)); + loadFile.read(reinterpret_cast(&theResult),sizeof(theResult)); + loadFile.read(reinterpret_cast(&name),sizeof(name)); + break; + default: + cout << "Unknown version: " << version << endl; + return false; + }; + loadFile.close(); + } + else + { + cout << "File not found or couldn't open: " << filename << endl; + return false; + } } diff --git a/source/code/replay.h b/source/code/replay.h index 23b9daa..24c21f4 100644 --- a/source/code/replay.h +++ b/source/code/replay.h @@ -1,26 +1,24 @@ /* -replay.h -Copyright (C) 2005 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - R�veh�jvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ //headerfile for replay.h @@ -46,52 +44,53 @@ using namespace std; //board_package, stores a board can be used for network play and replay struct boardPackage //92 bytes { - Uint32 time; //game time - Uint8 brick[6][13]; - Uint8 pixels; //pixels pushed - Uint8 cursorX; //Cursor coordinate - Uint8 cursorY; // -||- - Uint32 score; - Uint8 speed; - Uint8 chain; - Uint8 result; //0=none,1=gameOver,2=winner,4=draw + Uint32 time; //game time + Uint8 brick[6][13]; + Uint8 pixels; //pixels pushed + Uint8 cursorX; //Cursor coordinate + Uint8 cursorY; // -||- + Uint32 score; + Uint8 speed; + Uint8 chain; + Uint8 result; //0=none,1=gameOver,2=winner,4=draw }; -class Replay{ +class Replay +{ private: //Our replay is stored in an array of TOTALFRAMES length - //boardPackage bps[TOTALFRAMES]; - vector bps; + //boardPackage bps[TOTALFRAMES]; + vector bps; //The final package is not set to any specific time - boardPackage finalPack; + boardPackage finalPack; //We store number of frames, so we know how long to read the array - Uint32 nrOfFrames; + Uint32 nrOfFrames; //An enumerator, so we know how it ends! (should be removed then boardPackage is the 92 byte version) - enum { gameOver=0, winner, looser, draw } theResult; + enum { gameOver=0, winner, looser, draw } theResult; //If we are loaded from a file, then we are read only - bool isLoaded; + bool isLoaded; public: - - //Store player name - char name[30]; - - Replay(); //Constructor - Replay(const Replay& r); //Copy constructor - Uint32 getNumberOfFrames(); //Returns number of frames - void setFrameSecTo(Uint32,boardPackage); //Sets frame at a given time to the package - void setFinalFrame(boardPackage,int); //Sets the final package - boardPackage getFrameSec(Uint32); //Gets a frame to a time - boardPackage getFinalFrame(); //Gets the last frame, that must remain - int getFinalStatus(); //Return the result: winner, looser, draw or gameOver - bool isFinnished(Uint32); //Returns true if we are done + + //Store player name + char name[30]; + + Replay(); //Constructor + Replay(const Replay& r); //Copy constructor + Uint32 getNumberOfFrames(); //Returns number of frames + void setFrameSecTo(Uint32,boardPackage); //Sets frame at a given time to the package + void setFinalFrame(boardPackage,int); //Sets the final package + boardPackage getFrameSec(Uint32); //Gets a frame to a time + boardPackage getFinalFrame(); //Gets the last frame, that must remain + int getFinalStatus(); //Return the result: winner, looser, draw or gameOver + bool isFinnished(Uint32); //Returns true if we are done //Ok, I'll ignore this for some time, and just save to file, if however, we ever use a dynamic saving structure, we are fucked - bool saveReplay(string); //Saves a replay - bool saveReplay(string,Replay p2); //saves a replay, plus another replay given as a parameter - bool loadReplay(string); //laods a replay - bool loadReplay2(string); //loads the second part of the replay file, if it exists, returns false otherwise + bool saveReplay(string); //Saves a replay + bool saveReplay(string,Replay p2); //saves a replay, plus another replay given as a parameter + bool loadReplay(string); //laods a replay + bool loadReplay2(string); //loads the second part of the replay file, if it exists, returns false otherwise }; diff --git a/source/code/stats.cc b/source/code/stats.cc index a12bd6c..3306daa 100644 --- a/source/code/stats.cc +++ b/source/code/stats.cc @@ -1,27 +1,24 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2008 Poul Sander +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ - Poul Sander - R�vehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include "stats.h" @@ -31,80 +28,80 @@ Stats* Stats::instance = NULL; Stats::Stats() { - statMap.clear(); - load(); + statMap.clear(); + load(); } void Stats::load() { - string filename = getPathToSaveFiles()+"/statsFile"; - ifstream inFile(filename.c_str()); - string key; - char value[MAX_VAR_LENGTH]; - if(inFile) - { - while(!inFile.eof()) - { - inFile >> key; // The key is first on line - inFile.get(); //Take the space - inFile.getline(value,MAX_VAR_LENGTH); //The rest of the line is the value. - statMap[key] = str2int(value); - } - inFile.close(); - } + string filename = getPathToSaveFiles()+"/statsFile"; + ifstream inFile(filename.c_str()); + string key; + char value[MAX_VAR_LENGTH]; + if(inFile) + { + while(!inFile.eof()) + { + inFile >> key; // The key is first on line + inFile.get(); //Take the space + inFile.getline(value,MAX_VAR_LENGTH); //The rest of the line is the value. + statMap[key] = str2int(value); + } + inFile.close(); + } } Stats* Stats::getInstance() { - if(Stats::instance==NULL) - { - Stats::instance = new Stats(); - - } - return Stats::instance; + if(Stats::instance==NULL) + { + Stats::instance = new Stats(); + + } + return Stats::instance; } void Stats::save() { - string filename = getPathToSaveFiles()+"/statsFile"; - ofstream outFile(filename.c_str(),ios::trunc); - - if(outFile) - { - //outFile << statMap.size() << endl; - map::iterator iter; - for(iter = statMap.begin(); iter != statMap.end(); iter++) - { - outFile << iter->first << " " << iter->second << endl; - } - } + string filename = getPathToSaveFiles()+"/statsFile"; + ofstream outFile(filename.c_str(),ios::trunc); + + if(outFile) + { + //outFile << statMap.size() << endl; + map::iterator iter; + for(iter = statMap.begin(); iter != statMap.end(); iter++) + { + outFile << iter->first << " " << iter->second << endl; + } + } } unsigned int Stats::getNumberOf(string statName) { - if(exists(statName)) - { - return statMap[statName]; - } - else - return 0; + if(exists(statName)) + { + return statMap[statName]; + } + else + return 0; } void Stats::addOne(string statName) { - map::iterator iter = statMap.find(statName); - if(iter == statMap.end()) - { - statMap[statName] = 1; - } - else - { - iter->second++; - } + map::iterator iter = statMap.find(statName); + if(iter == statMap.end()) + { + statMap[statName] = 1; + } + else + { + iter->second++; + } } bool Stats::exists(string statName) { - //Using that 'find' returns an iterator to the end of the map if not found - return statMap.find(statName) != statMap.end(); + //Using that 'find' returns an iterator to the end of the map if not found + return statMap.find(statName) != statMap.end(); } diff --git a/source/code/stats.h b/source/code/stats.h index 8bf93a9..8c6bb44 100644 --- a/source/code/stats.h +++ b/source/code/stats.h @@ -1,30 +1,27 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2008 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - R�vehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ -// +// // File: stats.h // Author: poul // @@ -44,30 +41,30 @@ using namespace std; class Stats { -private: - map statMap; +private: + map statMap; + + static Stats *instance; - static Stats *instance; - - void load(); + void load(); protected: - - Stats(); - - + + Stats(); + + public: - - static Stats* getInstance(); - - void save(); - - unsigned int getNumberOf(string statName); - - void addOne(string statName); - - bool exists(string statName); - - + + static Stats* getInstance(); + + void save(); + + unsigned int getNumberOf(string statName); + + void addOne(string statName); + + bool exists(string statName); + + }; #endif /* _STATS_H */ diff --git a/source/code/ttfont.cc b/source/code/ttfont.cc index 608c1d2..46fe677 100644 --- a/source/code/ttfont.cc +++ b/source/code/ttfont.cc @@ -1,27 +1,24 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2008 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - R�vehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include "ttfont.h" @@ -32,88 +29,112 @@ Copyright (C) 2008 Poul Sander TTFont::TTFont() { - font = NULL; - actualInstance = false; + font = NULL; + actualInstance = false; } int TTFont::count = 0; TTFont::TTFont(TTF_Font *f) { - if(!(TTF_WasInit())) - { - //Init TTF for the first time - TTF_Init(); - } - - - if(f == NULL) - cout << "Font was null!" << endl; - - actualInstance = false; //We have not yet copied to final location - font = f; - + if(!(TTF_WasInit())) + { + //Init TTF for the first time + TTF_Init(); + } + + + if(f == NULL) + cout << "Font was null!" << endl; + + actualInstance = false; //We have not yet copied to final location + font = f; + } TTFont::~TTFont() { - if(!actualInstance) - return; - - cout << "Closing a font" << endl; - - TTF_CloseFont(font); - font = NULL; - - count--; - if(count==0) - TTF_Quit(); + if(!actualInstance) + return; + + cout << "Closing a font" << endl; + + TTF_CloseFont(font); + font = NULL; + + count--; + if(count==0) + TTF_Quit(); } //Copy constructor, you cannot copy an actual instance TTFont::TTFont(const TTFont &t) { - if(t.font == NULL || t.actualInstance) - { - font = NULL; - actualInstance = false; - } - else - { - font = t.font; - actualInstance = true; - count++; - } + if(t.font == NULL || t.actualInstance) + { + font = NULL; + ac/* +Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack +Copyright (C) 2008 Poul Sander + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Poul Sander + R�vehjvej 36, V. 1111 + 2800 Kgs. Lyngby + DENMARK + blockattack@poulsander.com + http://blockattack.sf.net +*/tualInstance = false; + } + else + { + font = t.font; + actualInstance = true; + count++; + } } int TTFont::getTextHeight() { - return TTF_FontHeight(font); + return TTF_FontHeight(font); } int TTFont::getTextWidth(string text) { - int width = 0; - if(TTF_SizeText(font,text.c_str(),&width,NULL)!=0) - cout << "Failed to get text width!" << endl; - return width; + int width = 0; + if(TTF_SizeText(font,text.c_str(),&width,NULL)!=0) + cout << "Failed to get text width!" << endl; + return width; } void TTFont::writeText(string text, SDL_Surface *target, int x, int y) { - SDL_Surface *text_surface; - SDL_Color color={255,255,255}; - if(!(text_surface=TTF_RenderText_Solid(font,text.c_str(), color))) - { - cout << "Error writing text: " << TTF_GetError() << endl; - } - else - { - SDL_Rect dest; - dest.x = x; - dest.y = y; - SDL_BlitSurface(text_surface,NULL,target,&dest); - SDL_FreeSurface(text_surface); - } + SDL_Surface *text_surface; + SDL_Color color= {255,255,255}; + if(!(text_surface=TTF_RenderText_Solid(font,text.c_str(), color))) + { + cout << "Error writing text: " << TTF_GetError() << endl; + } + else + { + SDL_Rect dest; + dest.x = x; + dest.y = y; + SDL_BlitSurface(text_surface,NULL,target,&dest); + SDL_FreeSurface(text_surface); + } } diff --git a/source/code/ttfont.h b/source/code/ttfont.h index 3292c89..d1cff5c 100644 --- a/source/code/ttfont.h +++ b/source/code/ttfont.h @@ -1,30 +1,27 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2008 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - R�vehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ -// +// // File: ttfont.hpp.h // Author: poul // @@ -45,20 +42,20 @@ using namespace std; class TTFont { private: - static int count; //The total number of instances - TTF_Font *font; - bool actualInstance; - + static int count; //The total number of instances + TTF_Font *font; + bool actualInstance; + public: - TTFont(); - TTFont(TTF_Font *f); - TTFont(const TTFont &t); - ~TTFont(); - - int getTextWidth(string text); - int getTextHeight(); - void writeText(string text, SDL_Surface *target, int x, int y); - + TTFont(); + TTFont(TTF_Font *f); + TTFont(const TTFont &t); + ~TTFont(); + + int getTextWidth(string text); + int getTextHeight(); + void writeText(string text, SDL_Surface *target, int x, int y); + }; #endif /* _TTFONT_H */ diff --git a/source/code/uploadReplay.cc b/source/code/uploadReplay.cc index 22ae53e..61519e2 100644 --- a/source/code/uploadReplay.cc +++ b/source/code/uploadReplay.cc @@ -1,27 +1,24 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2008 Poul Sander +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ - Poul Sander - R�vehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ #include "uploadReplay.h" @@ -35,54 +32,55 @@ SDL_Thread *threadThresholdFile; void uploadReplay_init() { - if(uploadReplayInitialized) - return; - //mutDownload = SDL_CreateMutex(); - mutUpload = SDL_CreateMutex(); - thresholdUp2Date = false; + if(uploadReplayInitialized) + return; + //mutDownload = SDL_CreateMutex(); + mutUpload = SDL_CreateMutex(); + thresholdUp2Date = false; } int downloadThresholdFile(void *ptr) { - //if(SDL_mutexP(mutDownload)==-1){ - // isDownloading = false; - // return -1; //We don't crash if we can't lock. Just failing to do so - //} - FILE *outfile; - CURL *easyhandle = curl_easy_init(); - if(!easyhandle){ - isDownloading=false; - //SDL_mutexV(mutDownload); - return -1; - } - string filename = getPathToSaveFiles()+"/scoreThreshold"; - outfile = fopen(filename.c_str(), "w"); - - curl_easy_setopt(easyhandle, CURLOPT_URL, "http://localhost/~poul/blockattackHighscores/result/threshold"); - curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, outfile); - - CURLcode res = curl_easy_perform(easyhandle); + //if(SDL_mutexP(mutDownload)==-1){ + // isDownloading = false; + // return -1; //We don't crash if we can't lock. Just failing to do so + //} + FILE *outfile; + CURL *easyhandle = curl_easy_init(); + if(!easyhandle) + { + isDownloading=false; + //SDL_mutexV(mutDownload); + return -1; + } + string filename = getPathToSaveFiles()+"/scoreThreshold"; + outfile = fopen(filename.c_str(), "w"); - fclose(outfile); + curl_easy_setopt(easyhandle, CURLOPT_URL, "http://localhost/~poul/blockattackHighscores/result/threshold"); + curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, outfile); - if(res == 200) - thresholdUp2Date = true; - - curl_easy_cleanup(easyhandle); - isDownloading=false; - //if(SDL_mutexV(mutDownload)==-1){ - //return 0; //We don't crash if we can't lock. Just failing to do so - //} - return 0; + CURLcode res = curl_easy_perform(easyhandle); + + fclose(outfile); + + if(res == 200) + thresholdUp2Date = true; + + curl_easy_cleanup(easyhandle); + isDownloading=false; + //if(SDL_mutexV(mutDownload)==-1){ + //return 0; //We don't crash if we can't lock. Just failing to do so + //} + return 0; } bool uploadReplay_canUpload() { - if(thresholdUp2Date) - return true; - if(isDownloading) - return false; - isDownloading=true; //We mark before start the thread - threadThresholdFile = SDL_CreateThread(downloadThresholdFile, NULL); - return thresholdUp2Date; + if(thresholdUp2Date) + return true; + if(isDownloading) + return false; + isDownloading=true; //We mark before start the thread + threadThresholdFile = SDL_CreateThread(downloadThresholdFile, NULL); + return thresholdUp2Date; } diff --git a/source/code/uploadReplay.h b/source/code/uploadReplay.h index 20ad861..a81eb40 100644 --- a/source/code/uploadReplay.h +++ b/source/code/uploadReplay.h @@ -1,35 +1,26 @@ /* -Block Attack - Rise of the Blocks, SDL game, besed on Nintendo's Tetris Attack -Copyright (C) 2008 Poul Sander - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Poul Sander - R�vehjvej 36, V. 1111 - 2800 Kgs. Lyngby - DENMARK - blockattack@poulsander.com - http://blockattack.sf.net +=========================================================================== +blockattack - Block Attack - Rise of the Blocks +Copyright (C) 2005-2012 Poul Sander + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see http://www.gnu.org/licenses/ + +Source information and contacts persons can be found at +http://blockattack.sf.net +=========================================================================== */ -// -// File: uploadReplay.h -// Author: poul -// -// Created on 26. februar 2008, 00:12 -// #ifndef _UPLOADREPLAY_H #define _UPLOADREPLAY_H @@ -44,13 +35,13 @@ using namespace std; SDL_mutex *mutDownload,*mutUpload; bool uploadReplay_canUpload(); - + void uploadReplay_upload(); - - + + class OnlineHighscores { - + }; #endif /* _UPLOADREPLAY_H */