commit ecef5838
Changed a lot of formatting
Changed files
diff --git a/source/code/BlockGame.cpp b/source/code/BlockGame.cpp
index 016bd9f..0f366ab 100644
--- a/source/code/BlockGame.cpp
+++ b/source/code/BlockGame.cpp
@@ -41,29 +41,27 @@ static stringstream ss; //Used for internal formatting
////////////////////////////////////////////////////////////////////////////////
//The BloackGame class represents a board, score, time etc. for a single player/
////////////////////////////////////////////////////////////////////////////////
-Uint16 BlockGame::rand2()
-{
+Uint16 BlockGame::rand2() {
nextRandomNumber = nextRandomNumber*1103515245 + 12345;
return ((Uint16)(nextRandomNumber/65536)) % 32768;
}
-int BlockGame::firstUnusedChain()
-{
+int BlockGame::firstUnusedChain() {
bool found=false;
int i = 0;
- while (!found)
- {
- if (!chainUsed[++i])
+ while (!found) {
+ if (!chainUsed[++i]) {
found=true;
- if (i>NUMBEROFCHAINS-2)
+ }
+ if (i>NUMBEROFCHAINS-2) {
found=true;
+ }
}
return i;
}
//Constructor
-BlockGame::BlockGame()
-{
+BlockGame::BlockGame() {
srand((int)time(nullptr));
nrFellDown = 0;
nrPushedPixel = 0;
@@ -101,30 +99,25 @@ BlockGame::BlockGame()
nextGarbageNumber = 10;
handicap=0;
for (int i=0; i<7; i++)
- for (int j=0; j<30; j++)
- {
+ for (int j=0; j<30; j++) {
board[i][j] = -1;
}
- for (int i=0; i<NUMBEROFCHAINS; i++)
- {
+ for (int i=0; i<NUMBEROFCHAINS; i++) {
chainUsed[i]=false;
chainSize[i] = 0;
}
lastCounter = -1; //To prevent the final chunk to be played when stating the program
-} //Constructor
+} //Constructor
//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::~BlockGame()
-{
+BlockGame::~BlockGame() {
}
-void BlockGame::setGameSpeed(Uint8 globalSpeedLevel)
-{
+void BlockGame::setGameSpeed(Uint8 globalSpeedLevel) {
boost::format f("%1%");
f % globalSpeedLevel;
- switch (globalSpeedLevel)
- {
+ switch (globalSpeedLevel) {
case 0:
baseSpeed=0.5;
break;
@@ -146,8 +139,7 @@ void BlockGame::setGameSpeed(Uint8 globalSpeedLevel)
};
}
-void BlockGame::setHandicap(Uint8 globalHandicap)
-{
+void BlockGame::setHandicap(Uint8 globalHandicap) {
boost::format f("%1%");
f % globalHandicap;
handicap=1000*((Uint32)globalHandicap);
@@ -155,116 +147,94 @@ void BlockGame::setHandicap(Uint8 globalHandicap)
//Set the move speed of the AI based on the aiLevel parameter
//Also enables AI
-void BlockGame::setAIlevel(Uint8 aiLevel)
-{
+void BlockGame::setAIlevel(Uint8 aiLevel) {
AI_Enabled = true;
AI_MoveSpeed=120-(20*(aiLevel-3));
};
-Uint8 BlockGame::getAIlevel() const
-{
+Uint8 BlockGame::getAIlevel() const {
return (120-AI_MoveSpeed)/20+3;
}
-int BlockGame::GetScore() const
-{
+int BlockGame::GetScore() const {
return score;
}
-int BlockGame::GetHandicap() const
-{
+int BlockGame::GetHandicap() const {
return handicap;
}
-bool BlockGame::isGameOver() const
-{
+bool BlockGame::isGameOver() const {
return bGameOver;
}
-Sint32 BlockGame::GetGameStartedAt() const
-{
+Sint32 BlockGame::GetGameStartedAt() const {
return gameStartedAt;
}
-Sint32 BlockGame::GetGameEndedAt() const
-{
+Sint32 BlockGame::GetGameEndedAt() const {
return gameEndedAfter;
}
-bool BlockGame::isTimeTrial() const
-{
+bool BlockGame::isTimeTrial() const {
return timetrial;
}
-bool BlockGame::isStageClear() const
-{
+bool BlockGame::isStageClear() const {
return stageClear;
}
-bool BlockGame::isVsMode() const
-{
+bool BlockGame::isVsMode() const {
return vsMode;
}
-bool BlockGame::isPuzzleMode() const
-{
+bool BlockGame::isPuzzleMode() const {
return puzzleMode;
}
-int BlockGame::GetLinesCleared() const
-{
+int BlockGame::GetLinesCleared() const {
return linesCleared;
}
-int BlockGame::GetStageClearLimit() const
-{
+int BlockGame::GetStageClearLimit() const {
return stageClearLimit;
}
-int BlockGame::GetChains() const
-{
+int BlockGame::GetChains() const {
return chain;
}
-int BlockGame::GetPixels() const
-{
+int BlockGame::GetPixels() const {
return pixels;
}
-int BlockGame::GetSpeedLevel() const
-{
+int BlockGame::GetSpeedLevel() const {
return speedLevel;
}
-int BlockGame::GetTowerHeight() const
-{
+int BlockGame::GetTowerHeight() const {
return TowerHeight;
}
-int BlockGame::GetCursorX() const
-{
+int BlockGame::GetCursorX() const {
return cursorx;
}
-int BlockGame::GetCursorY() const
-{
+int BlockGame::GetCursorY() const {
return cursory;
}
-void BlockGame::MoveCursorTo(int x, int y)
-{
+void BlockGame::MoveCursorTo(int x, int y) {
cursorx = x;
cursory = y;
}
-bool BlockGame::GetIsWinner() const
-{
+bool BlockGame::GetIsWinner() const {
return hasWonTheGame;
}
//Instead of creating new object new game is called, to prevent memory leaks
-void BlockGame::NewGame( unsigned int ticks)
-{
+void BlockGame::NewGame( unsigned int ticks) {
this->ticks = ticks;
stageButtonStatus = SBdontShow;
nrFellDown = 0;
@@ -294,30 +264,25 @@ void BlockGame::NewGame( unsigned int ticks)
nextGarbageNumber = 10;
handicap=0;
for (int i=0; i<7; i++)
- for (int j=0; j<30; j++)
- {
+ for (int j=0; j<30; j++) {
board[i][j] = -1;
}
- for (int i=0; i<NUMBEROFCHAINS; i++)
- {
+ for (int i=0; i<NUMBEROFCHAINS; i++) {
chainUsed[i]=false;
chainSize[i] = 0;
}
lastAImove = ticks+3000;
-} //NewGame
+} //NewGame
-void BlockGame::NewTimeTrialGame( unsigned int ticks)
-{
+void BlockGame::NewTimeTrialGame( unsigned int ticks) {
NewGame(ticks);
timetrial = true;
putStartBlocks();
}
//Starts a new stage game, takes level as input!
-void BlockGame::NewStageGame(int level, unsigned int ticks)
-{
- if (level > -1)
- {
+void BlockGame::NewStageGame(int level, unsigned int ticks) {
+ if (level > -1) {
NewGame(ticks);
stageClear = true;
Level = level;
@@ -328,17 +293,14 @@ void BlockGame::NewStageGame(int level, unsigned int ticks)
}
}
-void BlockGame::NewPuzzleGame(int level, unsigned int ticks)
-{
- if (level>-1)
- {
+void BlockGame::NewPuzzleGame(int level, unsigned int ticks) {
+ if (level>-1) {
NewGame(ticks);
puzzleMode = true;
Level = level;
MovesLeft = PuzzleNumberOfMovesAllowed(Level);
for (int i=0; i<6; i++)
- for (int j=0; j<12; j++)
- {
+ for (int j=0; j<12; j++) {
board[i][j+1] = PuzzleGetBrick(Level,i,j);
}
baseSpeed = 100000;
@@ -346,30 +308,29 @@ void BlockGame::NewPuzzleGame(int level, unsigned int ticks)
//Now push the blines up
for (int i=19; i>0; i--)
- for (int j=0; j<6; j++)
- {
+ for (int j=0; j<6; j++) {
board[j][i] = board[j][i-1];
}
- for (int j=0; j<6; j++)
- {
+ for (int j=0; j<6; j++) {
board[j][0] = rand() % 6;
- if (j > 0)
- {
- if (board[j][0] == board[j-1][0])
+ if (j > 0) {
+ if (board[j][0] == board[j-1][0]) {
board[j][0] = rand() % 6;
+ }
}
- if (board[j][0] == board[j][1])
+ if (board[j][0] == board[j][1]) {
board[j][0] = 6;
- if (board[j][0] == board[j][1])
+ }
+ if (board[j][0] == board[j][1]) {
board[j][0] = 6;
+ }
}
}
}
//Replay the current level
-void BlockGame::retryLevel(unsigned int ticks)
-{
+void BlockGame::retryLevel(unsigned int ticks) {
if (puzzleMode) {
NewPuzzleGame(Level, ticks);
}
@@ -379,14 +340,13 @@ void BlockGame::retryLevel(unsigned int ticks)
}
//Play the next level
-void BlockGame::nextLevel(unsigned int ticks)
-{
+void BlockGame::nextLevel(unsigned int ticks) {
if (puzzleMode) {
if (Level<PuzzleGetNumberOfPuzzles()-1) {
NewPuzzleGame(Level+1, ticks);
}
}
- else if(stageClear) {
+ else if (stageClear) {
if (Level<50-1) {
NewStageGame(Level+1, ticks);
}
@@ -394,8 +354,7 @@ void BlockGame::nextLevel(unsigned int ticks)
}
//Starts new Vs Game (two Player)
-void BlockGame::NewVsGame(BlockGame *target, unsigned int ticks)
-{
+void BlockGame::NewVsGame(BlockGame *target, unsigned int ticks) {
NewGame(ticks);
vsMode = true;
putStartBlocks();
@@ -404,12 +363,11 @@ void BlockGame::NewVsGame(BlockGame *target, unsigned int ticks)
}
//Starts new Vs Game (two Player)
-void BlockGame::NewVsGame(BlockGame *target, bool AI, unsigned int ticks)
-{
+void BlockGame::NewVsGame(BlockGame *target, bool AI, unsigned int ticks) {
NewGame(ticks);
vsMode = true;
AI_Enabled = AI;
- if(!AI) {
+ if (!AI) {
Stats::getInstance()->addOne("VSgamesStarted");
}
else {
@@ -420,28 +378,22 @@ void BlockGame::NewVsGame(BlockGame *target, bool AI, unsigned int ticks)
}
//Prints "winner" and ends game
-void BlockGame::setPlayerWon()
-{
- if (!bGameOver || !hasWonTheGame)
- {
+void BlockGame::setPlayerWon() {
+ if (!bGameOver || !hasWonTheGame) {
gameEndedAfter = ticks-gameStartedAt; //We game ends now!
- if(!AI_Enabled)
- {
+ if (!AI_Enabled) {
TimeHandler::addTime("playTime",TimeHandler::ms2ct(gameEndedAfter));
}
bGameOver = true;
PlayerWonEvent();
- if(!AI_Enabled)
- {
+ if (!AI_Enabled) {
Stats::getInstance()->addOne("totalWins");
- if(garbageTarget->AI_Enabled)
- {
+ if (garbageTarget->AI_Enabled) {
//We have defeated an AI
Stats::getInstance()->addOne("defeatedAI"+itoa(garbageTarget->getAIlevel()));
}
}
- if(AI_Enabled && !(garbageTarget->AI_Enabled))
- {
+ if (AI_Enabled && !(garbageTarget->AI_Enabled)) {
//The AI have defeated a human player
Stats::getInstance()->addOne("defeatedByAI"+itoa(getAIlevel()));
}
@@ -450,11 +402,9 @@ void BlockGame::setPlayerWon()
}
//Prints "draw" and ends the game
-void BlockGame::setDraw()
-{
+void BlockGame::setDraw() {
bGameOver = true;
- if(!AI_Enabled)
- {
+ if (!AI_Enabled) {
TimeHandler::addTime("playTime",TimeHandler::ms2ct(gameEndedAfter));
}
hasWonTheGame = false;
@@ -467,34 +417,34 @@ void BlockGame::setDraw()
//Test if LineNr is an empty line, returns false otherwise.
-bool BlockGame::LineEmpty(int lineNr) const
-{
+bool BlockGame::LineEmpty(int lineNr) const {
bool empty = true;
for (int i = 0; i <7; i++)
- if (board[i][lineNr] != -1)
+ if (board[i][lineNr] != -1) {
empty = false;
+ }
return empty;
}
//Test if the entire board is empty (used for Puzzles)
-bool BlockGame::BoardEmpty() const
-{
+bool BlockGame::BoardEmpty() const {
bool empty = true;
for (int i=0; i<6; i++)
for (int j=1; j<13; j++)
- if (board[i][j] != -1)
+ if (board[i][j] != -1) {
empty = false;
+ }
return empty;
}
//Anything that the user can't move? In that case Game Over cannot occur
-bool BlockGame::hasStaticContent() const
-{
+bool BlockGame::hasStaticContent() const {
for (int i=0; i<6; i++)
for (int j=1; j<13; j++)
- if (board[i][j] >= 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
+ if (board[i][j] >= 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
}
/*
@@ -502,25 +452,21 @@ bool BlockGame::hasStaticContent() const
*/
//void putStartBlocks(Uint32);
-void BlockGame::putStartBlocks()
-{
+void BlockGame::putStartBlocks() {
putStartBlocks(time(0));
}
-void BlockGame::putStartBlocks(Uint32 n)
-{
+void BlockGame::putStartBlocks(Uint32 n) {
#if DEBUG
cout << n << ":" << f.str() << endl;
#endif
for (int i=0; i<7; i++)
- for (int j=0; j<30; j++)
- {
+ for (int j=0; j<30; j++) {
board[i][j] = -1;
}
nextRandomNumber = n;
int choice = rand2()%3; //Pick a random layout
- switch (choice)
- {
+ switch (choice) {
case 0:
//row 0:
board[0][0]=1;
@@ -632,37 +578,28 @@ void BlockGame::putStartBlocks(Uint32 n)
}
//decreases hang for all hanging blocks and wait for waiting blocks
-void BlockGame::ReduceStuff()
-{
+void BlockGame::ReduceStuff() {
Sint32 howMuchHang = (ticks - FRAMELENGTH*hangTicks)/FRAMELENGTH;
- if (howMuchHang>0)
- {
+ if (howMuchHang>0) {
for (int i=0; i<7; i++)
- for (int j=0; j<30; j++)
- {
- if ((board[i][j]/BLOCKHANG)%10==1)
- {
+ for (int j=0; j<30; j++) {
+ if ((board[i][j]/BLOCKHANG)%10==1) {
int hangNumber = (board[i][j]/10)%100;
- if (hangNumber<=howMuchHang)
- {
+ if (hangNumber<=howMuchHang) {
board[i][j]-=BLOCKHANG;
board[i][j]-=hangNumber*10;
}
- else
- {
+ else {
board[i][j]-=10*howMuchHang;
}
}
- if ((board[i][j]/BLOCKWAIT)%10==1)
- {
+ if ((board[i][j]/BLOCKWAIT)%10==1) {
int hangNumber = (board[i][j]/10)%100;
- if (hangNumber<=howMuchHang)
- {
+ if (hangNumber<=howMuchHang) {
//The blocks must be cleared
board[i][j]-=hangNumber*10;
}
- else
- {
+ else {
board[i][j]-=10*howMuchHang;
}
}
@@ -672,36 +609,43 @@ void BlockGame::ReduceStuff()
}
//Creates garbage using a given wide and height
-bool BlockGame::CreateGarbage(int wide, int height)
-{
+bool BlockGame::CreateGarbage(int wide, int height) {
{
- if (wide>6) wide = 6;
- if (height>12) height = 12;
+ if (wide>6) {
+ wide = 6;
+ }
+ if (height>12) {
+ height = 12;
+ }
int startPosition = 12;
- while ((!(LineEmpty(startPosition))) || (startPosition == 29))
+ while ((!(LineEmpty(startPosition))) || (startPosition == 29)) {
startPosition++;
- if (startPosition == 29) return false; //failed to place blocks
- if (29-startPosition<height) return false; //not enough space
+ }
+ if (startPosition == 29) {
+ return false; //failed to place blocks
+ }
+ if (29-startPosition<height) {
+ return false; //not enough space
+ }
int start, end;
- if (bGarbageFallLeft)
- {
+ if (bGarbageFallLeft) {
start=0;
end=start+wide;
bGarbageFallLeft = false;
}
- else
- {
+ else {
start=6-wide;
end = 6;
bGarbageFallLeft = true;
}
for (int i = startPosition; i <startPosition+height; i++)
- for (int j = start; j < end; j++)
- {
+ for (int j = start; j < end; j++) {
board[j][i] = 1000000+nextGarbageNumber;
}
nextGarbageNumber++;
- if (nextGarbageNumber>999999) nextGarbageNumber = 10;
+ if (nextGarbageNumber>999999) {
+ nextGarbageNumber = 10;
+ }
//bGarbageFallLeft = !(bGarbageFallLeft);
return true;
}
@@ -709,38 +653,41 @@ bool BlockGame::CreateGarbage(int wide, int height)
}
//Creates garbage using a given wide and height
-bool BlockGame::CreateGreyGarbage()
-{
+bool BlockGame::CreateGreyGarbage() {
int startPosition = 12;
- while ((!(LineEmpty(startPosition))) || (startPosition == 29))
+ while ((!(LineEmpty(startPosition))) || (startPosition == 29)) {
startPosition++;
- if (startPosition == 29) return false; //failed to place blocks
- if (29-startPosition<1) return false; //not enough space
+ }
+ 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 <startPosition+1; i++)
- {
- for (int j = start; j < end; j++)
- {
+ for (int i = startPosition; i <startPosition+1; i++) {
+ for (int j = start; j < end; j++) {
board[j][i] = 2*1000000+nextGarbageNumber;
}
}
nextGarbageNumber++;
- if (nextGarbageNumber>999999)
+ if (nextGarbageNumber>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)
- {
+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;
}
@@ -751,11 +698,11 @@ int BlockGame::GarbageClearer(int x, int y, int number, bool aLineToClear, int c
}
//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))
- {
+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);
@@ -766,16 +713,16 @@ int BlockGame::GarbageMarker(int x, int y)
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++)
+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))
- {
+ else if (((board[x][y])/1000000 == 1)&&(garbageToBeCleared[x][y] == false)) {
garbageToBeCleared[x][y] = true;
//Float fill
GarbageMarker(x-1, y);
@@ -787,67 +734,57 @@ int BlockGame::FirstGarbageMarker(int x, int y)
}
//Clear Blocks if 3 or more is alligned (naive implemented)
-void BlockGame::ClearBlocks()
-{
+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++)
- {
+ for (int j=0; j<7; j++) {
toBeCleared[j][i] = false;
garbageToBeCleared[j][i] = false;
}
- for (int i=0; i<7; i++)
- {
+ 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))
- {
+ 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))
+ if ((!faaling)&&((board[i][j]/BLOCKFALL)%10==1)) {
board[i][j]-=BLOCKFALL;
- if (!((board[i][j]>-1)&&(board[i][j]%10000000<7)))
+ }
+ 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))
+ }
+ 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++)
- {
+ 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)
- {
+ 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
- {
+ else {
if (combo>2)
- for (int k = i-combo; k<i; k++)
- {
+ for (int k = i-combo; k<i; k++) {
toBeCleared[j][k] = true;
}
combo=1;
previus = board[j][i]%10000000;
}
} //if board
- else
- {
+ else {
if (combo>2)
- for (int k = i-combo; k<i; k++)
- {
+ for (int k = i-combo; k<i; k++) {
toBeCleared[j][k] = true;
}
combo = 0;
@@ -859,15 +796,14 @@ void BlockGame::ClearBlocks()
chain = 0;
for (int i=0; i<6; i++)
- for (int j=0; j<30; j++)
- {
+ for (int j=0; j<30; j++) {
//Clears blocks marked for clearing
Sint32 temp=board[i][j];
if (1==((temp/BLOCKWAIT)%10))
- if (((temp/10)%100)==0)
- {
- if (chainSize[chain]<chainSize[board[i][j]/10000000])
+ if (((temp/10)%100)==0) {
+ if (chainSize[chain]<chainSize[board[i][j]/10000000]) {
chain = board[i][j]/10000000;
+ }
AddBall(i, j, true, board[i][j]%10);
AddBall(i, j, false, board[i][j]%10);
@@ -875,22 +811,19 @@ void BlockGame::ClearBlocks()
board[i][j]=-2;
}
}
- for (int i=0; i<7; i++)
- {
+ for (int i=0; i<7; i++) {
bool setChain=false;
- for (int j=0; j<30; j++)
- {
- if (board[i][j]==-1)
+ for (int j=0; j<30; j++) {
+ if (board[i][j]==-1) {
setChain=false;
- if (board[i][j]==-2)
- {
+ }
+ if (board[i][j]==-2) {
board[i][j]=-1;
setChain=true;
BlockPopEvent();
}
if (board[i][j]!=-1)
- if ((setChain)&&((board[i][j]/GARBAGE)%10!=1)&&((board[i][j]/GARBAGE)%10!=2))
- {
+ if ((setChain)&&((board[i][j]/GARBAGE)%10!=1)&&((board[i][j]/GARBAGE)%10!=2)) {
board[i][j]=((board[i][j]%CHAINPLACE)+CHAINPLACE*chain);
//somethingsGottaFall = true;
}
@@ -898,38 +831,32 @@ void BlockGame::ClearBlocks()
}
}
int startvalue;
- if (pixels == 0)
+ if (pixels == 0) {
startvalue=1;
- else
+ }
+ else {
startvalue=0;
- for (int i=startvalue; i<30; i++)
- {
+ }
+ for (int i=startvalue; i<30; i++) {
previus=-1;
combo=0;
- for (int j=0; j<7; j++)
- {
- if (((board[j][i]>-1)&&(board[j][i]%10000000<7)))
- {
- if (board[j][i]%10000000 == previus)
- {
+ for (int j=0; j<7; j++) {
+ if (((board[j][i]>-1)&&(board[j][i]%10000000<7))) {
+ if (board[j][i]%10000000 == previus) {
combo++;
}
- else
- {
+ else {
if (combo>2)
- for (int k = j-combo; k<j; k++)
- {
+ for (int k = j-combo; k<j; k++) {
toBeCleared[k][i] = true;
}
combo=1;
previus = board[j][i]%10000000;
}
} //if board
- else
- {
+ else {
if (combo>2)
- for (int k = j-combo; k<j; k++)
- {
+ for (int k = j-combo; k<j; k++) {
toBeCleared[k][i] = true;
}
combo = 0;
@@ -944,43 +871,44 @@ void BlockGame::ClearBlocks()
int grey = 0;
for (int i=0; i<30; i++)
for (int j=0; j<6; j++)
- if (toBeCleared[j][i])
- {
+ if (toBeCleared[j][i]) {
//see if any garbage is around:
FirstGarbageMarker(j-1, i);
FirstGarbageMarker(j+1, i);
FirstGarbageMarker(j, i-1);
FirstGarbageMarker(j, i+1);
//that is checked now :-)
- if (board[j][i]%10000000==6)
+ if (board[j][i]%10000000==6) {
grey++;
- if ((vsMode) && (grey>2) && (board[j][i]%10000000==6))
+ }
+ if ((vsMode) && (grey>2) && (board[j][i]%10000000==6)) {
garbageTarget->CreateGreyGarbage();
- if ((board[j][i]>-1)&&(board[j][i]%10000000<7))
+ }
+ if ((board[j][i]>-1)&&(board[j][i]%10000000<7)) {
board[j][i]+=BLOCKWAIT+10*FALLTIME;
+ }
- if (chainSize[board[j][i]/10000000]>chainSize[chain])
+ 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
+ if (combo>3) {
+ score+=3*combo; //More points if more cleared simontanously
+ }
}
score+=chainSize[chain]*100;
- if (chain==0)
- {
+ 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++)
- {
+ for (int j=0; j<6; j++) {
//if(board[j][i]/10==(BLOCKWAIT+10*FALLTIME)/10)
- if (toBeCleared[j][i])
- {
+ if (toBeCleared[j][i]) {
board[j][i]=(board[j][i]%10000000)+chain*10000000;
}
}
@@ -990,10 +918,8 @@ void BlockGame::ClearBlocks()
bool dead = false;
for (int i=29; i>=0; i--)
for (int j=0; j<6; j++)
- if (toBeCleared[j][i])
- {
- if (!dead)
- {
+ if (toBeCleared[j][i]) {
+ if (!dead) {
dead=true;
string tempS = itoa(chainSize[chain]);
if (chainSize[chain]>1) {
@@ -1004,8 +930,7 @@ void BlockGame::ClearBlocks()
} //This was there text was added
if (vsMode)
- switch (combo)
- {
+ switch (combo) {
case 0:
case 1:
case 2:
@@ -1056,35 +981,34 @@ void BlockGame::ClearBlocks()
}
for (int i=0; i<30; i++)
for (int j=0; j<6; j++)
- if (garbageToBeCleared[j][i])
- {
+ 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++)
- {
+ 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))
- {
+ 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))
+ 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])
+ }
+ 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)))
+ 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))
+ }
+ if (((board[i][j]/1000000)%10==1)||((board[i][j]/BLOCKHANG)%10==1)||((board[i][j]/BLOCKWAIT)%10==1)) {
faaling = false;
+ }
}
}
@@ -1094,30 +1018,31 @@ void BlockGame::ClearBlocks()
//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)
+ 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; i<NUMBEROFCHAINS; i++)
- if (chainUsed[i]==true)
- {
- if ((vsMode)&&(chainSize[i]>1)) garbageTarget->CreateGarbage(6, chainSize[i]-1);
+ if (chainUsed[i]==true) {
+ if ((vsMode)&&(chainSize[i]>1)) {
+ garbageTarget->CreateGarbage(6, chainSize[i]-1);
+ }
if (chainSize[i]>4) {
LongChainDoneEvent();
}
- if(chainSize[i]>1 && !puzzleMode && !AI_Enabled)
+ 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()
-{
+void BlockGame::SetGameOver() {
if (!bGameOver) {
gameEndedAfter = ticks-gameStartedAt; //We game ends now!
if (!AI_Enabled) {
@@ -1125,148 +1050,145 @@ void BlockGame::SetGameOver()
}
}
bGameOver = true;
- if(stageClear)
+ if (stageClear) {
stageButtonStatus = SBstageClear;
+ }
}
-bool BlockGame::GetAIenabled()
-{
+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;
+int BlockGame::FallBlock(int x, int y, int number) {
+ if (y == 0) {
+ return -1;
+ }
if (x>0)
- if (board[x-1][y] == number)
+ 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;
+ while ((board[i][y] == number)&&(canFall)&&(i<6)) {
+ if (board[i][y-1] != -1) {
+ canFall = false;
+ }
i++;
}
- if (canFall)
- {
+ if (canFall) {
//cout << "Now falling" << endl;
- for (int j = x; j<i; j++)
- {
+ for (int j = x; j<i; j++) {
board[j][y-1] = board[j][y];
board[j][y] = -1;
}
}
return 0;
-} //FallBlock
+} //FallBlock
//Makes all Garbage fall one spot
-void BlockGame::GarbageFall()
-{
+void BlockGame::GarbageFall() {
for (int i=0; i<30; i++)
- for (int j=0; j<7; j++)
- {
- if ((((board[j][i]/1000000)%10) == 1)||(((board[j][i]/1000000)%10) == 2))
+ for (int j=0; j<7; j++) {
+ if ((((board[j][i]/1000000)%10) == 1)||(((board[j][i]/1000000)%10) == 2)) {
FallBlock(j, i, board[j][i]);
+ }
}
}
//Makes the blocks fall (it doesn't test time, this must be done before hand)
-void BlockGame::FallDown()
-{
+void BlockGame::FallDown() {
bool falling =false; //nothing is moving unless proven otherwise
for (int i=0; i<29; i++)
- for (int j=0; j<6; j++)
- {
- if ((board[j][i]==-1) && (board[j][i+1]!=-1) && (board[j][i+1]%BLOCKFALL<7))
- {
+ for (int j=0; j<6; j++) {
+ if ((board[j][i]==-1) && (board[j][i+1]!=-1) && (board[j][i+1]%BLOCKFALL<7)) {
board[j][i] = board[j][i+1];
board[j][i+1] = -1;
falling = true; //something is moving!
}
- if ((board[j][i]/BLOCKWAIT)%10==1)
+ if ((board[j][i]/BLOCKWAIT)%10==1) {
falling=true;
+ }
}
- if (!falling) //If nothing is falling
- {
- if ((puzzleMode)&&(!bGameOver)&&(MovesLeft==0)&&(!(BoardEmpty())))
- {
+ if (!falling) { //If nothing is falling
+ if ((puzzleMode)&&(!bGameOver)&&(MovesLeft==0)&&(!(BoardEmpty()))) {
//Puzzle not won
SetGameOver();
stageButtonStatus = SBpuzzleMode;
}
}
- GarbageFall(); //Makes the garbage fall
+ GarbageFall(); //Makes the garbage fall
nrFellDown++; //Sets number of this fall, so we know then the next will occur
}
//Moves the cursor, receaves N,S,E or W as a char an moves as desired
-void BlockGame::MoveCursor(char way)
-{
- if (!bGameOver) //If game over nothing happends
- {
- if ((way == 'N') && ((cursory<10)||(TowerHeight>12) ||(((pixels==bsize)||(pixels==0)) && (cursory<11))))
+void BlockGame::MoveCursor(char way) {
+ if (!bGameOver) { //If game over nothing happends
+ if ((way == 'N') && ((cursory<10)||(TowerHeight>12) ||(((pixels==bsize)||(pixels==0)) && (cursory<11)))) {
cursory++;
- if ((way == 'S') && (cursory>0))
+ }
+ if ((way == 'S') && (cursory>0)) {
cursory--;
- if ((way == 'W') && (cursorx>0))
+ }
+ if ((way == 'W') && (cursorx>0)) {
cursorx--;
- if ((way == 'E') && (cursorx<4))
+ }
+ 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)) && (gameStartedAt<ticks))
- {
+void BlockGame::SwitchAtCursor() {
+ if ((board[cursorx][cursory+1]<7) && (board[cursorx+1][cursory+1]<7) && (!bGameOver) && ((!puzzleMode)||(MovesLeft>0)) && (gameStartedAt<ticks)) {
int temp = board[cursorx][cursory+1];
board[cursorx][cursory+1] = board[cursorx+1][cursory+1];
board[cursorx+1][cursory+1] = temp;
}
- if ((puzzleMode)&&(gameStartedAt<ticks)&&(MovesLeft>0)) MovesLeft--;
+ if ((puzzleMode)&&(gameStartedAt<ticks)&&(MovesLeft>0)) {
+ MovesLeft--;
+ }
}
-void BlockGame::PushLine()
-{
+void BlockGame::PushLine() {
PushLineInternal();
}
//Generates a new line and moves the field one block up (restart puzzle mode)
-void BlockGame::PushLineInternal()
-{
+void BlockGame::PushLineInternal() {
//If not game over, not high tower and not puzzle mode
- if ((!bGameOver) && TowerHeight<13 && (!puzzleMode) && (gameStartedAt<ticks)&&(chain==0))
- {
+ if ((!bGameOver) && TowerHeight<13 && (!puzzleMode) && (gameStartedAt<ticks)&&(chain==0)) {
for (int i=19; i>0; i--)
- for (int j=0; j<6; j++)
- {
+ for (int j=0; j<6; j++) {
board[j][i] = board[j][i-1];
}
- for (int j=0; j<6; j++)
- {
+ for (int j=0; j<6; j++) {
board[j][0] = rand2() % 4;
- if (j > 0)
- {
- if (board[j][0] == board[j-1][0])
+ if (j > 0) {
+ if (board[j][0] == board[j-1][0]) {
board[j][0] = rand2() % 6;
+ }
}
- if (board[j][0] == board[j][1])
+ if (board[j][0] == board[j][1]) {
board[j][0] = rand2() % 6;
- if (board[j][0] == board[j][1])
+ }
+ if (board[j][0] == board[j][1]) {
board[j][0] = rand2() % 6;
- while ((j>0)&&(board[j][0]==board[j-1][0]))
+ }
+ while ((j>0)&&(board[j][0]==board[j-1][0])) {
board[j][0] = rand2() % 6;
+ }
}
score+=1;
MoveCursor('N'); //Workaround for this being done registred too
if (vsMode) {
- if (rand2()%6==1)
+ if (rand2()%6==1) {
board[rand2()%6][0]=6;
+ }
}
pixels = 0;
stop=0;
@@ -1275,34 +1197,30 @@ void BlockGame::PushLineInternal()
AI_LineOffset++;
nrPushedPixel=(int)((double)(pushedPixelAt-gameStartedAt)/(1000.0*speed));
- if(!AI_Enabled)
- {
+ if (!AI_Enabled) {
Stats::getInstance()->addOne("linesPushed");
}
} //if !bGameOver
//Restart Puzzle mode
- if (puzzleMode && !bGameOver)
- {
+ if (puzzleMode && !bGameOver) {
//Reloads level
MovesLeft = PuzzleNumberOfMovesAllowed(Level);
for (int i=0; i<6; i++)
- for (int j=0; j<12; j++)
- {
+ for (int j=0; j<12; j++) {
board[i][j+1] = PuzzleGetBrick(Level,i,j);
}
score=0;
bGameOver=false;
}
- if ((TowerHeight>12) && (!puzzleMode)&&(!bGameOver)&&(chain==0))
- {
- if ((!vsMode)&&(theTopScoresEndless.isHighScore(score))&&(!AI_Enabled))
- {
+ if ((TowerHeight>12) && (!puzzleMode)&&(!bGameOver)&&(chain==0)) {
+ if ((!vsMode)&&(theTopScoresEndless.isHighScore(score))&&(!AI_Enabled)) {
EndlessHighscoreEvent();
theTopScoresEndless.addScore(name, score);
- if(verboseLevel)
+ if (verboseLevel) {
cout << "New high score!" << endl;
+ }
}
SetGameOver();
}
@@ -1311,23 +1229,22 @@ void BlockGame::PushLineInternal()
}//PushLine
//Pushes a single pixel, so it appears to scrool
-void BlockGame::PushPixels()
-{
+void BlockGame::PushPixels() {
nrPushedPixel++;
- if ((pixels < bsize) && TowerHeight<13)
- {
+ if ((pixels < bsize) && TowerHeight<13) {
pixels++;
}
- else
+ else {
PushLineInternal();
- if (pixels>bsize)
+ }
+ if (pixels>bsize) {
pixels=0;
+ }
}
//See how high the tower is, saved in integer TowerHeight
-void BlockGame::FindTowerHeight()
-{
+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.
@@ -1335,12 +1252,12 @@ void BlockGame::FindTowerHeight()
prevTowerHeight = TowerHeight;
bool found = false;
TowerHeight = 0;
- while (!found)
- {
+ while (!found) {
found = true;
for (int j=0; j<6; j++)
- if (board[j][TowerHeight] != -1)
+ if (board[j][TowerHeight] != -1) {
found = false;
+ }
TowerHeight++;
}
TowerHeight--;
@@ -1350,33 +1267,31 @@ void BlockGame::FindTowerHeight()
/////////////////////////// AI starts here! ///////////////////////////////
///////////////////////////////////////////////////////////////////////////
//First the helpet functions:
-int BlockGame::nrOfType(int line, int type)
-{
+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++;
+ if (board[i][line]==type) {
+ counter++;
+ }
return counter;
}
//See if a combo can be made in this line
-int BlockGame::horiInLine(int 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++)
- {
+ for (int i=0; i<6; i++) {
iTemp = board[i][line];
- if ((iTemp>-1)&&(iTemp<7))
+ if ((iTemp>-1)&&(iTemp<7)) {
nrOfType[iTemp]++;
+ }
}
- for (int j=0; j<7; j++)
- {
- if (nrOfType[j]>max)
- {
+ for (int j=0; j<7; j++) {
+ if (nrOfType[j]>max) {
max = nrOfType[j];
AIcolorToClear = j;
}
@@ -1384,15 +1299,12 @@ int BlockGame::horiInLine(int line)
return max;
}
-bool BlockGame::horiClearPossible()
-{
+bool BlockGame::horiClearPossible() {
//cout << "Start_ horiclear possible" << endl;
int i=13;
bool solutionFound = false;
- do
- {
- if (horiInLine(i)>2)
- {
+ do {
+ if (horiInLine(i)>2) {
AI_LineOffset = 0;
AIlineToClear = i;
solutionFound = true;
@@ -1404,50 +1316,54 @@ bool BlockGame::horiClearPossible()
}
//the Line Has Unmoveable Objects witch might stall the AI
-bool BlockGame::lineHasGarbage(int line)
-{
+bool BlockGame::lineHasGarbage(int line) {
for (int i=0; i<6; i++)
- if (board[i][line]>1000000)
+ if (board[i][line]>1000000) {
return true;
+ }
return false;
}
//Types 0..6 in line
-int BlockGame::nrOfRealTypes(int 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++;
+ if ((board[i][line]>-1)&&(board[i][line]<7)) {
+ counter++;
+ }
return counter;
}
//See if there is a tower
-bool BlockGame::ThereIsATower()
-{
+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))
- {
+ do {
+ if ((emptySpacesFound) && (nrOfRealTypes(lineNumber)>0)&&(nrOfType(lineNumber, -1)>0)) {
AIlineToClear = lineNumber;
- if (lineHasGarbage(lineNumber))
+ if (lineHasGarbage(lineNumber)) {
return false;
- else
+ }
+ else {
bThereIsATower = true;
+ }
}
- else
+ else {
emptySpacesFound=false;
- if ((!emptySpacesFound)&&(nrOfType(lineNumber, -1)>0))
+ }
+ if ((!emptySpacesFound)&&(nrOfType(lineNumber, -1)>0)) {
emptySpacesFound = true;
- if (lineNumber<12)
+ }
+ if (lineNumber<12) {
lineNumber++;
- else
+ }
+ else {
topReached = true;
+ }
}
while ((!bThereIsATower)&&(!topReached));
//if(bThereIsATower)
@@ -1455,70 +1371,72 @@ bool BlockGame::ThereIsATower()
return bThereIsATower;
}
-double BlockGame::firstInLine1(int line)
-{
- if(line > 20 || line < 0)
- {
+double BlockGame::firstInLine1(int line) {
+ if (line > 20 || line < 0) {
cerr << "Warning: first in Line1: " << line << endl;
return 3.0;
}
for (int i=0; i<6; i++)
- if ((board[i][line]>-1)&&(board[i][line]<7))
+ 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)
-{
- if(line > 20 || line < 0)
- {
+double BlockGame::firstInLine(int line, int type) {
+ if (line > 20 || line < 0) {
cerr << "Warning: first in Line: " << line << endl;
return 3.0;
}
for (int i=0; i<6; i++)
- if (board[i][line]==type)
+ 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)
+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))
+ }
+ 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()
-{
+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+1<AIlineToClear)
+ if (cursory+1<AIlineToClear) {
MoveCursor('N');
- else if (cursory+1>AIlineToClear)
+ }
+ else if (cursory+1>AIlineToClear) {
MoveCursor('S');
- else if (cursorx<xplace)
+ }
+ else if (cursorx<xplace) {
MoveCursor('E');
- else if (cursorx>xplace)
+ }
+ else if (cursorx>xplace) {
MoveCursor('W');
- else
+ }
+ else {
SwitchAtCursor();
- if (!ThereIsATower())
+ }
+ if (!ThereIsATower()) {
AIstatus = 0;
+ }
}
//The AI will try to clear block horisontally
-void BlockGame::AI_ClearHori()
-{
+void BlockGame::AI_ClearHori() {
// cout << "AI: ClearHori";
int lowestLine = AIlineToClear;
//AIcolorToClear
@@ -1531,80 +1449,91 @@ void BlockGame::AI_ClearHori()
* found = true;
* }
* }*/
- for (int i=0; i<7; i++)
- {
- if (nrOfType(lowestLine, i)>2)
+ for (int i=0; i<7; i++) {
+ if (nrOfType(lowestLine, i)>2) {
AIcolorToClear = i;
+ }
}
- if (found)
- {
- if (cursory>lowestLine-1)
+ if (found) {
+ if (cursory>lowestLine-1) {
MoveCursor('S');
- else if (cursory<lowestLine-1)
+ }
+ else if (cursory<lowestLine-1) {
MoveCursor('N');
- else if (nrOfType(lowestLine, AIcolorToClear)>2)
- {
+ }
+ else if (nrOfType(lowestLine, AIcolorToClear)>2) {
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++;
+ 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 (left<right)
- {
+ if (left<right) {
// cout << ", right>left";
int count=0;
for (int i=0; (i<4)&&(count<1); i++)
- if ((board[i][lowestLine]==AIcolorToClear)&&((i==0)||(board[i+1][lowestLine]!=AIcolorToClear)))
- {
+ if ((board[i][lowestLine]==AIcolorToClear)&&((i==0)||(board[i+1][lowestLine]!=AIcolorToClear))) {
count++;
xplace = i;
}
}
- else
- {
+ 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))
- {
+ if ((board[i][lowestLine]==AIcolorToClear)&&(board[i-1][lowestLine]!=AIcolorToClear)) {
count++;
xplace = --i;
}
}
//cout << ", xplace: " << xplace;
- if (cursorx<xplace)
+ if (cursorx<xplace) {
MoveCursor('E');
- else if (cursorx>xplace)
+ }
+ else if (cursorx>xplace) {
MoveCursor('W');
- else if (cursorx==xplace)
+ }
+ else if (cursorx==xplace) {
SwitchAtCursor();
- else
+ }
+ else {
AIstatus = 0;
+ }
}
- else
+ else {
AIstatus = 0;
+ }
}
- else
+ else {
AIstatus = 0;
+ }
//cout << endl; //for debugging
}
//Test if vertical clear is possible
-bool BlockGame::veriClearPossible()
-{
+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)
+ 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)
- {
+ }
+ else if (++colors[j]>2) {
AIcolorToClear = j;
AIlineToClear = i;
found=true;
@@ -1618,128 +1547,137 @@ bool BlockGame::veriClearPossible()
//There in the line shall we move
-int BlockGame::closestTo(int line, int type, int place)
-{
- if ((int)firstInLine(line, type)>place)
+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)
+ }
+ 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()
-{
+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;
- if(AIlineToClear < 0 || AIlineToClear > 20)
- {
+ if (AIlineToClear < 0 || AIlineToClear > 20) {
cerr << "AIlineToClear out of range: " << AIlineToClear << endl;
return;
}
- if(placeToCenter<0 || placeToCenter > 5)
- {
+ if (placeToCenter<0 || placeToCenter > 5) {
cerr << "placeToCenter out of range: " << placeToCenter << endl;
return;
}
//cout << "AI_ClearVertical: " << placeToCenter << ", " << AIlineToClear << endl;
- while (((board[placeToCenter][AIlineToClear]>1000000)||(board[placeToCenter][AIlineToClear+1]>1000000)||(board[placeToCenter][AIlineToClear+2]>1000000))&&(unlimitedLoop<10))
- {
+ while (((board[placeToCenter][AIlineToClear]>1000000)||(board[placeToCenter][AIlineToClear+1]>1000000)||(board[placeToCenter][AIlineToClear+2]>1000000))&&(unlimitedLoop<10)) {
unlimitedLoop++;
placeToCenter++;
- if (placeToCenter>5)
+ if (placeToCenter>5) {
placeToCenter=0;
+ }
}
- if(unlimitedLoop>9)
- {
+ if (unlimitedLoop>9) {
AIstatus = 0;
return;
}
//cout << ", ptc: " << placeToCenter << ", line: " << AIlineToClear << ", cy: " << cursory;
- if (cursory+1>AIlineToClear+2)
- {
+ if (cursory+1>AIlineToClear+2) {
// cout << ", cursory>line+2";
MoveCursor('S');
}
- if (cursory+1<AIlineToClear)
+ if (cursory+1<AIlineToClear) {
MoveCursor('N');
+ }
bool toAlign[3]= {true, true, true};
- if (board[placeToCenter][AIlineToClear+0]==AIcolorToClear)
+ if (board[placeToCenter][AIlineToClear+0]==AIcolorToClear) {
toAlign[0]=false;
- if (board[placeToCenter][AIlineToClear+1]==AIcolorToClear)
+ }
+ if (board[placeToCenter][AIlineToClear+1]==AIcolorToClear) {
toAlign[1]=false;
- if (board[placeToCenter][AIlineToClear+2]==AIcolorToClear)
+ }
+ if (board[placeToCenter][AIlineToClear+2]==AIcolorToClear) {
toAlign[2]=false;
+ }
//cout << "status: " << toAlign[0] << " " << toAlign[1] << " " << toAlign[2];
- if (cursory+1==AIlineToClear)
- {
- if (toAlign[0]==false)
+ if (cursory+1==AIlineToClear) {
+ if (toAlign[0]==false) {
MoveCursor('N');
- else
- {
- if (cursorx>closestTo(AIlineToClear, AIcolorToClear, placeToCenter))
+ }
+ else {
+ if (cursorx>closestTo(AIlineToClear, AIcolorToClear, placeToCenter)) {
MoveCursor('W');
- else if (cursorx<closestTo(AIlineToClear, AIcolorToClear, placeToCenter))
+ }
+ else if (cursorx<closestTo(AIlineToClear, AIcolorToClear, placeToCenter)) {
MoveCursor('E');
- else
+ }
+ else {
SwitchAtCursor();
+ }
}
}
- else if (cursory+1==AIlineToClear+1)
- {
- if (toAlign[1]==false)
- {
- if (toAlign[2])
+ else if (cursory+1==AIlineToClear+1) {
+ if (toAlign[1]==false) {
+ if (toAlign[2]) {
MoveCursor('N');
- else
+ }
+ else {
MoveCursor('S');
+ }
}
- else
- {
- if (cursorx>closestTo(AIlineToClear+1, AIcolorToClear, placeToCenter))
+ else {
+ if (cursorx>closestTo(AIlineToClear+1, AIcolorToClear, placeToCenter)) {
MoveCursor('W');
- else if (cursorx<closestTo(AIlineToClear+1, AIcolorToClear, placeToCenter))
+ }
+ else if (cursorx<closestTo(AIlineToClear+1, AIcolorToClear, placeToCenter)) {
MoveCursor('E');
- else
+ }
+ else {
SwitchAtCursor();
+ }
}
}
- else if (cursory+1==AIlineToClear+2)
- {
- if (toAlign[2]==false)
+ else if (cursory+1==AIlineToClear+2) {
+ if (toAlign[2]==false) {
MoveCursor('S');
- else
- {
- if (cursorx>closestTo(AIlineToClear+2, AIcolorToClear, placeToCenter))
+ }
+ else {
+ if (cursorx>closestTo(AIlineToClear+2, AIcolorToClear, placeToCenter)) {
MoveCursor('W');
- else if (cursorx<closestTo(AIlineToClear+2, AIcolorToClear, placeToCenter))
+ }
+ else if (cursorx<closestTo(AIlineToClear+2, AIcolorToClear, placeToCenter)) {
MoveCursor('E');
- else
+ }
+ else {
SwitchAtCursor();
+ }
}
}
- if ((!toAlign[0])&&(!toAlign[1])&&(!toAlign[2]))
+ if ((!toAlign[0])&&(!toAlign[1])&&(!toAlign[2])) {
AIstatus = 0;
- if ((nrOfType(AIlineToClear, AIcolorToClear)==0)||(nrOfType(AIlineToClear+1, AIcolorToClear)==0)||(nrOfType(AIlineToClear+2, AIcolorToClear)==0))
+ }
+ if ((nrOfType(AIlineToClear, AIcolorToClear)==0)||(nrOfType(AIlineToClear+1, AIcolorToClear)==0)||(nrOfType(AIlineToClear+2, AIcolorToClear)==0)) {
AIstatus = 0;
+ }
//cout << endl;
}
-void BlockGame::AI_Move()
-{
- switch (AIstatus)
- {
+void BlockGame::AI_Move() {
+ switch (AIstatus) {
case 1:
- if (TowerHeight<8)PushLine();
- else AIstatus = 0;
+ if (TowerHeight<8) {
+ PushLine();
+ }
+ else {
+ AIstatus = 0;
+ }
break;
case 2:
AI_ClearTower();
@@ -1751,13 +1689,11 @@ void BlockGame::AI_Move()
AI_ClearVertical();
break;
case 5:
- if (!firstLineCreated)
- {
+ if (!firstLineCreated) {
PushLine();
firstLineCreated = true;
}
- else
- {
+ else {
PushLine();
AIstatus = 0;
}
@@ -1767,12 +1703,21 @@ void BlockGame::AI_Move()
AIstatus = 0;
break;
default:
- if (TowerHeight<6) AIstatus = 1;
- else if (horiClearPossible()) AIstatus = 3;
- else if (veriClearPossible()) AIstatus = 4;
- else if (ThereIsATower()) AIstatus = 2;
- else
+ if (TowerHeight<6) {
+ AIstatus = 1;
+ }
+ else if (horiClearPossible()) {
+ AIstatus = 3;
+ }
+ else if (veriClearPossible()) {
+ AIstatus = 4;
+ }
+ else if (ThereIsATower()) {
+ AIstatus = 2;
+ }
+ else {
AIstatus = 5;
+ }
break;
}
}
@@ -1783,8 +1728,7 @@ void BlockGame::AI_Move()
//Updates evrything, if not called nothing happends
-void BlockGame::Update()
-{
+void BlockGame::Update() {
Uint32 tempUInt32;
Uint32 nowTime = ticks; //We remember the time, so it doesn't change during this call
@@ -1792,8 +1736,7 @@ void BlockGame::Update()
FindTowerHeight();
if ((linesCleared-TowerHeight>stageClearLimit) && (stageClear) && (!bGameOver)) {
stageCleared[Level] = true;
- if(stageScores[Level]<score)
- {
+ if (stageScores[Level]<score) {
gameEndedAfter = nowTime-gameStartedAt;
stageScores[Level] = score;
stageTimes[Level] = gameEndedAfter;
@@ -1801,24 +1744,19 @@ void BlockGame::Update()
ofstream outfile;
outfile.open(stageClearSavePath.c_str(), ios::binary |ios::trunc);
- if (!outfile)
- {
+ if (!outfile) {
cerr << "Error writing to file: " << stageClearSavePath << endl;
}
- else
- {
- for (int i=0; i<nrOfStageLevels; i++)
- {
+ else {
+ for (int i=0; i<nrOfStageLevels; i++) {
bool tempBool = stageCleared[i];
outfile.write(reinterpret_cast<char*>(&tempBool), sizeof(bool));
}
- for (int i=0; i<nrOfStageLevels; i++)
- {
+ for (int i=0; i<nrOfStageLevels; i++) {
tempUInt32 = stageScores[i];
outfile.write(reinterpret_cast<char*>(&tempUInt32), sizeof(Uint32));
}
- for (int i=0; i<nrOfStageLevels; i++)
- {
+ for (int i=0; i<nrOfStageLevels; i++) {
tempUInt32 = stageTimes[i];
outfile.write(reinterpret_cast<char*>(&tempUInt32), sizeof(Uint32));
}
@@ -1827,20 +1765,20 @@ void BlockGame::Update()
setPlayerWon();
stageButtonStatus = SBstageClear;
}
- if ((TowerHeight>12)&&(prevTowerHeight<13)&&(!puzzleMode))
- {
+ if ((TowerHeight>12)&&(prevTowerHeight<13)&&(!puzzleMode)) {
stop+=1000;
}
- while (nowTime>nrStops*40+gameStartedAt) //Increase stops, till we reach nowTime
- {
- if (stop>0)
- {
+ 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) {
+ nrPushedPixel=(int)((nowTime-gameStartedAt)/(1000.0*speed));
+ }
}
- if (stop<0)
+ if (stop<0) {
stop = 0;
+ }
nrStops++;
}
//If we have static content, we don't raise at all!
@@ -1856,8 +1794,7 @@ void BlockGame::Update()
}
//increse speed:
- if ((nowTime>gameStartedAt+20000*speedLevel)&&(speedLevel <99)&&(!bGameOver))
- {
+ 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));
@@ -1865,24 +1802,26 @@ void BlockGame::Update()
//To prevent the stack from raising a lot then we stop a chain (doesn't work anymore)
- if (chain>0)
+ if (chain>0) {
stop+=1;
+ }
//Raises the stack
if ((nowTime>gameStartedAt+nrPushedPixel*1000*speed) && (!bGameOver)&&(!stop))
- while ((nowTime>gameStartedAt+nrPushedPixel*1000*speed)&&(!(puzzleMode)))
+ while ((nowTime>gameStartedAt+nrPushedPixel*1000*speed)&&(!(puzzleMode))) {
PushPixels();
- if (!bGameOver)ClearBlocks();
+ }
+ if (!bGameOver) {
+ ClearBlocks();
+ }
/*************************************************************
Ai stuff
**************************************************************/
- if (bGameOver)
- {
+ if (bGameOver) {
AIstatus = 0; //Enusres that AI is resetted
}
else if (AI_Enabled)
- if (lastAImove+AI_MoveSpeed<ticks)
- {
+ if (lastAImove+AI_MoveSpeed<ticks) {
AI_Move();
lastAImove=ticks;
}
@@ -1890,27 +1829,25 @@ void BlockGame::Update()
/*************************************************************
Ai stuff ended
**************************************************************/
- if ((nowTime>gameStartedAt+nrFellDown*140) && (!bGameOver)) FallDown();
- if ((nowTime<gameStartedAt)&&(puzzleMode))
- {
+ if ((nowTime>gameStartedAt+nrFellDown*140) && (!bGameOver)) {
+ FallDown();
+ }
+ if ((nowTime<gameStartedAt)&&(puzzleMode)) {
FallDown();
nrFellDown--;
}
ReduceStuff();
- if ((timetrial) && (!bGameOver) && (nowTime>gameStartedAt+2*60*1000))
- {
+ if ((timetrial) && (!bGameOver) && (nowTime>gameStartedAt+2*60*1000)) {
SetGameOver();
TimeTrialEndEvent();
- if ((theTopScoresTimeTrial.isHighScore(score))&&(!AI_Enabled))
- {
+ 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)
- {
+ if (inFile) {
inFile >> bestResult;
inFile.close();
}
@@ -1919,45 +1856,40 @@ void BlockGame::Update()
}
}
-bool BlockGame::IsNearDeath()
-{
- if ((TowerHeight>12)&&(!puzzleMode)&&(!bGameOver))
+bool BlockGame::IsNearDeath() {
+ if ((TowerHeight>12)&&(!puzzleMode)&&(!bGameOver)) {
return true;
- else
+ }
+ else {
return false;
+ }
}
-void BlockGame::UpdateInternal(unsigned int newtick)
-{
- while(newtick >= ticks+50)
- {
+void BlockGame::UpdateInternal(unsigned int newtick) {
+ while (newtick >= ticks+50) {
ticks+=50;
Update();
}
}
-void BlockGame::Update(unsigned int newtick)
-{
+void BlockGame::Update(unsigned int newtick) {
UpdateInternal(newtick);
}
-void BlockGame::PerformAction(unsigned int tick, int action, string param)
-{
+void BlockGame::PerformAction(unsigned int tick, int action, string param) {
ss.str(std::string());
ss.clear();
ss << param;
int p1,p2;
Uint32 p3;
- switch(action)
- {
+ switch (action) {
case ACTION_UPDATE:
UpdateInternal(tick);
break;
case ACTION_MOVECURSOR:
MoveCursor(param.at(0));
break;
- case ACTION_MOVECURSORTO:
- {
+ case ACTION_MOVECURSORTO: {
int p1,p2;
ss >> p1 >> p2;
@@ -1970,8 +1902,7 @@ void BlockGame::PerformAction(unsigned int tick, int action, string param)
case ACTION_PUSH:
PushLine();
break;
- case ACTION_CREATEGARBAGE:
- {
+ case ACTION_CREATEGARBAGE: {
ss >> p1 >> p2;
CreateGarbage(p1,p2);
}
diff --git a/source/code/CppSdlImageHolder.cpp b/source/code/CppSdlImageHolder.cpp
index 5d4a6f1..ad1c3be 100644
--- a/source/code/CppSdlImageHolder.cpp
+++ b/source/code/CppSdlImageHolder.cpp
@@ -25,19 +25,15 @@ http://blockattack.sf.net
#include "SDL_image.h"
#include <stdexcept>
-namespace CppSdl
-{
+namespace CppSdl {
-CppSdlImageHolder::CppSdlImageHolder()
-{
+CppSdlImageHolder::CppSdlImageHolder() {
data = nullptr;
}
-CppSdlImageHolder::CppSdlImageHolder(std::string filename)
-{
+CppSdlImageHolder::CppSdlImageHolder(std::string filename) {
data = IMG_Load(filename.c_str());
- if(!data)
- {
+ if (!data) {
//Here we should throw an exception
throw std::runtime_error(std::string("Could not read file \""+filename+"\""));
}
@@ -45,9 +41,8 @@ CppSdlImageHolder::CppSdlImageHolder(std::string filename)
OptimizeForBlit();
}
-CppSdlImageHolder::CppSdlImageHolder(char* rawdata, int datasize)
-{
- SDL_RWops *rw = SDL_RWFromMem (rawdata, datasize);
+CppSdlImageHolder::CppSdlImageHolder(char* rawdata, int datasize) {
+ SDL_RWops* rw = SDL_RWFromMem (rawdata, datasize);
//The above might fail and return null.
if (!rw) {
@@ -64,37 +59,32 @@ CppSdlImageHolder::CppSdlImageHolder(char* rawdata, int datasize)
OptimizeForBlit();
}
-CppSdlImageHolder::~CppSdlImageHolder()
-{
+CppSdlImageHolder::~CppSdlImageHolder() {
MakeNull();
}
-SDL_Surface* CppSdlImageHolder::GetRawDataInsecure()
-{
+SDL_Surface* CppSdlImageHolder::GetRawDataInsecure() {
Initialized();
return data;
}
-Uint32 CppSdlImageHolder::GetWidth()
-{
+Uint32 CppSdlImageHolder::GetWidth() {
if (IsNull()) {
return 0;
}
return area.w;
}
-Uint32 CppSdlImageHolder::GetHeight()
-{
- if(IsNull()) {
+Uint32 CppSdlImageHolder::GetHeight() {
+ if (IsNull()) {
return 0;
}
return area.h;
}
-void CppSdlImageHolder::PaintTo(SDL_Surface* target, int x, int y)
-{
+void CppSdlImageHolder::PaintTo(SDL_Surface* target, int x, int y) {
static SDL_Rect dest; //static for reuse
- if(IsNull()) {
+ if (IsNull()) {
return;
}
dest.x = x;
@@ -102,11 +92,10 @@ void CppSdlImageHolder::PaintTo(SDL_Surface* target, int x, int y)
SDL_BlitSurface(data,&area, target,&dest);
}
-void CppSdlImageHolder::OptimizeForBlit(bool allowAlpha)
-{
- static SDL_Surface *tmp;
+void CppSdlImageHolder::OptimizeForBlit(bool allowAlpha) {
+ static SDL_Surface* tmp;
Initialized();
- if(allowAlpha) {
+ if (allowAlpha) {
tmp = SDL_DisplayFormatAlpha(data);
}
else {
@@ -116,24 +105,21 @@ void CppSdlImageHolder::OptimizeForBlit(bool allowAlpha)
data = tmp;
}
-void CppSdlImageHolder::Initialized()
-{
- if(data == nullptr) {
+void CppSdlImageHolder::Initialized() {
+ if (data == nullptr) {
throw std::runtime_error("ImageHolder used uninitialized!");
}
}
-bool CppSdlImageHolder::IsNull()
-{
- if(data == nullptr ) {
+bool CppSdlImageHolder::IsNull() {
+ if (data == nullptr ) {
return true;
}
return false;
}
-void CppSdlImageHolder::MakeNull()
-{
- if(IsNull()) {
+void CppSdlImageHolder::MakeNull() {
+ if (IsNull()) {
return;
}
SDL_FreeSurface(data);
diff --git a/source/code/Libs/NFont.cpp b/source/code/Libs/NFont.cpp
index d47f7d1..2ea2ac4 100644
--- a/source/code/Libs/NFont.cpp
+++ b/source/code/Libs/NFont.cpp
@@ -38,15 +38,13 @@ NFont::AnimData NFont::data;
#define MAX(a,b) (a > b? a : b)
// Static setters
-void NFont::setAnimData(void* data)
-{
+void NFont::setAnimData(void* data) {
NFont::data.userVar = data;
}
-void NFont::setBuffer(unsigned int size)
-{
+void NFont::setBuffer(unsigned int size) {
delete[] buffer;
- if(size > 0) {
+ if (size > 0) {
buffer = new char[size];
}
else {
@@ -56,19 +54,17 @@ void NFont::setBuffer(unsigned int size)
// Static functions
-char* NFont::copyString(const char* c)
-{
- if(c == NULL) {
+char* NFont::copyString(const char* c) {
+ if (c == NULL) {
return NULL;
}
int count = 0;
- for(; c[count] != '\0'; count++);
+ for (; c[count] != '\0'; count++);
char* result = new char[count+1];
- for(int i = 0; i < count; i++)
- {
+ for (int i = 0; i < count; i++) {
result[i] = c[i];
}
@@ -76,20 +72,18 @@ char* NFont::copyString(const char* c)
return result;
}
-Uint32 NFont::getPixel(SDL_Surface *Surface, int x, int y) // No Alpha?
-{
+Uint32 NFont::getPixel(SDL_Surface* Surface, int x, int y) { // No Alpha?
Uint8* bits;
Uint32 bpp;
- if(x < 0 || x >= Surface->w) {
+ 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)
- {
+ switch (bpp) {
case 1:
return *((Uint8*)Surface->pixels + y * Surface->pitch + x);
break;
@@ -112,8 +106,7 @@ Uint32 NFont::getPixel(SDL_Surface *Surface, int x, int y) // No Alpha?
return 0; // Best I could do for errors
}
-SDL_Rect NFont::rectUnion(const SDL_Rect& A, const SDL_Rect& B)
-{
+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);
@@ -123,15 +116,13 @@ SDL_Rect NFont::rectUnion(const SDL_Rect& A, const SDL_Rect& B)
return result;
}
-SDL_Surface* NFont::copySurface(SDL_Surface *Surface)
-{
+SDL_Surface* NFont::copySurface(SDL_Surface* Surface) {
return SDL_ConvertSurface(Surface, Surface->format, Surface->flags);
}
-SDL_Surface* NFont::verticalGradient(SDL_Surface* targetSurface, Uint32 top, Uint32 bottom, int heightAdjust)
-{
+SDL_Surface* NFont::verticalGradient(SDL_Surface* targetSurface, Uint32 top, Uint32 bottom, int heightAdjust) {
SDL_Surface* surface = targetSurface;
- if(surface == NULL) {
+ if (surface == NULL) {
return NULL;
}
@@ -151,10 +142,8 @@ SDL_Surface* NFont::verticalGradient(SDL_Surface* targetSurface, Uint32 top, Uin
Uint32 color;
int temp;
- for (int x = 0, y = 0; y < surface->h; x++)
- {
- if (x >= surface->w)
- {
+ for (int x = 0, y = 0; y < surface->h; x++) {
+ if (x >= surface->w) {
x = 0;
y++;
@@ -165,8 +154,7 @@ SDL_Surface* NFont::verticalGradient(SDL_Surface* targetSurface, Uint32 top, Uin
ratio = (y - 2)/float(surface->h - heightAdjust); // the neg 3s are for full color at top and bottom
- if(!useCK)
- {
+ if (!useCK) {
color = getPixel(surface, x, y);
SDL_GetRGBA(color, surface->format, &r, &g, &b, &a); // just getting alpha
}
@@ -188,38 +176,35 @@ SDL_Surface* NFont::verticalGradient(SDL_Surface* targetSurface, Uint32 top, Uin
color = SDL_MapRGBA(surface->format, r, g, b, a);
- if(useCK)
- {
- if(getPixel(surface, x, y) == colorkey) {
+ if (useCK) {
+ if (getPixel(surface, x, y) == colorkey) {
continue;
}
- if(color == colorkey) {
+ if (color == colorkey) {
color == 0? color++ : color--;
}
}
// make sure it isn't pink
- if(color == SDL_MapRGBA(surface->format, 0xFF, 0, 0xFF, a)) {
+ 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)) {
+ 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;
+ Uint8* bits = ((Uint8*)surface->pixels) + y*surface->pitch + x*bpp;
/* Set the pixel */
- switch(bpp)
- {
+ switch (bpp) {
case 1:
- *((Uint8 *)(bits)) = (Uint8)color;
+ *((Uint8*)(bits)) = (Uint8)color;
break;
case 2:
- *((Uint16 *)(bits)) = (Uint16)color;
+ *((Uint16*)(bits)) = (Uint16)color;
break;
- case 3: /* Format/endian independent */
- {
+ case 3: { /* Format/endian independent */
r = (color >> surface->format->Rshift) & 0xFF;
g = (color >> surface->format->Gshift) & 0xFF;
b = (color >> surface->format->Bshift) & 0xFF;
@@ -229,7 +214,7 @@ SDL_Surface* NFont::verticalGradient(SDL_Surface* targetSurface, Uint32 top, Uin
}
break;
case 4:
- *((Uint32 *)(bits)) = (Uint32)color;
+ *((Uint32*)(bits)) = (Uint32)color;
break;
}
@@ -239,74 +224,62 @@ SDL_Surface* NFont::verticalGradient(SDL_Surface* targetSurface, Uint32 top, Uin
// Constructors
-NFont::NFont()
-{
+NFont::NFont() {
init();
}
-NFont::NFont(SDL_Surface* src)
-{
+NFont::NFont(SDL_Surface* src) {
init();
load(src);
}
-NFont::NFont(SDL_Surface* dest, SDL_Surface* src)
-{
+NFont::NFont(SDL_Surface* dest, SDL_Surface* src) {
init();
load(src);
setDest(dest);
}
#ifdef NFONT_USE_TTF
-NFont::NFont(TTF_Font* ttf, SDL_Color fg)
-{
+NFont::NFont(TTF_Font* ttf, SDL_Color fg) {
init();
load(ttf, fg);
}
-NFont::NFont(TTF_Font* ttf, SDL_Color fg, SDL_Color bg)
-{
+NFont::NFont(TTF_Font* ttf, SDL_Color fg, SDL_Color bg) {
init();
load(ttf, fg, bg);
}
-NFont::NFont(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style)
-{
+NFont::NFont(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style) {
init();
load(filename_ttf, pointSize, fg, style);
}
-NFont::NFont(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_Color bg, int 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);
}
-NFont::NFont(SDL_Surface* dest, TTF_Font* ttf, SDL_Color fg)
-{
+NFont::NFont(SDL_Surface* dest, TTF_Font* ttf, SDL_Color fg) {
init();
load(ttf, fg);
setDest(dest);
}
-NFont::NFont(SDL_Surface* dest, TTF_Font* ttf, SDL_Color fg, SDL_Color bg)
-{
+NFont::NFont(SDL_Surface* dest, TTF_Font* ttf, SDL_Color fg, SDL_Color bg) {
init();
load(ttf, fg, bg);
setDest(dest);
}
-NFont::NFont(SDL_Surface* dest, const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style)
-{
+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);
}
-NFont::NFont(SDL_Surface* dest, const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_Color bg, int style)
-{
+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);
}
#endif
-void NFont::init()
-{
+void NFont::init() {
src = NULL;
dest = NULL;
@@ -322,21 +295,19 @@ void NFont::init()
lineSpacing = 0;
letterSpacing = 0;
- if(buffer == NULL) {
+ if (buffer == NULL) {
buffer = new char[1024];
}
}
-NFont::~NFont()
-{}
+NFont::~NFont() {
+}
// Loading
-bool NFont::load(SDL_Surface* FontSurface)
-{
+bool NFont::load(SDL_Surface* FontSurface) {
src = FontSurface;
- if (src == NULL)
- {
+ if (src == NULL) {
printf("\n ERROR: NFont given a NULL surface\n");
return false;
}
@@ -344,8 +315,7 @@ bool NFont::load(SDL_Surface* FontSurface)
int x = 1, i = 0;
// memset would be faster
- for(int j = 0; j < 256; j++)
- {
+ for (int j = 0; j < 256; j++) {
charWidth[j] = 0;
charPos[j] = 0;
}
@@ -357,17 +327,15 @@ bool NFont::load(SDL_Surface* FontSurface)
maxWidth = 0;
// Get the character positions and widths
- while (x < src->w)
- {
- if(getPixel(src, x, 0) != pixel)
- {
+ 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) {
+ while (x < src->w && getPixel(src, x, 0) != pixel) {
x++;
}
charWidth[i] = x - charWidth[i];
- if(charWidth[i] > maxWidth) {
+ if (charWidth[i] > maxWidth) {
maxWidth = charWidth[i];
}
i++;
@@ -385,13 +353,10 @@ bool NFont::load(SDL_Surface* FontSurface)
// Get the max ascent
j = 1;
- while(j < baseline && j < src->h)
- {
+ while (j < baseline && j < src->h) {
x = 0;
- while(x < src->w)
- {
- if(getPixel(src, x, j) != pixel)
- {
+ while (x < src->w) {
+ if (getPixel(src, x, j) != pixel) {
ascent = baseline - j;
j = src->h;
break;
@@ -403,13 +368,10 @@ bool NFont::load(SDL_Surface* FontSurface)
// Get the max descent
j = src->h - 1;
- while(j > 0 && j > baseline)
- {
+ while (j > 0 && j > baseline) {
x = 0;
- while(x < src->w)
- {
- if(getPixel(src, x, j) != pixel)
- {
+ while (x < src->w) {
+ if (getPixel(src, x, j) != pixel) {
descent = j - baseline+1;
j = 0;
break;
@@ -423,8 +385,7 @@ bool NFont::load(SDL_Surface* FontSurface)
height = ascent + descent;
- if((src->flags & SDL_SRCALPHA) != SDL_SRCALPHA)
- {
+ if ((src->flags & SDL_SRCALPHA) != SDL_SRCALPHA) {
pixel = getPixel(src, 0, src->h - 1);
SDL_UnlockSurface(src);
SDL_SetColorKey(src, SDL_SRCCOLORKEY, pixel);
@@ -436,16 +397,14 @@ bool NFont::load(SDL_Surface* FontSurface)
return true;
}
-bool NFont::load(SDL_Surface* destSurface, SDL_Surface* FontSurface)
-{
+bool NFont::load(SDL_Surface* destSurface, SDL_Surface* 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) {
+bool NFont::load(TTF_Font* ttf, SDL_Color fg, SDL_Color bg) {
+ if (ttf == NULL) {
return false;
}
SDL_Surface* surfs[127 - 33];
@@ -454,8 +413,7 @@ bool NFont::load(TTF_Font* ttf, SDL_Color fg, SDL_Color bg)
char buff[2];
buff[1] = '\0';
- for(int i = 0; i < 127 - 33; i++)
- {
+ 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;
@@ -475,8 +433,7 @@ bool NFont::load(TTF_Font* ttf, SDL_Color fg, SDL_Color bg)
int x = 1;
SDL_Rect dest = {static_cast<Sint16>(x), 0, 0, 0};
- for(int i = 0; i < 127 - 33; i++)
- {
+ for (int i = 0; i < 127 - 33; i++) {
pixel.x = line.x = x-1;
SDL_FillRect(result, &line, bgcolor);
SDL_FillRect(result, &pixel, pink);
@@ -496,9 +453,8 @@ bool NFont::load(TTF_Font* ttf, SDL_Color fg, SDL_Color bg)
}
-bool NFont::load(TTF_Font* ttf, SDL_Color fg)
-{
- if(ttf == NULL) {
+bool NFont::load(TTF_Font* ttf, SDL_Color fg) {
+ if (ttf == NULL) {
return false;
}
SDL_Surface* surfs[127 - 33];
@@ -507,8 +463,7 @@ bool NFont::load(TTF_Font* ttf, SDL_Color fg)
char buff[2];
buff[1] = '\0';
- for(int i = 0; i < 127 - 33; i++)
- {
+ for (int i = 0; i < 127 - 33; i++) {
buff[0] = i + 33;
surfs[i] = TTF_RenderText_Blended(ttf, buff, fg);
width += surfs[i]->w;
@@ -528,8 +483,7 @@ bool NFont::load(TTF_Font* ttf, SDL_Color fg)
int x = 1;
SDL_Rect dest = {static_cast<Sint16>(x), 0, 0, 0};
- for(int i = 0; i < 127 - 33; i++)
- {
+ for (int i = 0; i < 127 - 33; i++) {
pixel.x = x-1;
SDL_FillRect(result, &pixel, pink);
@@ -550,18 +504,15 @@ bool NFont::load(TTF_Font* ttf, SDL_Color fg)
}
-bool NFont::load(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int style)
-{
- if(!TTF_WasInit() && TTF_Init() < 0)
- {
+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)
- {
+ if (ttf == NULL) {
printf("Unable to load TrueType font: %s \n", TTF_GetError());
return false;
}
@@ -571,18 +522,15 @@ bool NFont::load(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, int s
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)
- {
+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)
- {
+ if (ttf == NULL) {
printf("Unable to load TrueType font: %s \n", TTF_GetError());
return false;
}
@@ -596,22 +544,20 @@ bool NFont::load(const char* filename_ttf, Uint32 pointSize, SDL_Color fg, SDL_C
-void NFont::freeSurface()
-{
+void NFont::freeSurface() {
SDL_FreeSurface(src);
}
// Drawing
-SDL_Rect NFont::drawToSurface(int x, int y, const char* text) const
-{
+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) {
+ if (c == NULL || src == NULL || dest == NULL) {
return data.dirtyRect;
}
@@ -622,34 +568,31 @@ SDL_Rect NFont::drawToSurface(int x, int y, const char* text) const
int newlineX = x;
- for(; *c != '\0'; c++)
- {
- if(*c == '\n')
- {
+ for (; *c != '\0'; c++) {
+ if (*c == '\n') {
dstRect.x = newlineX;
dstRect.y += height + lineSpacing;
continue;
}
- if (*c == ' ')
- {
+ if (*c == ' ') {
dstRect.x += charWidth[0] + letterSpacing;
continue;
}
unsigned char ctest = (unsigned char)(*c);
// Skip bad characters
- if(ctest < 33 || (ctest > 126 && ctest < 161)) {
+ if (ctest < 33 || (ctest > 126 && ctest < 161)) {
continue;
}
- if(dstRect.x >= dest->w) {
+ if (dstRect.x >= dest->w) {
continue;
}
- if(dstRect.y >= dest->h) {
+ if (dstRect.y >= dest->h) {
continue;
}
num = ctest - 33; // Get array index
- if(num > 126) { // shift the extended characters down to the correct index
+ if (num > 126) { // shift the extended characters down to the correct index
num -= 34;
}
srcRect.x = charPos[num];
@@ -657,7 +600,7 @@ SDL_Rect NFont::drawToSurface(int x, int y, const char* text) const
copyS = srcRect;
copyD = dstRect;
SDL_BlitSurface(src, &srcRect, dest, &dstRect);
- if(data.dirtyRect.w == 0 || data.dirtyRect.h == 0) {
+ if (data.dirtyRect.w == 0 || data.dirtyRect.h == 0) {
data.dirtyRect = dstRect;
}
else {
@@ -672,8 +615,7 @@ SDL_Rect NFont::drawToSurface(int x, int y, const char* text) const
return data.dirtyRect;
}
-SDL_Rect NFont::drawToSurfacePos(int x, int y, NFont::AnimFn posFn) const
-{
+SDL_Rect NFont::drawToSurfacePos(int x, int y, NFont::AnimFn posFn) const {
data.font = this;
data.dest = dest;
data.src = src;
@@ -698,7 +640,7 @@ SDL_Rect NFont::drawToSurfacePos(int x, int y, NFont::AnimFn posFn) const
unsigned char num;
SDL_Rect srcRect, dstRect, copyS, copyD;
- if(c == NULL || src == NULL || dest == NULL) {
+ if (c == NULL || src == NULL || dest == NULL) {
return makeRect(x,y,0,0);
}
@@ -707,13 +649,11 @@ SDL_Rect NFont::drawToSurfacePos(int x, int y, NFont::AnimFn posFn) const
dstRect.x = x;
dstRect.y = y;
- for(; *c != '\0'; c++)
- {
+ for (; *c != '\0'; c++) {
data.index++;
data.letterNum++;
- if(*c == '\n')
- {
+ if (*c == '\n') {
data.letterNum = 1;
data.wordNum = 1;
data.lineNum++;
@@ -722,8 +662,7 @@ SDL_Rect NFont::drawToSurfacePos(int x, int y, NFont::AnimFn posFn) const
y += height + lineSpacing;
continue;
}
- if (*c == ' ')
- {
+ if (*c == ' ') {
data.letterNum = 1;
data.wordNum++;
@@ -732,13 +671,13 @@ SDL_Rect NFont::drawToSurfacePos(int x, int y, NFont::AnimFn posFn) const
}
unsigned char ctest = (unsigned char)(*c);
// Skip bad characters
- if(ctest < 33 || (ctest > 126 && ctest < 161)) {
+ 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
+ if (num > 126) { // shift the extended characters down to the array index
num -= 34;
}
srcRect.x = charPos[num];
@@ -756,7 +695,7 @@ SDL_Rect NFont::drawToSurfacePos(int x, int y, NFont::AnimFn posFn) const
copyS = srcRect;
copyD = dstRect;
SDL_BlitSurface(src, &srcRect, dest, &dstRect);
- if(data.dirtyRect.w == 0 || data.dirtyRect.h == 0) {
+ if (data.dirtyRect.w == 0 || data.dirtyRect.h == 0) {
data.dirtyRect = dstRect;
}
else {
@@ -774,9 +713,8 @@ SDL_Rect NFont::drawToSurfacePos(int x, int y, NFont::AnimFn posFn) const
return data.dirtyRect;
}
-SDL_Rect NFont::draw(int x, int y, const char* formatted_text, ...) const
-{
- if(formatted_text == NULL) {
+SDL_Rect NFont::draw(int x, int y, const char* formatted_text, ...) const {
+ if (formatted_text == NULL) {
return makeRect(x, y, 0, 0);
}
@@ -788,9 +726,8 @@ SDL_Rect NFont::draw(int x, int y, const char* formatted_text, ...) const
return drawToSurface(x, y, buffer);
}
-SDL_Rect NFont::drawCenter(int x, int y, const char* formatted_text, ...) const
-{
- if(formatted_text == NULL) {
+SDL_Rect NFont::drawCenter(int x, int y, const char* formatted_text, ...) const {
+ if (formatted_text == NULL) {
return makeRect(x, y, 0, 0);
}
@@ -804,10 +741,8 @@ SDL_Rect NFont::drawCenter(int x, int y, const char* formatted_text, ...) const
// 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')
- {
+ for (char* c = str; *c != '\0';) {
+ if (*c == '\n') {
*c = '\0';
drawToSurface(x - getWidth("%s", str)/2, y, str);
*c = '\n';
@@ -826,9 +761,8 @@ SDL_Rect NFont::drawCenter(int x, int y, const char* formatted_text, ...) const
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) {
+SDL_Rect NFont::drawRight(int x, int y, const char* formatted_text, ...) const {
+ if (formatted_text == NULL) {
return makeRect(x, y, 0, 0);
}
@@ -840,10 +774,8 @@ SDL_Rect NFont::drawRight(int x, int y, const char* formatted_text, ...) const
char* str = copyString(buffer);
char* del = str;
- for(char* c = str; *c != '\0';)
- {
- if(*c == '\n')
- {
+ for (char* c = str; *c != '\0';) {
+ if (*c == '\n') {
*c = '\0';
drawToSurface(x - getWidth("%s", str), y, str);
*c = '\n';
@@ -862,8 +794,7 @@ SDL_Rect NFont::drawRight(int x, int y, const char* formatted_text, ...) const
return drawToSurface(x - getWidth("%s", s), y, s);
}
-SDL_Rect NFont::drawPos(int x, int y, NFont::AnimFn posFn, const char* text, ...) const
-{
+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);
@@ -872,8 +803,7 @@ SDL_Rect NFont::drawPos(int x, int y, NFont::AnimFn posFn, const char* text, ...
return drawToSurfacePos(x, y, posFn);
}
-SDL_Rect NFont::drawAll(int x, int y, NFont::AnimFn allFn, const char* text, ...) const
-{
+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);
@@ -887,19 +817,16 @@ SDL_Rect NFont::drawAll(int x, int y, NFont::AnimFn allFn, const char* text, ...
// Getters
-SDL_Surface* NFont::getDest() const
-{
+SDL_Surface* NFont::getDest() const {
return dest;
}
-SDL_Surface* NFont::getSurface() const
-{
+SDL_Surface* NFont::getSurface() const {
return src;
}
-int NFont::getHeight(const char* formatted_text, ...) const
-{
- if(formatted_text == NULL) {
+int NFont::getHeight(const char* formatted_text, ...) const {
+ if (formatted_text == NULL) {
return height;
}
@@ -911,9 +838,8 @@ int NFont::getHeight(const char* formatted_text, ...) const
int numLines = 1;
const char* c;
- for (c = buffer; *c != '\0'; c++)
- {
- if(*c == '\n') {
+ for (c = buffer; *c != '\0'; c++) {
+ if (*c == '\n') {
numLines++;
}
}
@@ -922,8 +848,7 @@ int NFont::getHeight(const char* formatted_text, ...) const
return height*numLines + lineSpacing*(numLines - 1); //height*numLines;
}
-int NFont::getWidth(const char* formatted_text, ...) const
-{
+int NFont::getWidth(const char* formatted_text, ...) const {
if (formatted_text == NULL) {
return 0;
}
@@ -938,18 +863,15 @@ int NFont::getWidth(const char* formatted_text, ...) const
int width = 0;
int bigWidth = 0; // Allows for multi-line strings
- for (c = buffer; *c != '\0'; c++)
- {
+ for (c = buffer; *c != '\0'; c++) {
charnum = (unsigned char)(*c) - 33;
// skip spaces and nonprintable characters
- if(*c == '\n')
- {
+ if (*c == '\n') {
bigWidth = bigWidth >= width? bigWidth : width;
width = 0;
}
- else if (*c == ' ' || charnum > 222)
- {
+ else if (*c == ' ' || charnum > 222) {
width += charWidth[0];
continue;
}
@@ -961,10 +883,9 @@ int NFont::getWidth(const char* formatted_text, ...) const
return bigWidth;
}
-int NFont::getAscent(const char character) const
-{
+int NFont::getAscent(const char character) const {
unsigned char test = (unsigned char)character;
- if(test < 33 || test > 222 || (test > 126 && test < 161)) {
+ if (test < 33 || test > 222 || (test > 126 && test < 161)) {
return 0;
}
unsigned char num = (unsigned char)character - 33;
@@ -972,13 +893,10 @@ int NFont::getAscent(const char character) const
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)
- {
+ while (j < baseline && j < src->h) {
i = charPos[num];
- while(i < x + charWidth[num])
- {
- if(getPixel(src, i, j) != pixel)
- {
+ while (i < x + charWidth[num]) {
+ if (getPixel(src, i, j) != pixel) {
result = baseline - j;
j = src->h;
break;
@@ -990,9 +908,8 @@ int NFont::getAscent(const char character) const
return result;
}
-int NFont::getAscent(const char* formatted_text, ...) const
-{
- if(formatted_text == NULL) {
+int NFont::getAscent(const char* formatted_text, ...) const {
+ if (formatted_text == NULL) {
return ascent;
}
@@ -1004,20 +921,18 @@ int NFont::getAscent(const char* formatted_text, ...) const
int max = 0;
const char* c = buffer;
- for (; *c != '\0'; c++)
- {
+ for (; *c != '\0'; c++) {
int asc = getAscent(*c);
- if(asc > max) {
+ if (asc > max) {
max = asc;
}
}
return max;
}
-int NFont::getDescent(const char character) const
-{
+int NFont::getDescent(const char character) const {
unsigned char test = (unsigned char)character;
- if(test < 33 || test > 222 || (test > 126 && test < 161)) {
+ if (test < 33 || test > 222 || (test > 126 && test < 161)) {
return 0;
}
unsigned char num = (unsigned char)character - 33;
@@ -1025,13 +940,10 @@ int NFont::getDescent(const char character) const
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)
- {
+ while (j > 0 && j > baseline) {
i = charPos[num];
- while(i < x + charWidth[num])
- {
- if(getPixel(src, i, j) != pixel)
- {
+ while (i < x + charWidth[num]) {
+ if (getPixel(src, i, j) != pixel) {
result = j - baseline;
j = 0;
break;
@@ -1043,9 +955,8 @@ int NFont::getDescent(const char character) const
return result;
}
-int NFont::getDescent(const char* formatted_text, ...) const
-{
- if(formatted_text == NULL) {
+int NFont::getDescent(const char* formatted_text, ...) const {
+ if (formatted_text == NULL) {
return descent;
}
@@ -1057,33 +968,28 @@ int NFont::getDescent(const char* formatted_text, ...) const
int max = 0;
const char* c = buffer;
- for (; *c != '\0'; c++)
- {
+ for (; *c != '\0'; c++) {
int des = getDescent(*c);
- if(des > max) {
+ if (des > max) {
max = des;
}
}
return max;
}
-int NFont::getSpacing() const
-{
+int NFont::getSpacing() const {
return letterSpacing;
}
-int NFont::getLineSpacing() const
-{
+int NFont::getLineSpacing() const {
return lineSpacing;
}
-int NFont::getBaseline() const
-{
+int NFont::getBaseline() const {
return baseline;
}
-int NFont::getMaxWidth() const
-{
+int NFont::getMaxWidth() const {
return maxWidth;
}
@@ -1092,45 +998,36 @@ int NFont::getMaxWidth() const
// Setters
-void NFont::setSpacing(int LetterSpacing)
-{
+void NFont::setSpacing(int LetterSpacing) {
letterSpacing = LetterSpacing;
}
-void NFont::setLineSpacing(int LineSpacing)
-{
+void NFont::setLineSpacing(int LineSpacing) {
lineSpacing = LineSpacing;
}
-void NFont::setDest(SDL_Surface* Dest)
-{
+void NFont::setDest(SDL_Surface* Dest) {
dest = Dest;
}
-int NFont::setBaseline(int Baseline)
-{
- if(Baseline >= 0) {
+int NFont::setBaseline(int Baseline) {
+ if (Baseline >= 0) {
baseline = Baseline;
}
- else
- {
+ 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++)
- {
+ for (unsigned char avgChar = 64; avgChar < 67; avgChar++) {
x = charPos[avgChar];
j = src->h - 1;
- while(j > 0)
- {
+ while (j > 0) {
i = x;
- while(i - x < charWidth[64])
- {
- if(getPixel(src, i, j) != pixel)
- {
+ while (i - x < charWidth[64]) {
+ if (getPixel(src, i, j) != pixel) {
heightSum += j;
j = 0;
break;
diff --git a/source/code/Makefile b/source/code/Makefile
index 3fa8788..8a8acf9 100644
--- a/source/code/Makefile
+++ b/source/code/Makefile
@@ -76,4 +76,4 @@ clean:
SOURCE_FILES = $(OFILES:.o=.cpp)
format:
- astyle -t -j -y -c $(SOURCE_FILES)
+ astyle -t -j -y -c -k1 -z2 -A2 --pad-header $(SOURCE_FILES)
diff --git a/source/code/MenuSystem.cpp b/source/code/MenuSystem.cpp
index 63c5e17..202c636 100644
--- a/source/code/MenuSystem.cpp
+++ b/source/code/MenuSystem.cpp
@@ -28,7 +28,7 @@ http://blockattack.sf.net
#include "CppSdlImageHolder.hpp"
extern std::shared_ptr<CppSdl::CppSdlImageHolder> mouse;
-extern SDL_Surface *backgroundImage;
+extern SDL_Surface* backgroundImage;
extern bool highPriority;
extern int verboseLevel;
int mousex;
@@ -37,8 +37,7 @@ int mousey;
using namespace std;
/*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)
-{
+inline void DrawIMG(SDL_Surface* img, SDL_Surface* target, int x, int y) {
SDL_Rect dest;
dest.x = x;
dest.y = y;
@@ -47,19 +46,17 @@ inline void DrawIMG(SDL_Surface *img, SDL_Surface *target, int x, int y)
ButtonGfx standardButton;
-void ButtonGfx::setSurfaces(shared_ptr<CppSdl::CppSdlImageHolder> marked, shared_ptr<CppSdl::CppSdlImageHolder> unmarked)
-{
+void ButtonGfx::setSurfaces(shared_ptr<CppSdl::CppSdlImageHolder> marked, shared_ptr<CppSdl::CppSdlImageHolder> unmarked) {
this->marked = marked;
this->unmarked = unmarked;
xsize=(marked)->GetWidth();
ysize=(marked)->GetHeight();
- if(verboseLevel) {
+ if (verboseLevel) {
cout << "Surfaces set, size: " <<xsize << " , " << ysize << endl;
}
}
-Button::Button()
-{
+Button::Button() {
gfx = &standardButton;
label = "";
marked = false;
@@ -67,12 +64,10 @@ Button::Button()
popOnRun = false;
}
-Button::~Button()
-{
+Button::~Button() {
}
-Button::Button(const Button& b)
-{
+Button::Button(const Button& b) {
gfx = b.gfx;
label = b.label;
marked = b.marked;
@@ -80,26 +75,22 @@ Button::Button(const Button& b)
popOnRun = false;
}
-void Button::setLabel(const string& text)
-{
+void Button::setLabel(const string& text) {
label = text;
}
-void Button::setAction(void (*action2run)(Button*))
-{
+void Button::setAction(void (*action2run)(Button*)) {
action = action2run;
}
-bool Button::isClicked(int x,int y)
-{
+bool Button::isClicked(int x,int y) {
if ( x >= this->x && y >= this->y && x<= this->x+gfx->xsize && y <= this->y + gfx->ysize) {
return true;
}
return false;
}
-void Button::doAction()
-{
+void Button::doAction() {
if (action) {
action(this);
return;
@@ -107,8 +98,7 @@ void Button::doAction()
cerr << "Warning: button \"" << label << "\" has no action assigned!";
}
-void Button::drawTo(SDL_Surface **surface)
-{
+void Button::drawTo(SDL_Surface** surface) {
#if DEBUG
//cout << "Painting button: " << label << " at: " << x << "," << y << endl;
#endif
@@ -122,28 +112,23 @@ void Button::drawTo(SDL_Surface **surface)
gfx->thefont.drawCenter(x+gfx->xsize/2,y+gfx->ysize/2-gfx->thefont.getHeight(label.c_str())/2,label.c_str());
}
-void Button::setPopOnRun(bool popOnRun)
-{
+void Button::setPopOnRun(bool popOnRun) {
this->popOnRun = popOnRun;
}
-bool Button::isPopOnRun() const
-{
+bool Button::isPopOnRun() const {
return popOnRun;
}
-void Button::setGfx(ButtonGfx* gfx)
-{
+void Button::setGfx(ButtonGfx* gfx) {
this->gfx = gfx;
}
-int Button::getHeight()
-{
+int Button::getHeight() {
return this->gfx->ysize;
}
-void Menu::drawSelf()
-{
+void Menu::drawSelf() {
DrawIMG(backgroundImage,screen,0,0);
vector<Button*>::iterator it;
for (it = buttons.begin(); it < buttons.end(); it++) {
@@ -154,12 +139,10 @@ void Menu::drawSelf()
mouse->PaintTo(screen,mousex,mousey);
}
-void Menu::performClick(int x,int y)
-{
+void Menu::performClick(int x,int y) {
vector<Button*>::iterator it;
- for(it = buttons.begin(); it < buttons.end(); it++)
- {
- Button *b = (*it);
+ for (it = buttons.begin(); it < buttons.end(); it++) {
+ Button* b = (*it);
if (b->isClicked(x,y)) {
b->doAction();
}
@@ -172,13 +155,11 @@ void Menu::performClick(int x,int y)
}
}
-void Menu::placeButtons()
-{
+void Menu::placeButtons() {
int nextY = 100;
const int X = 50;
vector<Button*>::iterator it;
- for(it = buttons.begin(); it < buttons.end(); it++)
- {
+ for (it = buttons.begin(); it < buttons.end(); it++) {
(*it)->x = X;
(*it)->y = nextY;
nextY += (*it)->getHeight()+10;
@@ -187,27 +168,24 @@ void Menu::placeButtons()
exit.y = nextY;
}
-void Menu::addButton(Button *b)
-{
+void Menu::addButton(Button* b) {
buttons.push_back(b);
b->marked = false;
placeButtons();
}
-Menu::Menu(SDL_Surface **screen)
-{
+Menu::Menu(SDL_Surface** screen) {
this->screen = *screen;
buttons = vector<Button*>(10);
isSubmenu = true;
exit.setLabel( _("Back") );
}
-Menu::Menu(SDL_Surface **screen,bool submenu)
-{
+Menu::Menu(SDL_Surface** screen,bool submenu) {
this->screen = *screen;
buttons = vector<Button*>(0);
isSubmenu = submenu;
- if(isSubmenu) {
+ if (isSubmenu) {
exit.setLabel( _("Back") );
}
else {
@@ -215,13 +193,12 @@ Menu::Menu(SDL_Surface **screen,bool submenu)
}
}
-Menu::Menu(SDL_Surface** screen, const string& title, bool submenu)
-{
+Menu::Menu(SDL_Surface** screen, const string& title, bool submenu) {
this->screen = *screen;
buttons = vector<Button*>(0);
isSubmenu = submenu;
this->title = title;
- if(isSubmenu) {
+ if (isSubmenu) {
exit.setLabel(_("Back") );
}
else {
@@ -229,14 +206,12 @@ Menu::Menu(SDL_Surface** screen, const string& title, bool submenu)
}
}
-void Menu::run()
-{
+void Menu::run() {
running = true;
bool bMouseUp = false;
long oldmousex = mousex;
long oldmousey = mousey;
- while(running && !Config::getInstance()->isShuttingDown())
- {
+ while (running && !Config::getInstance()->isShuttingDown()) {
if (!(highPriority)) {
SDL_Delay(10);
}
@@ -244,47 +219,39 @@ void Menu::run()
SDL_Event event;
- while ( SDL_PollEvent(&event) )
- {
- if ( event.type == SDL_QUIT )
- {
+ 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 )
- {
+ if ( event.type == SDL_KEYDOWN ) {
+ if ( event.key.keysym.sym == SDLK_ESCAPE ) {
running = false;
}
- if (event.key.keysym.sym == SDLK_UP)
- {
+ if (event.key.keysym.sym == SDLK_UP) {
marked--;
- if(marked<0) {
+ 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)
- {
+ if (event.key.keysym.sym == SDLK_DOWN) {
marked++;
- if(marked>buttons.size()) {
+ if (marked>buttons.size()) {
marked = 0;
}
}
- if(event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER )
- {
- if(marked < buttons.size())
- {
+ if (event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER ) {
+ if (marked < buttons.size()) {
buttons.at(marked)->doAction();
- if(buttons.at(marked)->isPopOnRun()) {
+ if (buttons.at(marked)->isPopOnRun()) {
running = false;
}
}
- if(marked == buttons.size()) {
+ if (marked == buttons.size()) {
running = false;
}
}
@@ -293,29 +260,23 @@ void Menu::run()
}
- for(int i=0; i<buttons.size(); i++)
- {
+ for (int i=0; i<buttons.size(); i++) {
buttons.at(i)->marked = (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)
- {
+ 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))
- {
+ 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))
- {
+ if (exit.isClicked(mousex,mousey)) {
marked = buttons.size();
}
oldmousex = mousex;
@@ -323,22 +284,18 @@ void Menu::run()
}
//mouse clicked
- if( (buttonState&SDL_BUTTON(1) )==SDL_BUTTON(1) && bMouseUp)
- {
+ 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))
- {
+ for (int i=0; i< buttons.size(); ++i) {
+ if (buttons.at(i)->isClicked(mousex,mousey)) {
buttons.at(i)->doAction();
- if(buttons.at(i)->isPopOnRun()) {
+ if (buttons.at(i)->isPopOnRun()) {
running = false;
}
mousex = 0;
}
}
- if(exit.isClicked(mousex,mousey))
- {
+ if (exit.isClicked(mousex,mousey)) {
running = false;
}
}
diff --git a/source/code/ReadKeyboard.cpp b/source/code/ReadKeyboard.cpp
index 4a9e6fb..a31cc4a 100644
--- a/source/code/ReadKeyboard.cpp
+++ b/source/code/ReadKeyboard.cpp
@@ -26,25 +26,21 @@ http://blockattack.sf.net
using namespace std;
-ReadKeyboard::ReadKeyboard(void)
-{
+ReadKeyboard::ReadKeyboard(void) {
length = 0;
maxLength = 16;
position = 0;
strcpy(textstring," ");
}
-ReadKeyboard::~ReadKeyboard(void)
-{
+ReadKeyboard::~ReadKeyboard(void) {
}
-Uint8 ReadKeyboard::CharsBeforeCursor()
-{
+Uint8 ReadKeyboard::CharsBeforeCursor() {
return position;
}
-ReadKeyboard::ReadKeyboard(const char *oldName)
-{
+ReadKeyboard::ReadKeyboard(const char* oldName) {
length = 0;
maxLength = 16;
position = 0;
@@ -52,8 +48,7 @@ ReadKeyboard::ReadKeyboard(const char *oldName)
strncpy(textstring,oldName,strlen(oldName));
char charecter = textstring[maxLength+1];
int i = maxLength+1;
- while ((charecter == ' ') && (i>0))
- {
+ while ((charecter == ' ') && (i>0)) {
i--;
charecter = textstring[i];
}
@@ -71,12 +66,9 @@ ReadKeyboard::ReadKeyboard(const char *oldName)
}
-void ReadKeyboard::putchar(char thing)
-{
- if (length < maxLength)
- {
- for (int i = 28; i>position; i--)
- {
+void ReadKeyboard::putchar(char thing) {
+ if (length < maxLength) {
+ for (int i = 28; i>position; i--) {
textstring[i]=textstring[i-1];
}
textstring[position] = thing;
@@ -86,10 +78,8 @@ void ReadKeyboard::putchar(char thing)
}
-void ReadKeyboard::removeChar()
-{
- for (int i = position; i<28; i++)
- {
+void ReadKeyboard::removeChar() {
+ for (int i = position; i<28; i++) {
textstring[i]=textstring[i+1];
}
textstring[28]=' ';
@@ -98,24 +88,19 @@ void ReadKeyboard::removeChar()
}
}
-bool ReadKeyboard::ReadKey(SDLKey keyPressed)
-{
- if (keyPressed == SDLK_SPACE)
- {
+bool ReadKeyboard::ReadKey(SDLKey keyPressed) {
+ if (keyPressed == SDLK_SPACE) {
ReadKeyboard::putchar(' ');
return true;
}
- if (keyPressed == SDLK_DELETE)
- {
+ if (keyPressed == SDLK_DELETE) {
if ((length>0)&& (position<length)) {
ReadKeyboard::removeChar();
}
return true;
}
- if (keyPressed == SDLK_BACKSPACE)
- {
- if (position>0)
- {
+ if (keyPressed == SDLK_BACKSPACE) {
+ if (position>0) {
position--;
ReadKeyboard::removeChar();
return true;
@@ -124,30 +109,25 @@ bool ReadKeyboard::ReadKey(SDLKey keyPressed)
}
Uint8* keys;
keys = SDL_GetKeyState(nullptr);
- if (keyPressed == SDLK_HOME)
- {
+ if (keyPressed == SDLK_HOME) {
position=0;
return true;
}
- if (keyPressed == SDLK_END)
- {
+ if (keyPressed == SDLK_END) {
position=length;
return true;
}
- if ((keyPressed == SDLK_LEFT) && (position>0))
- {
+ if ((keyPressed == SDLK_LEFT) && (position>0)) {
position--;
return true;
}
- if ((keyPressed == SDLK_RIGHT) && (position<length))
- {
+ if ((keyPressed == SDLK_RIGHT) && (position<length)) {
position++;
return true;
}
char charToPut;
- if(keyPressed)
- switch (keyPressed)
- {
+ if (keyPressed)
+ switch (keyPressed) {
case SDLK_a:
charToPut = 'a';
break;
@@ -293,10 +273,8 @@ bool ReadKeyboard::ReadKey(SDLKey keyPressed)
default:
return false;
}
- if ((keys[SDLK_LSHIFT]) || (keys[SDLK_RSHIFT]))
- {
- switch (charToPut)
- {
+ if ((keys[SDLK_LSHIFT]) || (keys[SDLK_RSHIFT])) {
+ switch (charToPut) {
case 'a':
charToPut = 'A';
break;
@@ -384,8 +362,7 @@ bool ReadKeyboard::ReadKey(SDLKey keyPressed)
return true;
}
-const char* ReadKeyboard::GetString()
-{
+const char* ReadKeyboard::GetString() {
textstring[29]='\0';
return &textstring[0];
}
diff --git a/source/code/common.cpp b/source/code/common.cpp
index fa081c0..93439d1 100644
--- a/source/code/common.cpp
+++ b/source/code/common.cpp
@@ -30,16 +30,14 @@ using boost::format;
static stringstream converter;
//Function to convert numbers to string
-string itoa(int num)
-{
+string itoa(int num) {
converter.str(std::string());
converter.clear();
converter << num;
return converter.str();
}
-string double2str(double num)
-{
+string double2str(double num) {
converter.str(std::string());
converter.clear();
converter << num;
@@ -51,18 +49,15 @@ string double2str(double num)
* if the string is not a double then 0.0 is returned instead of throing an error
* in that way this function will always return a useable value.
*/
-double str2double(const string &str2parse)
-{
- try
- {
+double str2double(const string& str2parse) {
+ try {
converter.clear();
converter.str(str2parse);
double val = 0.0;
converter >> val;
return val;
}
- catch(ios_base::failure &f)
- {
+ catch (ios_base::failure& f) {
return 0.0;
}
}
@@ -72,30 +67,25 @@ double str2double(const string &str2parse)
* if the string is not an int then 0 is returned instead of throing an error
* in that way this function will always return a useable value.
*/
-int str2int(const string &str2parse)
-{
- try
- {
+int str2int(const string& str2parse) {
+ try {
converter.clear();
converter.str(str2parse);
int val = 0;
converter >> val;
return val;
}
- catch(ios_base::failure &f)
- {
+ catch (ios_base::failure& f) {
return 0;
}
}
#ifdef WIN32
//Returns path to "my Documents" in windows:
-string getMyDocumentsPath()
-{
+string getMyDocumentsPath() {
TCHAR pszPath[MAX_PATH];
//if (SUCCEEDED(SHGetSpecialFolderPath(nullptr, pszPath, CSIDL_PERSONAL, FALSE))) {
- if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_PERSONAL, nullptr, 0, pszPath)))
- {
+ if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_PERSONAL, nullptr, 0, pszPath))) {
// pszPath is now the path that you want
#if DEBUG
cout << "MyDocuments Located: " << pszPath << endl;
@@ -103,8 +93,7 @@ string getMyDocumentsPath()
string theResult= pszPath;
return theResult;
}
- else
- {
+ else {
cout << "Warning: My Documents not found!" << endl;
string theResult ="";
return theResult;
@@ -119,8 +108,7 @@ string getMyDocumentsPath()
* In Windows it is My Documents/My Games
* Consider changing this for Vista that has a special save games folder
*/
-string getPathToSaveFiles()
-{
+string getPathToSaveFiles() {
#ifdef __unix__
return (string)getenv("HOME")+(string)"/.gamesaves/"+GAMENAME;
#elif WIN32
@@ -133,8 +121,7 @@ string getPathToSaveFiles()
/**
* Takes a number of milliseconds and returns the value in commonTime format.
*/
-commonTime TimeHandler::ms2ct(unsigned int milliseconds)
-{
+commonTime TimeHandler::ms2ct(unsigned int milliseconds) {
commonTime ct;
ct.days = 0;
unsigned int time = milliseconds;
@@ -146,8 +133,7 @@ commonTime TimeHandler::ms2ct(unsigned int milliseconds)
return ct;
}
-commonTime TimeHandler::getTime(const string &name)
-{
+commonTime TimeHandler::getTime(const string& name) {
commonTime ct;
ct.days = Config::getInstance()->getInt(name+"Days");
ct.hours = Config::getInstance()->getInt(name+"Hours");
@@ -160,8 +146,7 @@ commonTime TimeHandler::getTime(const string &name)
* Returns the total runtime with toAdd added but without writing it to config file.
* Used for stats
*/
-commonTime TimeHandler::peekTime(const string &name, const commonTime &toAdd)
-{
+commonTime TimeHandler::peekTime(const string& name, const commonTime& toAdd) {
commonTime ct = getTime(name);
ct.seconds +=toAdd.seconds;
@@ -184,8 +169,7 @@ commonTime TimeHandler::peekTime(const string &name, const commonTime &toAdd)
* Same as peekTotalTime but writes the time to the config file.
* Should only be called only once! when the program shuts down
*/
-commonTime TimeHandler::addTime(const string &name, const commonTime &toAdd)
-{
+commonTime TimeHandler::addTime(const string& name, const commonTime& toAdd) {
commonTime ct = peekTime(name,toAdd);
Config::getInstance()->setInt(name+"Days",ct.days);
@@ -197,26 +181,22 @@ commonTime TimeHandler::addTime(const string &name, const commonTime &toAdd)
Config* Config::instance = 0;
-Config::Config()
-{
+Config::Config() {
configMap.clear();
load();
shuttingDown = 0; // Not shutting down
}
-void Config::load()
-{
+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())
- {
+ 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
+ if (key==previuskey) { //the last entry will be read 2 times if a linebreak is missing in the end
continue;
}
previuskey = key;
@@ -231,26 +211,21 @@ void Config::load()
}
}
-Config* Config::getInstance()
-{
- if(Config::instance==0)
- {
+Config* Config::getInstance() {
+ if (Config::instance==0) {
Config::instance = new Config();
}
return Config::instance;
}
-void Config::save()
-{
+void Config::save() {
string filename = getPathToSaveFiles()+"/configFile";
ofstream outFile(filename.c_str(),ios::trunc);
- if(outFile)
- {
+ if (outFile) {
map<string,string>::iterator iter;
- for(iter = configMap.begin(); iter != configMap.end(); 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
@@ -259,49 +234,40 @@ void Config::save()
outFile.close();
}
-bool Config::exists(const string &varName) const
-{
+bool Config::exists(const string& varName) const {
//Using that find returns an iterator to the end of the map if not found
return configMap.find(varName) != configMap.end();
}
-void Config::setDefault(const string &varName,const string &content)
-{
- if(exists(varName)) {
+void Config::setDefault(const string& varName,const string& content) {
+ if (exists(varName)) {
return; //Already exists do not change
}
setString(varName,content);
}
-void Config::setShuttingDown(long shuttingDown)
-{
+void Config::setShuttingDown(long shuttingDown) {
this->shuttingDown = shuttingDown;
}
-long Config::isShuttingDown() const
-{
+long Config::isShuttingDown() const {
return shuttingDown;
}
-void Config::setString(const string &varName, const string &content)
-{
+void Config::setString(const string& varName, const string& content) {
configMap[varName] = content;
}
-void Config::setInt(const string &varName, int content)
-{
+void Config::setInt(const string& varName, int content) {
configMap[varName] = itoa(content);
}
-void Config::setValue(const string &varName,double content)
-{
+void Config::setValue(const string& varName,double content) {
configMap[varName] = double2str(content);
}
-string Config::getString(const string &varName)
-{
- if(exists(varName))
- {
+string Config::getString(const string& varName) {
+ if (exists(varName)) {
return configMap[varName];
}
else {
@@ -309,10 +275,8 @@ string Config::getString(const string &varName)
}
}
-int Config::getInt(const string &varName)
-{
- if(exists(varName))
- {
+int Config::getInt(const string& varName) {
+ if (exists(varName)) {
return str2int(configMap[varName]);
}
else {
@@ -320,10 +284,8 @@ int Config::getInt(const string &varName)
}
}
-double Config::getValue(const string &varName)
-{
- if(exists(varName))
- {
+double Config::getValue(const string& varName) {
+ if (exists(varName)) {
return str2double(configMap[varName]);
}
else {
diff --git a/source/code/highscore.cpp b/source/code/highscore.cpp
index cf72c50..513fcc2 100644
--- a/source/code/highscore.cpp
+++ b/source/code/highscore.cpp
@@ -1,184 +1,164 @@
-/*
-===========================================================================
-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 "highscore.h"
-
-using namespace std;
-
-#ifdef WIN32
-
-//Returns path to "my Documents" in windows:
-string getMyDocumentsPath1()
-{
- TCHAR pszPath[MAX_PATH];
- //if (SUCCEEDED(SHGetSpecialFolderPath(nullptr, pszPath, CSIDL_PERSONAL, FALSE))) {
- if (SUCCEEDED(SHGetSpecialFolderPath(nullptr, 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
-
-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";
-#elif defined(_WIN32)
- string home = getMyDocumentsPath1();
- string filename1, filename2;
- if (&home!=nullptr)
- {
- 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";
-#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<top; i++)
- {
- scorefile.read(tabel[i].name,30*sizeof(char));
- scorefile.read(reinterpret_cast<char*>(&tabel[i].score), sizeof(int));
- }
- }
- else
- {
- for (int i = 0; i<top; i++)
- {
- strcpy(tabel[i].name,"Poul Sander \0");
- tabel[i].score = 2000 - i*100;
- }
- }
- scorefile.close();
- writeFile();
-}
-
-void Highscore::writeFile()
-{
-#if defined(__unix__)
- 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!=nullptr)
- {
- 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";
-#endif
- 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<top; i++)
- {
- outfile.write(tabel[i].name,30*sizeof(char));
- outfile.write(reinterpret_cast<char*>(&tabel[i].score),sizeof(int));
- }
- outfile.close();
-}
-
-bool Highscore::isHighScore(int newScore)
-{
- if (newScore>tabel[top-1].score) {
- return true;
- }
- else {
- return false;
- }
-}
-
-void Highscore::addScore(const string& newName, int newScore)
-{
- int ranking = top-1;
- while ((tabel[ranking-1].score<newScore) && (ranking != 0)) {
- ranking--;
- }
- for (int i=top-1; i>ranking; 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");
- snprintf(tabel[ranking].name, sizeof(tabel[ranking].name), "%s", newName.c_str());
- Highscore::writeFile();
-}
-
-int Highscore::getScoreNumber(int room)
-{
- return tabel[room].score;
-}
-
-char* Highscore::getScoreName(int room)
-{
- return &tabel[room].name[0];
-}
+/*
+===========================================================================
+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 "highscore.h"
+
+using namespace std;
+
+#ifdef WIN32
+
+//Returns path to "my Documents" in windows:
+string getMyDocumentsPath1() {
+ TCHAR pszPath[MAX_PATH];
+ //if (SUCCEEDED(SHGetSpecialFolderPath(nullptr, pszPath, CSIDL_PERSONAL, FALSE))) {
+ if (SUCCEEDED(SHGetSpecialFolderPath(nullptr, 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
+
+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";
+#elif defined(_WIN32)
+ string home = getMyDocumentsPath1();
+ string filename1, filename2;
+ if (&home!=nullptr) {
+ 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";
+#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<top; i++) {
+ scorefile.read(tabel[i].name,30*sizeof(char));
+ scorefile.read(reinterpret_cast<char*>(&tabel[i].score), sizeof(int));
+ }
+ }
+ else {
+ for (int i = 0; i<top; i++) {
+ strcpy(tabel[i].name,"Poul Sander \0");
+ tabel[i].score = 2000 - i*100;
+ }
+ }
+ scorefile.close();
+ writeFile();
+}
+
+void Highscore::writeFile() {
+#if defined(__unix__)
+ 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!=nullptr) {
+ 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";
+#endif
+ 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<top; i++) {
+ outfile.write(tabel[i].name,30*sizeof(char));
+ outfile.write(reinterpret_cast<char*>(&tabel[i].score),sizeof(int));
+ }
+ outfile.close();
+}
+
+bool Highscore::isHighScore(int newScore) {
+ if (newScore>tabel[top-1].score) {
+ return true;
+ }
+ else {
+ return false;
+ }
+}
+
+void Highscore::addScore(const string& newName, int newScore) {
+ int ranking = top-1;
+ while ((tabel[ranking-1].score<newScore) && (ranking != 0)) {
+ ranking--;
+ }
+ for (int i=top-1; i>ranking; 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");
+ snprintf(tabel[ranking].name, sizeof(tabel[ranking].name), "%s", newName.c_str());
+ Highscore::writeFile();
+}
+
+int Highscore::getScoreNumber(int room) {
+ return tabel[room].score;
+}
+
+char* Highscore::getScoreName(int room) {
+ return &tabel[room].name[0];
+}
diff --git a/source/code/joypad.cpp b/source/code/joypad.cpp
index 8edf5c8..8c680a2 100644
--- a/source/code/joypad.cpp
+++ b/source/code/joypad.cpp
@@ -1,204 +1,188 @@
-/*
-===========================================================================
-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 "joypad.h"
-
-bool Joypad_init()
-{
- 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<NRofPADS; i++)
- {
- //cout << SDL_JoystickNumAxes(joystick) << endl;
- if (i*2>=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<NRofBUTTONS; i++)
- {
- if (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)) {
- joynum++;
- }
- if (joynum>=Joypad_number) {
- working = false;
- }
- else
- {
- joystick=SDL_JoystickOpen(joynum);
- if (joystick==nullptr) {
- working =false;
- }
- else {
- working=true;
- }
- }
-}
-
-Joypad::~Joypad()
-{
- if(working) {
- 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;
- }
-}
+/*
+===========================================================================
+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 "joypad.h"
+
+bool Joypad_init() {
+ 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<NRofPADS; i++) {
+ //cout << SDL_JoystickNumAxes(joystick) << endl;
+ if (i*2>=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<NRofBUTTONS; i++) {
+ if (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)) {
+ joynum++;
+ }
+ if (joynum>=Joypad_number) {
+ working = false;
+ }
+ else {
+ joystick=SDL_JoystickOpen(joynum);
+ if (joystick==nullptr) {
+ working =false;
+ }
+ else {
+ working=true;
+ }
+ }
+}
+
+Joypad::~Joypad() {
+ if (working) {
+ 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;
+ }
+}
diff --git a/source/code/listFiles.cpp b/source/code/listFiles.cpp
index b53c634..9bb19fd 100644
--- a/source/code/listFiles.cpp
+++ b/source/code/listFiles.cpp
@@ -30,8 +30,7 @@ listFiles.cpp
using namespace std;
-void ListFiles::setDirectory(const string &directory)
-{
+void ListFiles::setDirectory(const string& directory) {
for (int i=0; i<MAX_NR_OF_FILES; i++) {
filenames[i]="";
}
@@ -39,17 +38,14 @@ void ListFiles::setDirectory(const string &directory)
DWORD dwError;
string directory2 = directory+"/*";
hFind = FindFirstFile(directory2.c_str(), &FindFileData);
- if (hFind == INVALID_HANDLE_VALUE)
- {
+ if (hFind == INVALID_HANDLE_VALUE) {
cout << "Invalid file handle. Error is " << GetLastError() << endl;
}
- else
- {
+ else {
nrOfFiles=0;
filenames[nrOfFiles] = FindFileData.cFileName;
cout << "File: " << FindFileData.cFileName << endl;
- while ((FindNextFile(hFind, &FindFileData) != 0) && FindFileData.cFileName[0]!='.' && (nrOfFiles<MAX_NR_OF_FILES-1))
- {
+ while ((FindNextFile(hFind, &FindFileData) != 0) && FindFileData.cFileName[0]!='.' && (nrOfFiles<MAX_NR_OF_FILES-1)) {
nrOfFiles++;
filenames[nrOfFiles] = FindFileData.cFileName;
cout << "File: " << FindFileData.cFileName << endl;
@@ -57,25 +53,22 @@ void ListFiles::setDirectory(const string &directory)
dwError = GetLastError();
FindClose(hFind);
- if (dwError != ERROR_NO_MORE_FILES)
- {
+ if (dwError != ERROR_NO_MORE_FILES) {
cout << "FindNextFile error. Error is " << dwError << endl;
}
}
#elif defined(__unix__)
- DIR *DirectoryPointer;
- struct dirent *dp;
+ DIR* DirectoryPointer;
+ struct dirent* dp;
nrOfFiles=0;
//cout << "Will look in: " << directory << endl;
DirectoryPointer = opendir(directory.c_str());
- if(!DirectoryPointer) {
+ if (!DirectoryPointer) {
return;
}
- while ((dp=readdir(DirectoryPointer))&&(nrOfFiles<MAX_NR_OF_FILES-1))
- {
+ while ((dp=readdir(DirectoryPointer))&&(nrOfFiles<MAX_NR_OF_FILES-1)) {
string name = (string)(char*)dp->d_name;
- if (!isInList(name) && name[0]!='.' )
- {
+ if (!isInList(name) && name[0]!='.' ) {
nrOfFiles++;
filenames[nrOfFiles] = name;
}
@@ -88,33 +81,27 @@ void ListFiles::setDirectory(const string &directory)
//Put code here
}
-bool ListFiles::isInList(const string &name)
-{
- for (int i=0; (i<=nrOfFiles); i++)
- {
- if (0==strcmp(name.c_str(),filenames[i].c_str()))
- {
+bool ListFiles::isInList(const string& name) {
+ for (int i=0; (i<=nrOfFiles); i++) {
+ if (0==strcmp(name.c_str(),filenames[i].c_str())) {
return true;
}
}
return false;
}
-void ListFiles::setDirectory2(const string &dic)
-{
+void ListFiles::setDirectory2(const string& dic) {
#if defined(__unix__)
- DIR *DirectoryPointer;
- struct dirent *dp;
+ DIR* DirectoryPointer;
+ struct dirent* dp;
//cout << "Will look in: " << dic << endl;
DirectoryPointer = opendir(dic.c_str());
- if(!DirectoryPointer) {
+ if (!DirectoryPointer) {
return;
}
- while ((dp=readdir(DirectoryPointer))&&(nrOfFiles<MAX_NR_OF_FILES-1))
- {
+ while ((dp=readdir(DirectoryPointer))&&(nrOfFiles<MAX_NR_OF_FILES-1)) {
string name = (string)(char*)dp->d_name;
- if (!isInList(name) && name != "." && name != "..")
- {
+ if (!isInList(name) && name != "." && name != "..") {
nrOfFiles++;
filenames[nrOfFiles] = name;
}
@@ -125,22 +112,18 @@ void ListFiles::setDirectory2(const string &dic)
#endif
}
-string ListFiles::getFileName(int nr)
-{
+string ListFiles::getFileName(int nr) {
if (startFileNr+nr<MAX_NR_OF_FILES) {
return filenames[startFileNr+nr];
}
- else
- {
+ else {
return "";
}
}
-bool ListFiles::fileExists(int nr)
-{
+bool ListFiles::fileExists(int nr) {
string emptyString="";
- if (startFileNr+nr<MAX_NR_OF_FILES)
- {
+ if (startFileNr+nr<MAX_NR_OF_FILES) {
if (filenames[startFileNr+nr]==emptyString) {
return false;
}
@@ -153,8 +136,7 @@ bool ListFiles::fileExists(int nr)
}
}
-void ListFiles::back()
-{
+void ListFiles::back() {
if (startFileNr>FIRST_FILE) {
startFileNr = startFileNr-10;
}
@@ -163,17 +145,15 @@ void ListFiles::back()
}
}
-void ListFiles::forward()
-{
+void ListFiles::forward() {
if (startFileNr<nrOfFiles-FIRST_FILE) {
startFileNr = startFileNr+10;
}
}
-string ListFiles::getRandom()
-{
+string ListFiles::getRandom() {
int numberOfFiles = nrOfFiles-FIRST_FILE+1;
- if(numberOfFiles<1) {
+ if (numberOfFiles<1) {
return "";
}
int select = rand()%numberOfFiles;
diff --git a/source/code/main.cpp b/source/code/main.cpp
index 65f89a7..653168e 100644
--- a/source/code/main.cpp
+++ b/source/code/main.cpp
@@ -103,10 +103,8 @@ using namespace std;
static void MakeBackground(int,int);
-SDL_Surface * IMG_Load2(const char* path)
-{
- if (!PHYSFS_exists(path))
- {
+SDL_Surface* IMG_Load2(const char* path) {
+ if (!PHYSFS_exists(path)) {
cerr << "Error: File not in blockattack.data: " << path << endl;
return nullptr; //file doesn't exist
}
@@ -117,12 +115,11 @@ SDL_Surface * IMG_Load2(const char* path)
unsigned int m_size = PHYSFS_fileLength(myfile);
// Get the file data.
- char *m_data = new char[m_size];
+ char* m_data = new char[m_size];
int length_read = PHYSFS_read (myfile, m_data, 1, m_size);
- if (length_read != (int)m_size)
- {
+ if (length_read != (int)m_size) {
delete [] m_data;
m_data = 0;
PHYSFS_close(myfile);
@@ -133,11 +130,10 @@ SDL_Surface * IMG_Load2(const char* path)
PHYSFS_close(myfile);
// And this is how you load an image 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)
- {
+ if (!rw) {
delete [] m_data;
m_data = 0;
PHYSFS_close(myfile);
@@ -150,10 +146,8 @@ SDL_Surface * IMG_Load2(const char* path)
return surface;
}
-shared_ptr<CppSdl::CppSdlImageHolder> IMG_Load3(string path)
-{
- if (!PHYSFS_exists(path.c_str()))
- {
+shared_ptr<CppSdl::CppSdlImageHolder> IMG_Load3(string path) {
+ if (!PHYSFS_exists(path.c_str())) {
cerr << "Error: File not in blockattack.data: " << path << endl;
throw exception();
}
@@ -164,12 +158,11 @@ shared_ptr<CppSdl::CppSdlImageHolder> IMG_Load3(string path)
unsigned int m_size = PHYSFS_fileLength(myfile);
// Get the file data.
- char *m_data = new char[m_size];
+ char* m_data = new char[m_size];
int length_read = PHYSFS_read (myfile, m_data, 1, m_size);
- if (length_read != (int)m_size)
- {
+ if (length_read != (int)m_size) {
delete [] m_data;
m_data = 0;
PHYSFS_close(myfile);
@@ -190,10 +183,8 @@ static int InitImages();
static string oldThemePath = "default";
static bool loaded = false;
-void loadTheme(const string &themeName)
-{
- if(loaded)
- {
+void loadTheme(const string& themeName) {
+ if (loaded) {
UnloadImages();
}
#if defined(__unix__)
@@ -215,7 +206,7 @@ void loadTheme(const string &themeName)
//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)) {
+ if (themeName.compare("default")==0 || (themeName.compare("start")==0)) {
InitImages();
loaded =true;
return; //Nothing more to do
@@ -230,16 +221,13 @@ void loadTheme(const string &themeName)
}
-long NFont_OpenFont(NFont *target, const char* path,int ptsize, SDL_Color color, int style=TTF_STYLE_NORMAL)
-{
- if (!PHYSFS_exists(path))
- {
+long NFont_OpenFont(NFont* target, const char* path,int ptsize, SDL_Color color, int style=TTF_STYLE_NORMAL) {
+ if (!PHYSFS_exists(path)) {
cerr << "Error: File not in blockattack.data: " << path << endl;
return -1; //file doesn't exist
}
- if(!(TTF_WasInit()))
- {
+ if (!(TTF_WasInit())) {
TTF_Init();
}
@@ -249,11 +237,10 @@ long NFont_OpenFont(NFont *target, const char* path,int ptsize, SDL_Color color,
unsigned int m_size = PHYSFS_fileLength(myfile);
// Get the file data.
- char *m_data = new char[m_size];
+ char* m_data = new char[m_size];
int length_read = PHYSFS_read (myfile, m_data, 1, m_size);
- if (length_read != (int)m_size)
- {
+ if (length_read != (int)m_size) {
delete [] m_data;
m_data = 0;
PHYSFS_close(myfile);
@@ -264,11 +251,10 @@ long NFont_OpenFont(NFont *target, const char* path,int ptsize, SDL_Color color,
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)
- {
+ if (!rw) {
delete [] m_data;
m_data = 0;
PHYSFS_close(myfile);
@@ -276,7 +262,7 @@ long NFont_OpenFont(NFont *target, const char* path,int ptsize, SDL_Color color,
return -2;
}
- TTF_Font *font;
+ TTF_Font* font;
font=TTF_OpenFontRW(rw, 1, ptsize);
TTF_SetFontStyle(font,style);
@@ -288,10 +274,8 @@ long NFont_OpenFont(NFont *target, const char* path,int ptsize, SDL_Color color,
}
-Mix_Music * Mix_LoadMUS2(string path)
-{
- if (!PHYSFS_exists(path.c_str()))
- {
+Mix_Music* Mix_LoadMUS2(string path) {
+ if (!PHYSFS_exists(path.c_str())) {
cerr << "Warning: File not in blockattack.data: " << path << endl;
return nullptr; //file doesn't exist
}
@@ -302,12 +286,11 @@ Mix_Music * Mix_LoadMUS2(string path)
unsigned int m_size = PHYSFS_fileLength(myfile);
// Get the file data.
- char *m_data = new char[m_size];
+ char* m_data = new char[m_size];
int length_read = PHYSFS_read (myfile, m_data, 1, m_size);
- if (length_read != (int)m_size)
- {
+ if (length_read != (int)m_size) {
delete [] m_data;
m_data = 0;
PHYSFS_close(myfile);
@@ -318,11 +301,10 @@ Mix_Music * Mix_LoadMUS2(string path)
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)
- {
+ if (!rw) {
delete [] m_data;
m_data = 0;
PHYSFS_close(myfile);
@@ -336,10 +318,8 @@ Mix_Music * Mix_LoadMUS2(string path)
}
-Mix_Chunk * Mix_LoadWAV2(const char* path)
-{
- if (!PHYSFS_exists(path))
- {
+Mix_Chunk* Mix_LoadWAV2(const char* path) {
+ if (!PHYSFS_exists(path)) {
cerr << "Warning: File not in blockattack.data: " << path << endl;
return nullptr; //file doesn't exist
}
@@ -350,12 +330,11 @@ Mix_Chunk * Mix_LoadWAV2(const char* path)
unsigned int m_size = PHYSFS_fileLength(myfile);
// Get the file data.
- char *m_data = new char[m_size];
+ char* m_data = new char[m_size];
int length_read = PHYSFS_read (myfile, m_data, 1, m_size);
- if (length_read != (int)m_size)
- {
+ if (length_read != (int)m_size) {
delete [] m_data;
m_data = 0;
PHYSFS_close(myfile);
@@ -366,11 +345,10 @@ Mix_Chunk * Mix_LoadWAV2(const char* path)
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)
- {
+ if (!rw) {
delete [] m_data;
m_data = 0;
PHYSFS_close(myfile);
@@ -384,8 +362,7 @@ Mix_Chunk * Mix_LoadWAV2(const char* path)
}
//Load all image files to memory
-static int InitImages()
-{
+static int InitImages() {
if (!((backgroundImage = IMG_Load2("gfx/background.png"))
&& (background = IMG_Load2("gfx/blackBackGround.png"))
&& (bOptions = IMG_Load2("gfx/bOptions.png"))
@@ -491,15 +468,13 @@ static int InitImages()
cerr << "Error: Failed to load image file: " << SDL_GetError() << endl;
exit(1);
}
- try
- {
+ 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)
- {
+ catch (exception& e) {
cerr << e.what() << endl;
exit(1);
}
@@ -533,12 +508,10 @@ static int InitImages()
CONVERT(iLevelCheckBox);
CONVERT(iLevelCheckBoxMarked);
CONVERTA(iCheckBoxArea);
- for (int i = 0; i<4; i++)
- {
+ for (int i = 0; i<4; i++) {
CONVERTA(explosion[i]);
}
- for (int i = 0; i<7; i++)
- {
+ for (int i = 0; i<7; i++) {
CONVERTA(bricks[i]);
CONVERTA(balls[i]);
}
@@ -624,8 +597,7 @@ static int InitImages()
//Loads the sound if sound present
- if (!NoSound)
- {
+ if (!NoSound) {
//And here the music:
bgMusic = Mix_LoadMUS2("music/bgMusic.ogg");
highbeatMusic = Mix_LoadMUS2("music/highbeat.ogg");
@@ -643,14 +615,11 @@ static int InitImages()
//Unload images and fonts and sounds
-void UnloadImages()
-{
- if(verboseLevel)
- {
+void UnloadImages() {
+ if (verboseLevel) {
cout << "Unloading data..." << endl;
}
- if (!NoSound) //Only unload then it has been loaded!
- {
+ if (!NoSound) { //Only unload then it has been loaded!
Mix_HaltMusic();
Mix_FreeMusic(bgMusic);
Mix_FreeMusic(highbeatMusic);
@@ -742,12 +711,10 @@ void UnloadImages()
static stringstream converter;
//Function to convert numbers to string (2 diget)
-static string itoa2(int num)
-{
+static string itoa2(int num) {
converter.str(std::string());
converter.clear();
- if(num<10)
- {
+ if (num<10) {
converter << "0";
}
converter << num;
@@ -755,8 +722,7 @@ static string itoa2(int num)
}
/*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)
-{
+void DrawIMG(SDL_Surface* img, SDL_Surface* target, int x, int y) {
SDL_Rect dest;
dest.x = x;
dest.y = y;
@@ -764,8 +730,7 @@ void DrawIMG(SDL_Surface *img, SDL_Surface *target, int x, int y)
}
/*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)
-{
+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;
@@ -778,15 +743,13 @@ void DrawIMG(SDL_Surface *img, SDL_Surface * target, int x, int y, int w, int h,
}
-void NFont_Write(SDL_Surface *target,int x,int y,string text)
-{
+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);
@@ -803,8 +766,7 @@ void ResetFullscreen()
//The small things that are faaling when you clear something
-class aBall
-{
+class aBall {
private:
double x;
double y;
@@ -814,71 +776,60 @@ private:
unsigned long int lastTime;
public:
- aBall()
- {}
+ aBall() {
+ }
//constructor:
- aBall(int X, int Y, bool right, int coulor)
- {
+ aBall(int X, int Y, bool right, int coulor) {
double tal = 1.0+((double)rand()/((double)RAND_MAX));
velocityY = -tal*startVelocityY;
lastTime = currentTime;
x = (double)X;
y = (double)Y;
color = coulor;
- if (right)
- {
+ if (right) {
velocityX = tal*VelocityX;
}
- else
- {
+ else {
velocityX = -tal*VelocityX;
}
} //constructor
//Deconstructor
- ~aBall()
- {
+ ~aBall() {
} //Deconstructor
- void update()
- {
+ 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)
- {
+ if (y<1.0) {
velocityY=10.0;
}
- if ((velocityY>minVelocity) && (y>(double)(768-ballSize)) && (y<768.0))
- {
+ if ((velocityY>minVelocity) && (y>(double)(768-ballSize)) && (y<768.0)) {
velocityY = -0.70*velocityY;
y = 768.0-ballSize;
}
lastTime = currentTime;
}
- int getX()
- {
+ int getX() {
return (int)x;
}
- int getY()
- {
+ int getY() {
return (int)y;
}
- int getColor()
- {
+ int getColor() {
return color;
}
}; //aBall
static const int maxNumberOfBalls = 6*12*2*2;
-class ballManeger
-{
+class ballManeger {
public:
aBall ballArray[maxNumberOfBalls];
bool ballUsed[maxNumberOfBalls];
@@ -886,27 +837,22 @@ public:
aBall oldBallArray[maxNumberOfBalls];
bool oldBallUsed[maxNumberOfBalls];
- ballManeger()
- {
- for (int i=0; i<maxNumberOfBalls; i++)
- {
+ ballManeger() {
+ for (int i=0; i<maxNumberOfBalls; i++) {
ballUsed[i] = false;
oldBallUsed[i] = false;
}
}
//Adds a ball to the screen at given coordiantes, traveling right or not with color
- int addBall(int x, int y,bool right,int color)
- {
+ int addBall(int x, int y,bool right,int color) {
int ballNumber = 0;
//Find a free ball
- while ((ballUsed[ballNumber])&&(ballNumber<maxNumberOfBalls))
- {
+ while ((ballUsed[ballNumber])&&(ballNumber<maxNumberOfBalls)) {
ballNumber++;
}
//Could not find a free ball, return -1
- if (ballNumber==maxNumberOfBalls)
- {
+ if (ballNumber==maxNumberOfBalls) {
return -1;
}
currentTime = SDL_GetTicks();
@@ -915,24 +861,19 @@ public:
return 1;
} //addBall
- void update()
- {
+ void update() {
currentTime = SDL_GetTicks();
- for (int i = 0; i<maxNumberOfBalls; i++)
- {
+ for (int i = 0; i<maxNumberOfBalls; i++) {
- if (ballUsed[i])
- {
+ if (ballUsed[i]) {
oldBallUsed[i] = true;
oldBallArray[i] = ballArray[i];
ballArray[i].update();
- if (ballArray[i].getY()>800 || ballArray[i].getX()>xsize || ballArray[i].getX()<-ballSize)
- {
+ if (ballArray[i].getY()>800 || ballArray[i].getX()>xsize || ballArray[i].getX()<-ballSize) {
ballUsed[i] = false;
}
}
- else
- {
+ else {
oldBallUsed[i] = false;
}
}
@@ -944,8 +885,7 @@ public:
static ballManeger theBallManeger;
//a explosions, non moving
-class anExplosion
-{
+class anExplosion {
private:
int x;
int y;
@@ -957,12 +897,11 @@ private:
unsigned long int placeTime; //Then the explosion occored
public:
- anExplosion()
- {}
+ anExplosion() {
+ }
//constructor:
- anExplosion(int X, int Y)
- {
+ anExplosion(int X, int Y) {
placeTime = currentTime;
x = X;
y = Y;
@@ -970,35 +909,29 @@ public:
} //constructor
//Deconstructor
- ~anExplosion()
- {
+ ~anExplosion() {
} //Deconstructor
//true if animation has played and object should be removed from the screen
- bool removeMe()
- {
+ bool removeMe() {
frameNumber = (currentTime-placeTime)/frameLength;
return (!(frameNumber<maxFrame));
}
- int getX()
- {
+ int getX() {
return (int)x;
}
- int getY()
- {
+ int getY() {
return (int)y;
}
- int getFrame()
- {
+ int getFrame() {
return frameNumber;
}
}; //nExplosion
-class explosionManeger
-{
+class explosionManeger {
public:
anExplosion explosionArray[maxNumberOfBalls];
bool explosionUsed[maxNumberOfBalls];
@@ -1006,24 +939,19 @@ public:
anExplosion oldExplosionArray[maxNumberOfBalls];
bool oldExplosionUsed[maxNumberOfBalls];
- explosionManeger()
- {
- for (int i=0; i<maxNumberOfBalls; i++)
- {
+ explosionManeger() {
+ for (int i=0; i<maxNumberOfBalls; i++) {
explosionUsed[i] = false;
oldExplosionUsed[i] = false;
}
}
- int addExplosion(int x, int y)
- {
+ int addExplosion(int x, int y) {
int explosionNumber = 0;
- while ((explosionUsed[explosionNumber])&&(explosionNumber<maxNumberOfBalls))
- {
+ while ((explosionUsed[explosionNumber])&&(explosionNumber<maxNumberOfBalls)) {
explosionNumber++;
}
- if (explosionNumber==maxNumberOfBalls)
- {
+ if (explosionNumber==maxNumberOfBalls) {
return -1;
}
currentTime = SDL_GetTicks();
@@ -1032,24 +960,19 @@ public:
return 1;
} //addBall
- void update()
- {
+ void update() {
currentTime = SDL_GetTicks();
- for (int i = 0; i<maxNumberOfBalls; i++)
- {
+ for (int i = 0; i<maxNumberOfBalls; i++) {
- if (explosionUsed[i])
- {
+ if (explosionUsed[i]) {
oldExplosionUsed[i] = true;
oldExplosionArray[i] = explosionArray[i];
- if (explosionArray[i].removeMe())
- {
+ if (explosionArray[i].removeMe()) {
explosionArray[i].~anExplosion();
explosionUsed[i] = false;
}
}
- else
- {
+ else {
oldExplosionUsed[i] = false;
}
}
@@ -1061,8 +984,7 @@ public:
static explosionManeger theExplosionManeger;
//text pop-up
-class textMessage
-{
+class textMessage {
private:
int x;
int y;
@@ -1071,12 +993,11 @@ private:
unsigned long int placeTime; //Then the text was placed
public:
- textMessage()
- {}
+ textMessage() {
+ }
//constructor:
- textMessage(int X, int Y,const char* Text,unsigned int Time)
- {
+ textMessage(int X, int Y,const char* Text,unsigned int Time) {
placeTime = currentTime;
x = X;
y = Y;
@@ -1086,29 +1007,24 @@ public:
} //constructor
//true if the text has expired
- bool removeMe()
- {
+ bool removeMe() {
return currentTime-placeTime>time;
}
- int getX()
- {
+ int getX() {
return x;
}
- int getY()
- {
+ int getY() {
return y;
}
- const char* getText()
- {
+ const char* getText() {
return textt;
}
}; //text popup
-class textManeger
-{
+class textManeger {
public:
textMessage textArray[maxNumberOfBalls];
bool textUsed[maxNumberOfBalls];
@@ -1116,24 +1032,19 @@ public:
textMessage oldTextArray[maxNumberOfBalls];
bool oldTextUsed[maxNumberOfBalls];
- textManeger()
- {
- for (int i=0; i<maxNumberOfBalls; i++)
- {
+ textManeger() {
+ for (int i=0; i<maxNumberOfBalls; i++) {
textUsed[i] = false;
oldTextUsed[i] = false;
}
}
- int addText(int x, int y,string Text,unsigned int Time)
- {
+ int addText(int x, int y,string Text,unsigned int Time) {
int textNumber = 0;
- while ((textNumber<maxNumberOfBalls)&&((textUsed[textNumber])||(oldTextUsed[textNumber])))
- {
+ while ((textNumber<maxNumberOfBalls)&&((textUsed[textNumber])||(oldTextUsed[textNumber]))) {
textNumber++;
}
- if (textNumber==maxNumberOfBalls)
- {
+ if (textNumber==maxNumberOfBalls) {
return -1;
}
currentTime = SDL_GetTicks();
@@ -1142,27 +1053,21 @@ public:
return 1;
} //addText
- void update()
- {
+ void update() {
currentTime = SDL_GetTicks();
- for (int i = 0; i<maxNumberOfBalls; i++)
- {
+ for (int i = 0; i<maxNumberOfBalls; i++) {
- if (textUsed[i])
- {
- if (!oldTextUsed[i])
- {
+ if (textUsed[i]) {
+ if (!oldTextUsed[i]) {
oldTextUsed[i] = true;
oldTextArray[i] = textMessage(textArray[i]);
}
- if (textArray[i].removeMe())
- {
+ if (textArray[i].removeMe()) {
textArray[i].~textMessage();
textUsed[i] = false;
}
}
- else if (oldTextUsed[i])
- {
+ else if (oldTextUsed[i]) {
oldTextUsed[i] = false;
oldTextArray[i].~textMessage();
}
@@ -1178,13 +1083,11 @@ static textManeger theTextManeger;
#include "BlockGame.hpp"
#include "BlockGame.cpp"
-class BlockGameSdl : public BlockGame
-{
+class BlockGameSdl : public BlockGame {
public:
SDL_Surface* sBoard;
- BlockGameSdl(int tx, int ty)
- {
+ BlockGameSdl(int tx, int ty) {
tmp = IMG_Load2("gfx/BackBoard.png");
sBoard = SDL_DisplayFormat(tmp);
SDL_FreeSurface(tmp);
@@ -1192,8 +1095,7 @@ public:
topx = tx;
topy = ty;
}
- ~BlockGameSdl()
- {
+ ~BlockGameSdl() {
SDL_FreeSurface(sBoard);
}
@@ -1242,7 +1144,7 @@ public:
}
void TimeTrialEndEvent() const override {
- if(!NoSound && SoundEnabled) {
+ if (!NoSound && SoundEnabled) {
Mix_PlayChannel(1,counterFinalChunk,0);
}
}
@@ -1254,32 +1156,25 @@ public:
Mix_PlayChannel(1, applause, 0);
}
private:
- void convertSurface()
- {
+ void convertSurface() {
SDL_FreeSurface(sBoard);
sBoard = SDL_DisplayFormat(backBoard);
}
//Draws all the bricks to the board (including garbage)
- void PaintBricks() const
- {
+ void PaintBricks() const {
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))
- {
+ 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)
- {
+ 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)
- {
+ 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)
- {
+ if ((board[j][i]/1000000)%10==1) {
int left, right, over, under;
int number = board[j][i];
if (j<1) {
@@ -1306,67 +1201,51 @@ private:
else {
under = board[j][i-1];
}
- if ((left == number)&&(right == number)&&(over == number)&&(under == number))
- {
+ 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))
- {
+ 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))
- {
+ 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))
- {
+ 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))
- {
+ 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))
- {
+ 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))
- {
+ 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))
- {
+ 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))
- {
+ 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))
- {
+ 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))
- {
+ 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))
- {
+ 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)
- {
+ if ((board[j][i]/1000000)%10==2) {
+ if (j==0) {
DrawIMG(garbageGML, sBoard, j*bsize, bsize*12-i*bsize-pixels);
}
- else if (j==5)
- {
+ else if (j==5) {
DrawIMG(garbageGMR, sBoard, j*bsize, bsize*12-i*bsize-pixels);
}
- else
- {
+ else {
DrawIMG(garbageGM, sBoard, j*bsize, bsize*12-i*bsize-pixels);
}
}
@@ -1374,10 +1253,8 @@ private:
const int j = 0;
int garbageSize=0;
- for (int i=0; i<20; i++)
- {
- if ((board[j][i]/1000000)%10==1)
- {
+ 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) {
@@ -1404,32 +1281,27 @@ private:
else {
under = board[j][i-1];
}
- if (((left != number)&&(right == number)&&(over != number)&&(under == number))&&(garbageSize>0))
- {
+ 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
- {
+ if (!((left != number)&&(right == number)&&(over == number)&&(under == number))) { //not in garbage
garbageSize=0;
}
- else
- {
+ else {
garbageSize++;
}
}
}
for (int i=0; i<6; i++)
- if (board[i][0]!=-1)
- {
+ if (board[i][0]!=-1) {
DrawIMG(transCover, sBoard, i*bsize, 12*bsize-pixels); //Make the appering blocks transperant
}
}
public:
//Draws everything
- void DoPaintJob()
- {
+ void DoPaintJob() {
DrawIMG(backBoard, sBoard, 0, 0);
nf_standard_blue_font.setDest(sBoard); //reset to screen at the end of this funciton!
@@ -1437,57 +1309,45 @@ public:
if (stageClear) {
DrawIMG(blackLine, sBoard, 0, bsize*(12+2)+bsize*(stageClearLimit-linesCleared)-pixels-1);
}
- if (puzzleMode&&(!bGameOver))
- {
+ 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)
- {
+ if (puzzleMode && stageButtonStatus == SBpuzzleMode) {
DrawIMG(bRetry,sBoard, cordRetryButton.x, cordRetryButton.y);
- if (Level<PuzzleGetNumberOfPuzzles()-1)
- {
- if(hasWonTheGame)
- {
+ if (Level<PuzzleGetNumberOfPuzzles()-1) {
+ if (hasWonTheGame) {
DrawIMG(bNext,sBoard,cordNextButton.x, cordNextButton.y);
}
- else
- {
+ else {
DrawIMG(bSkip,sBoard,cordNextButton.x, cordNextButton.y);
}
}
- else
- {
+ else {
strHolder = "Last puzzle";
nf_standard_blue_font.draw(5,5,strHolder.c_str());
}
}
- if(stageClear && stageButtonStatus == SBstageClear)
- {
+ if (stageClear && stageButtonStatus == SBstageClear) {
DrawIMG(bRetry,sBoard, cordRetryButton.x, cordRetryButton.y);
- if(Level<50-1)
- {
- if(hasWonTheGame)
- {
+ if (Level<50-1) {
+ if (hasWonTheGame) {
DrawIMG(bNext,sBoard,cordNextButton.x, cordNextButton.y);
}
- else
- {
+ else {
DrawIMG(bSkip,sBoard,cordNextButton.x, cordNextButton.y);
}
}
- else
- {
+ else {
strHolder = "Last stage";
nf_standard_blue_font.draw(5,5,strHolder.c_str());
}
}
#if DEBUG
- if (AI_Enabled&&(!bGameOver))
- {
+ if (AI_Enabled&&(!bGameOver)) {
strHolder = "AI_status: " + itoa(AIstatus)+ ", "+ itoa(AIlineToClear);
//NFont_Write(sBoard, 5, 5, strHolder.c_str());
nf_standard_blue_font.draw(5,5,strHolder.c_str());
@@ -1496,16 +1356,13 @@ public:
if (!bGameOver) {
DrawIMG(cursor[(ticks/600)%2],sBoard,cursorx*bsize-4,11*bsize-cursory*bsize-pixels-4);
}
- if (ticks<gameStartedAt)
- {
+ if (ticks<gameStartedAt) {
int currentCounter = abs((int)ticks-(int)gameStartedAt)/1000;
- if( (currentCounter!=lastCounter) && (SoundEnabled)&&(!NoSound))
- {
+ if ( (currentCounter!=lastCounter) && (SoundEnabled)&&(!NoSound)) {
Mix_PlayChannel(1,counterChunk,0);
}
lastCounter = currentCounter;
- switch (currentCounter)
- {
+ switch (currentCounter) {
case 2:
DrawIMG(counter[2], sBoard, 2*bsize, 5*bsize);
break;
@@ -1519,44 +1376,33 @@ public:
break;
}
}
- else
- {
- if(SoundEnabled&&(!NoSound)&&(timetrial)&&(ticks>gameStartedAt+10000)&&(!bGameOver))
- {
+ else {
+ if (SoundEnabled&&(!NoSound)&&(timetrial)&&(ticks>gameStartedAt+10000)&&(!bGameOver)) {
int currentCounter = (ticks-(int)gameStartedAt)/1000;
- if(currentCounter!=lastCounter)
- {
- if(currentCounter>115 && currentCounter<120)
- {
+ if (currentCounter!=lastCounter) {
+ if (currentCounter>115 && currentCounter<120) {
Mix_PlayChannel(1,counterChunk,0);
}
}
lastCounter = currentCounter;
}
- else
- {
- if( (0==lastCounter) && (SoundEnabled)&&(!NoSound))
- {
+ else {
+ if ( (0==lastCounter) && (SoundEnabled)&&(!NoSound)) {
Mix_PlayChannel(1,counterFinalChunk,0);
}
lastCounter = -1;
}
}
- if ((bGameOver)&&(!editorMode))
- {
- if (hasWonTheGame)
- {
+ if ((bGameOver)&&(!editorMode)) {
+ if (hasWonTheGame) {
DrawIMG(iWinner, sBoard, 0, 5*bsize);
}
- else
- {
- if (bDraw)
- {
+ else {
+ if (bDraw) {
DrawIMG(iDraw, sBoard, 0, 5*bsize);
}
- else
- {
+ else {
DrawIMG(iGameOver, sBoard, 0, 5*bsize);
}
}
@@ -1565,8 +1411,7 @@ public:
}
- void Update(int newtick)
- {
+ void Update(int newtick) {
BlockGame::Update(newtick);
DoPaintJob();
}
@@ -1579,10 +1424,8 @@ private:
//writeScreenShot saves the screen as a bmp file, it uses the time to get a unique filename
-void writeScreenShot()
-{
- if(verboseLevel)
- {
+void writeScreenShot() {
+ if (verboseLevel) {
cout << "Saving screenshot" << endl;
}
int rightNow = (int)time(nullptr);
@@ -1611,19 +1454,17 @@ void writeScreenShot()
}
//Function to return the name of a key, to be displayed...
-static string getKeyName(SDLKey key)
-{
+static string getKeyName(SDLKey key) {
string keyname(SDL_GetKeyName(key));
return keyname;
}
-void MakeBackground(int xsize,int ysize,BlockGame &theGame, BlockGame &theGame2);
+void MakeBackground(int xsize,int ysize,BlockGame& theGame, BlockGame& theGame2);
//Dialogbox
-bool OpenDialogbox(int x, int y, char *name)
-{
+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)
@@ -1634,49 +1475,40 @@ bool OpenDialogbox(int x, int y, char *name)
string strHolder;
MakeBackground(xsize,ysize);
DrawIMG(background,screen,0,0);
- while (!done && !Config::getInstance()->isShuttingDown())
- {
+ 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)
- {
+ 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 )
- {
+ 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) )
- {
+ 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) )
- {
+ else if ( (event.key.keysym.sym == SDLK_ESCAPE) ) {
done = true;
accept = false;
}
- else if (!(event.key.keysym.sym == SDLK_BACKSPACE))
- {
+ 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))
- {
+ else if ((event.key.keysym.sym == SDLK_BACKSPACE)&&(!repeating)) {
if ((rk.ReadKey(event.key.keysym.sym))&&(SoundEnabled)&&(!NoSound)) {
Mix_PlayChannel(1,typingChunk,0);
}
@@ -1687,18 +1519,15 @@ bool OpenDialogbox(int x, int y, char *name)
} //while(event)
- if (SDL_GetTicks()>(time+repeatDelay))
- {
+ if (SDL_GetTicks()>(time+repeatDelay)) {
time = SDL_GetTicks();
keys = SDL_GetKeyState(nullptr);
- if ( (keys[SDLK_BACKSPACE])&&(repeating) )
- {
+ if ( (keys[SDLK_BACKSPACE])&&(repeating) ) {
if ((rk.ReadKey(SDLK_BACKSPACE))&&(SoundEnabled)&&(!NoSound)) {
Mix_PlayChannel(1,typingChunk,0);
}
}
- else
- {
+ else {
repeating = false;
}
}
@@ -1712,8 +1541,7 @@ bool OpenDialogbox(int x, int y, char *name)
}
//Draws the highscores
-void DrawHighscores(int x, int y, bool endless)
-{
+void DrawHighscores(int x, int y, bool endless) {
MakeBackground(xsize,ysize);
DrawIMG(background,screen,0,0);
if (endless) {
@@ -1722,24 +1550,19 @@ void DrawHighscores(int x, int y, bool endless)
else {
nf_standard_blue_font.draw(x+100,y+100,_("Time Trial:") );
}
- for (int i =0; i<10; i++)
- {
+ for (int i =0; i<10; i++) {
char playerScore[32];
char playerName[32];
- if (endless)
- {
+ if (endless) {
sprintf(playerScore, "%i", theTopScoresEndless.getScoreNumber(i));
}
- else
- {
+ else {
sprintf(playerScore, "%i", theTopScoresTimeTrial.getScoreNumber(i));
}
- if (endless)
- {
+ if (endless) {
strcpy(playerName,theTopScoresEndless.getScoreName(i));
}
- else
- {
+ else {
strcpy(playerName,theTopScoresTimeTrial.getScoreName(i));
}
nf_standard_blue_font.draw(x+420,y+150+i*35,playerScore);
@@ -1747,8 +1570,7 @@ void DrawHighscores(int x, int y, bool endless)
}
}
-void DrawStats()
-{
+void DrawStats() {
MakeBackground(xsize,ysize);
DrawIMG(background,screen,0,0);
int y = 5;
@@ -1756,8 +1578,7 @@ void DrawStats()
NFont_Write(screen, 10,y,_("Stats") );
y+=y_spacing*2;
NFont_Write(screen, 10,y,_("Chains") );
- for(int i=2; i<13; i++)
- {
+ 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)));
@@ -1801,8 +1622,7 @@ void DrawStats()
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++)
- {
+ for (int i=0; i<7; i++) {
y += y_spacing;
NFont_Write(screen, x_offset,y,string("AI "+itoa(i+1)).c_str());
numberAsString = itoa(Stats::getInstance()->getNumberOf("defeatedAI"+itoa(i)));
@@ -1812,8 +1632,7 @@ void DrawStats()
}
}
-void OpenScoresDisplay()
-{
+void OpenScoresDisplay() {
int mousex,mousey;
bool done = false; //We are done!
int page = 0;
@@ -1825,10 +1644,8 @@ void OpenScoresDisplay()
const int backY = ysize-buttonYsize-20;
const int nextX = xsize-buttonXsize-20;
const int nextY = backY;
- while (!done && !Config::getInstance()->isShuttingDown())
- {
- switch(page)
- {
+ while (!done && !Config::getInstance()->isShuttingDown()) {
+ switch (page) {
case 0:
//Highscores, endless
DrawHighscores(100,100,true);
@@ -1856,50 +1673,39 @@ void OpenScoresDisplay()
SDL_GetMouseState(&mousex,&mousey);
- while ( SDL_PollEvent(&event) )
- {
+ while ( SDL_PollEvent(&event) ) {
- if ( event.type == SDL_QUIT )
- {
+ if ( event.type == SDL_QUIT ) {
Config::getInstance()->setShuttingDown(5);
done = true;
}
- if ( event.type == SDL_KEYDOWN )
- {
- if( (event.key.keysym.sym == SDLK_RIGHT))
- {
+ if ( event.type == SDL_KEYDOWN ) {
+ if ( (event.key.keysym.sym == SDLK_RIGHT)) {
page++;
- if(page>=numberOfPages)
- {
+ if (page>=numberOfPages) {
page = 0;
}
}
- else if( (event.key.keysym.sym == SDLK_LEFT))
- {
+ else if ( (event.key.keysym.sym == SDLK_LEFT)) {
page--;
- if(page<0)
- {
+ if (page<0) {
page = numberOfPages-1;
}
}
- else
- {
+ else {
done = true;
}
- if ( event.key.keysym.sym == SDLK_F9 )
- {
+ if ( event.key.keysym.sym == SDLK_F9 ) {
writeScreenShot();
}
- if ( (event.key.keysym.sym == SDLK_RETURN)||(event.key.keysym.sym == SDLK_KP_ENTER) )
- {
+ if ( (event.key.keysym.sym == SDLK_RETURN)||(event.key.keysym.sym == SDLK_KP_ENTER) ) {
done = true;
}
- else if ( (event.key.keysym.sym == SDLK_ESCAPE) )
- {
+ else if ( (event.key.keysym.sym == SDLK_ESCAPE) ) {
done = true;
}
}
@@ -1907,37 +1713,30 @@ void OpenScoresDisplay()
} //while(event)
// If the mouse button is released, make bMouseUp equal true
- if (!SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(1))
- {
+ if (!SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(1)) {
bMouseUp=true;
}
- if (SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(1) && bMouseUp)
- {
+ if (SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(1) && bMouseUp) {
bMouseUp = false;
//The Score button:
- if((mousex>scoreX) && (mousex<scoreX+buttonXsize) && (mousey>scoreY) && (mousey<scoreY+buttonYsize))
- {
+ if ((mousex>scoreX) && (mousex<scoreX+buttonXsize) && (mousey>scoreY) && (mousey<scoreY+buttonYsize)) {
done =true;
}
//The back button:
- if((mousex>backX) && (mousex<backX+buttonXsize) && (mousey>backY) && (mousey<backY+buttonYsize))
- {
+ if ((mousex>backX) && (mousex<backX+buttonXsize) && (mousey>backY) && (mousey<backY+buttonYsize)) {
page--;
- if(page<0)
- {
+ if (page<0) {
page = numberOfPages-1;
}
}
//The next button:
- if((mousex>nextX) && (mousex<nextX+buttonXsize) && (mousey>nextY) && (mousey<nextY+buttonYsize))
- {
+ if ((mousex>nextX) && (mousex<nextX+buttonXsize) && (mousey>nextY) && (mousey<nextY+buttonYsize)) {
page++;
- if(page>=numberOfPages)
- {
+ if (page>=numberOfPages) {
page = 0;
}
}
@@ -1953,14 +1752,12 @@ void OpenScoresDisplay()
//Open a puzzle file
-bool OpenFileDialogbox(int x, int y, char *name)
-{
+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";
- if(verboseLevel)
- {
+ if (verboseLevel) {
cout << "Looking in " << folder << endl;
}
lf.setDirectory(folder.c_str());
@@ -1972,40 +1769,32 @@ bool OpenFileDialogbox(int x, int y, char *name)
DrawIMG(background,screen,0,0);
DrawIMG(bForward,background,x+460,y+420);
DrawIMG(bBack,background,x+20,y+420);
- while (!done && !Config::getInstance()->isShuttingDown())
- {
+ while (!done && !Config::getInstance()->isShuttingDown()) {
DrawIMG(background,screen,0,0);
const int nrOfFiles = 10;
DrawIMG(changeButtonsBack,screen,x,y);
- for (int i=0; i<nrOfFiles; i++)
- {
+ for (int i=0; i<nrOfFiles; i++) {
NFont_Write(screen, x+10,y+10+36*i,lf.getFileName(i).c_str());
}
SDL_Event event;
- while ( SDL_PollEvent(&event) )
- {
- if ( event.type == SDL_QUIT )
- {
+ 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_ESCAPE) )
- {
+ if ( event.type == SDL_KEYDOWN ) {
+ if ( (event.key.keysym.sym == SDLK_ESCAPE) ) {
done = true;
}
- if ( (event.key.keysym.sym == SDLK_RIGHT) )
- {
+ if ( (event.key.keysym.sym == SDLK_RIGHT) ) {
lf.forward();
}
- if ( (event.key.keysym.sym == SDLK_LEFT) )
- {
+ if ( (event.key.keysym.sym == SDLK_LEFT) ) {
lf.back();
}
}
@@ -2015,33 +1804,26 @@ bool OpenFileDialogbox(int x, int y, char *name)
SDL_GetMouseState(&mousex,&mousey);
// If the mouse button is released, make bMouseUp equal true
- if (!SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(1))
- {
+ if (!SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(1)) {
bMouseUp=true;
}
- if (SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(1) && bMouseUp)
- {
+ if (SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(1) && bMouseUp) {
bMouseUp = false;
//The Forward Button:
- if ( (mousex>x+460) && (mousex<x+460+buttonXsize) && (mousey>y+420) && (mousey<y+420+40) )
- {
+ if ( (mousex>x+460) && (mousex<x+460+buttonXsize) && (mousey>y+420) && (mousey<y+420+40) ) {
lf.forward();
}
//The back button:
- if ( (mousex>x+20) && (mousex<x+20+buttonXsize) && (mousey>y+420) && (mousey<y+420+40) )
- {
+ if ( (mousex>x+20) && (mousex<x+20+buttonXsize) && (mousey>y+420) && (mousey<y+420+40) ) {
lf.back();
}
- for (int i=0; i<10; i++)
- {
- if ( (mousex>x+10) && (mousex<x+480) && (mousey>y+10+i*36) && (mousey<y+10+i*36+32) )
- {
- if (lf.fileExists(i))
- {
+ for (int i=0; i<10; i++) {
+ if ( (mousex>x+10) && (mousex<x+480) && (mousey>y+10+i*36) && (mousey<y+10+i*36+32) ) {
+ if (lf.fileExists(i)) {
strncpy(name,lf.getFileName(i).c_str(),28); //Problems occurs then larger than 28 (maybe 29)
done=true; //The user have, clicked the purpose of this function is now complete
}
@@ -2058,20 +1840,15 @@ bool OpenFileDialogbox(int x, int y, char *name)
//Draws the balls and explosions
-static void DrawBalls()
-{
- for (int i = 0; i< maxNumberOfBalls; i++)
- {
- if (theBallManeger.ballUsed[i])
- {
+static void DrawBalls() {
+ for (int i = 0; i< maxNumberOfBalls; i++) {
+ if (theBallManeger.ballUsed[i]) {
DrawIMG(balls[theBallManeger.ballArray[i].getColor()],screen,theBallManeger.ballArray[i].getX(),theBallManeger.ballArray[i].getY());
} //if used
- if (theExplosionManeger.explosionUsed[i])
- {
+ if (theExplosionManeger.explosionUsed[i]) {
DrawIMG(explosion[theExplosionManeger.explosionArray[i].getFrame()],screen,theExplosionManeger.explosionArray[i].getX(),theExplosionManeger.explosionArray[i].getY());
}
- if (theTextManeger.textUsed[i])
- {
+ if (theTextManeger.textUsed[i]) {
//cout << "Printing text: " << theTextManeger.textArray[i].getText() << endl;
int x = theTextManeger.textArray[i].getX()-12;
int y = theTextManeger.textArray[i].getY()-12;
@@ -2082,20 +1859,15 @@ static void DrawBalls()
} //DrawBalls
//Removes the old balls
-void UndrawBalls()
-{
- for (int i = 0; i< maxNumberOfBalls; i++)
- {
- if (theBallManeger.oldBallUsed[i])
- {
+void UndrawBalls() {
+ for (int i = 0; i< maxNumberOfBalls; i++) {
+ if (theBallManeger.oldBallUsed[i]) {
DrawIMG(background,screen,theBallManeger.oldBallArray[i].getX(),theBallManeger.oldBallArray[i].getY(),ballSize,ballSize,theBallManeger.oldBallArray[i].getX(),theBallManeger.oldBallArray[i].getY());
} //if used
- if (theExplosionManeger.oldExplosionUsed[i])
- {
+ if (theExplosionManeger.oldExplosionUsed[i]) {
DrawIMG(background,screen,theExplosionManeger.oldExplosionArray[i].getX(),theExplosionManeger.oldExplosionArray[i].getY(),70,120,theExplosionManeger.oldExplosionArray[i].getX(),theExplosionManeger.oldExplosionArray[i].getY());
}
- if (theTextManeger.oldTextUsed[i])
- {
+ if (theTextManeger.oldTextUsed[i]) {
int x = theTextManeger.oldTextArray[i].getX()-12;
int y = theTextManeger.oldTextArray[i].getY()-12;
DrawIMG(background,screen,x,y,25,25,x,y);
@@ -2104,12 +1876,10 @@ void UndrawBalls()
} //UndrawBalls
//draws everything
-void DrawEverything(int xsize, int ysize,BlockGameSdl *theGame, BlockGameSdl *theGame2)
-{
+void DrawEverything(int xsize, int ysize,BlockGameSdl* theGame, BlockGameSdl* theGame2) {
SDL_ShowCursor(SDL_DISABLE);
//draw background:
- if (forceredraw != 1)
- {
+ if (forceredraw != 1) {
UndrawBalls();
DrawIMG(background,screen,oldMousex,oldMousey,32,32,oldMousex,oldMousey);
@@ -2130,30 +1900,24 @@ void DrawEverything(int xsize, int ysize,BlockGameSdl *theGame, BlockGameSdl *th
string strHolder;
strHolder = itoa(theGame->GetScore()+theGame->GetHandicap());
NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+100,strHolder.c_str());
- if (theGame->GetAIenabled())
- {
+ if (theGame->GetAIenabled()) {
NFont_Write(screen, theGame->GetTopX()+10,theGame->GetTopY()-34,_("AI") );
}
- else if (editorMode)
- {
+ else if (editorMode) {
NFont_Write(screen, theGame->GetTopX()+10,theGame->GetTopY()-34,_("Playing field") );
}
- else if (!singlePuzzle)
- {
+ else if (!singlePuzzle) {
NFont_Write(screen, theGame->GetTopX()+10,theGame->GetTopY()-34,player1name);
}
- if (theGame->isTimeTrial())
- {
+ if (theGame->isTimeTrial()) {
int tid = (int)SDL_GetTicks()-theGame->GetGameStartedAt();
int minutes;
int seconds;
- if (tid>=0)
- {
+ 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
- {
+ else {
minutes = ((abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))/60/1000;
seconds = (((abs((int)SDL_GetTicks()-(int)theGame->GetGameStartedAt())))%(60*1000))/1000;
}
@@ -2163,8 +1927,7 @@ void DrawEverything(int xsize, int ysize,BlockGameSdl *theGame, BlockGameSdl *th
if (theGame->isGameOver()) {
seconds=0;
}
- if (seconds>9)
- {
+ if (seconds>9) {
strHolder = itoa(minutes)+":"+itoa(seconds);
}
else {
@@ -2173,8 +1936,7 @@ void DrawEverything(int xsize, int ysize,BlockGameSdl *theGame, BlockGameSdl *th
//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
- {
+ 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()) {
@@ -2183,12 +1945,10 @@ void DrawEverything(int xsize, int ysize,BlockGameSdl *theGame, BlockGameSdl *th
if (theGame->isGameOver()) {
seconds=(theGame->GetGameEndedAt()/1000)%60;
}
- if (seconds>9)
- {
+ if (seconds>9) {
strHolder = itoa(minutes)+":"+itoa(seconds);
}
- else
- {
+ else {
strHolder = itoa(minutes)+":0"+itoa(seconds);
}
NFont_Write(screen, theGame->GetTopX()+310,theGame->GetTopY()+150,strHolder.c_str());
@@ -2198,47 +1958,40 @@ void DrawEverything(int xsize, int ysize,BlockGameSdl *theGame, BlockGameSdl *th
//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()))
- {
+ 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 (!editorMode) {
/*
*If single player mode (and not VS)
*/
- if(!twoPlayers && !theGame->isGameOver())
- {
+ if (!twoPlayers && !theGame->isGameOver()) {
//Blank player2's board:
DrawIMG(backBoard,screen,theGame2->GetTopX(),theGame2->GetTopY());
//Write a description:
- if(theGame->isTimeTrial())
- {
+ if (theGame->isTimeTrial()) {
NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+10,"Time Trial");
NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160,"Objective:");
string infostring = _("Score as much as \npossible in 2 minutes");
NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32,infostring);
}
- else if(theGame->isStageClear())
- {
+ 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:");
string infostring = _("You must clear a \nnumber of lines.\nSpeed is rapidly \nincreased.");
NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32,infostring);
}
- else if(theGame->isPuzzleMode())
- {
+ else if (theGame->isPuzzleMode()) {
NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+10,"Puzzle");
NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160,"Objective:");
string infostring = _("Clear the entire board \nwith a limited number \nof moves.");
NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160+32,infostring);
}
- else
- {
+ else {
NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+10,"Endless");
NFont_Write(screen, theGame2->GetTopX()+7,theGame2->GetTopY()+160,"Objective:");
string infostring = _("Score as much as \npossible. No time limit.");
@@ -2251,41 +2004,33 @@ void DrawEverything(int xsize, int ysize,BlockGameSdl *theGame, BlockGameSdl *th
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())
- {
+ if (theGame->isPuzzleMode()) {
NFont_Write(screen, theGame2->GetTopX()+7,y+160,( _("Restart: ")+getKeyName(keySettings[0].push) ).c_str() );
}
- else
- {
+ else {
NFont_Write(screen, theGame2->GetTopX()+7,y+160,( _("Push line: ")+getKeyName(keySettings[0].push) ).c_str() );
}
}
- else
- {
+ 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())
- {
+ if (theGame2->GetAIenabled()) {
NFont_Write(screen, theGame2->GetTopX()+10,theGame2->GetTopY()-34,_("AI") );
}
- else
- {
+ else {
NFont_Write(screen, theGame2->GetTopX()+10,theGame2->GetTopY()-34,theGame2->name);
}
- if (theGame2->isTimeTrial())
- {
+ if (theGame2->isTimeTrial()) {
int tid = (int)SDL_GetTicks()-theGame2->GetGameStartedAt();
int minutes;
int seconds;
- if (tid>=0)
- {
+ 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
- {
+ else {
minutes = ((abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())))/60/1000;
seconds = (((abs((int)SDL_GetTicks()-(int)theGame2->GetGameStartedAt())))%(60*1000))/1000;
}
@@ -2295,19 +2040,16 @@ void DrawEverything(int xsize, int ysize,BlockGameSdl *theGame, BlockGameSdl *th
if (theGame2->isGameOver()) {
seconds=0;
}
- if (seconds>9)
- {
+ if (seconds>9) {
strHolder = itoa(minutes)+":"+itoa(seconds);
}
- else
- {
+ 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
- {
+ 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()) {
@@ -2316,12 +2058,10 @@ void DrawEverything(int xsize, int ysize,BlockGameSdl *theGame, BlockGameSdl *th
if (theGame2->isGameOver()) {
seconds=(theGame2->GetGameEndedAt()/1000)%60;
}
- if (seconds>9)
- {
+ if (seconds>9) {
strHolder = itoa(minutes)+":"+itoa(seconds);
}
- else
- {
+ else {
strHolder = itoa(minutes)+":0"+itoa(seconds);
}
NFont_Write(screen, theGame2->GetTopX()+310,theGame2->GetTopY()+150,strHolder.c_str());
@@ -2338,8 +2078,7 @@ void DrawEverything(int xsize, int ysize,BlockGameSdl *theGame, BlockGameSdl *th
#if DEBUG
Frames++;
- if (SDL_GetTicks() >= Ticks + 1000)
- {
+ if (SDL_GetTicks() >= Ticks + 1000) {
if (Frames > 999) {
Frames=999;
}
@@ -2357,29 +2096,25 @@ void DrawEverything(int xsize, int ysize,BlockGameSdl *theGame, BlockGameSdl *th
}
//Generates the standard background
-static void MakeBackground(int xsize,int ysize)
-{
+static void MakeBackground(int xsize,int ysize) {
int w = backgroundImage->w;
int h = backgroundImage->h;
- for(int i=0; i*w<xsize; i++)
- for(int j=0; j*h<ysize; j++)
- {
+ for (int i=0; i*w<xsize; i++)
+ for (int j=0; j*h<ysize; j++) {
DrawIMG(backgroundImage,background,i*w,j*h);
}
standardBackground = true;
}
//Generates the background with red board backs
-static void MakeBackground(int xsize,int ysize,BlockGameSdl *theGame, BlockGameSdl *theGame2)
-{
+static void MakeBackground(int xsize,int ysize,BlockGameSdl* theGame, BlockGameSdl* theGame2) {
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, BlockGameSdl *theGame)
-{
+static void MakeBackground(int xsize, int ysize, BlockGameSdl* theGame) {
MakeBackground(xsize,ysize);
DrawIMG(boardBackBack,background,theGame->GetTopX()-60,theGame->GetTopY()-68);
standardBackground = false;
@@ -2387,8 +2122,7 @@ static void MakeBackground(int xsize, int ysize, BlockGameSdl *theGame)
//The function that allows the player to choose PuzzleLevel
-int PuzzleLevelSelect(int Type)
-{
+int PuzzleLevelSelect(int Type) {
const int xplace = 200;
const int yplace = 300;
int levelNr = 0;
@@ -2404,8 +2138,7 @@ int PuzzleLevelSelect(int Type)
int selected = 0;
//Loads the levels, if they havn't been loaded:
- if(Type == 0)
- {
+ if (Type == 0) {
LoadPuzzleStages();
}
@@ -2413,57 +2146,44 @@ int PuzzleLevelSelect(int Type)
SDL_GetTicks();
MakeBackground(xsize,ysize);
- if(Type == 0)
- {
+ if (Type == 0) {
nrOfLevels = PuzzleGetNumberOfPuzzles();
}
- if(Type == 1)
- {
+ if (Type == 1) {
ifstream stageFile(stageClearSavePath.c_str(),ios::binary);
- if (stageFile)
- {
- for (int i = 0; i<nrOfStageLevels; i++)
- {
+ if (stageFile) {
+ for (int i = 0; i<nrOfStageLevels; i++) {
stageFile.read(reinterpret_cast<char*>(&tempBool),sizeof(bool));
stageCleared[i]=tempBool;
}
- if(!stageFile.eof())
- {
- for(int i=0; i<nrOfStageLevels; i++)
- {
+ if (!stageFile.eof()) {
+ for (int i=0; i<nrOfStageLevels; i++) {
tempUInt32 = 0;
- if(!stageFile.eof())
- {
+ if (!stageFile.eof()) {
stageFile.read(reinterpret_cast<char*>(&tempUInt32),sizeof(Uint32));
}
stageScores[i]=tempUInt32;
totalScore+=tempUInt32;
}
- for(int i=0; i<nrOfStageLevels; i++)
- {
+ for (int i=0; i<nrOfStageLevels; i++) {
tempUInt32 = 0;
- if(!stageFile.eof())
- {
+ if (!stageFile.eof()) {
stageFile.read(reinterpret_cast<char*>(&tempUInt32),sizeof(Uint32));
}
stageTimes[i]=tempUInt32;
totalTime += tempUInt32;
}
}
- else
- {
- for(int i=0; i<nrOfStageLevels; i++)
- {
+ else {
+ for (int i=0; i<nrOfStageLevels; i++) {
stageScores[i]=0;
stageTimes[i]=0;
}
}
stageFile.close();
}
- else
- {
- for (int i=0; i<nrOfStageLevels; i++)
- {
+ else {
+ for (int i=0; i<nrOfStageLevels; i++) {
stageCleared[i]= false;
stageScores[i]=0;
stageTimes[i]=0;
@@ -2472,26 +2192,22 @@ int PuzzleLevelSelect(int Type)
nrOfLevels = nrOfStageLevels;
}
- while(!levelSelected)
- {
+ while (!levelSelected) {
SDL_GetTicks();
DrawIMG(background, screen, 0, 0);
DrawIMG(iCheckBoxArea,screen,xplace,yplace);
- if(Type == 0)
- {
+ if (Type == 0) {
NFont_Write(screen, xplace+12,yplace+2,_("Select Puzzle") );
}
- if(Type == 1)
- {
+ if (Type == 1) {
NFont_Write(screen, xplace+12,yplace+2, _("Stage Clear Level Select") );
}
//Now drow the fields you click in (and a V if clicked):
- for (int i = 0; i < nrOfLevels; i++)
- {
+ for (int i = 0; i < nrOfLevels; i++) {
DrawIMG(iLevelCheckBox,screen,xplace+10+(i%10)*50, yplace+60+(i/10)*50);
- if(i==selected) {
+ if (i==selected) {
DrawIMG(iLevelCheckBoxMarked,screen,xplace+10+(i%10)*50, yplace+60+(i/10)*50);
}
if (Type == 0 && PuzzleIsCleared(i)) {
@@ -2504,47 +2220,36 @@ int PuzzleLevelSelect(int Type)
SDL_Event event;
while ( SDL_PollEvent(&event) )
- if ( event.type == SDL_KEYDOWN )
- {
- if ( event.key.keysym.sym == SDLK_ESCAPE )
- {
+ if ( event.type == SDL_KEYDOWN ) {
+ if ( event.key.keysym.sym == SDLK_ESCAPE ) {
levelNr = -1;
levelSelected = true;
}
- if ( event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER )
- {
+ if ( event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER ) {
levelNr = selected;
levelSelected = true;
}
- if ( event.key.keysym.sym == SDLK_RIGHT )
- {
+ if ( event.key.keysym.sym == SDLK_RIGHT ) {
++selected;
- if(selected >= nrOfLevels)
- {
+ if (selected >= nrOfLevels) {
selected = 0;
}
}
- if ( event.key.keysym.sym == SDLK_LEFT )
- {
+ if ( event.key.keysym.sym == SDLK_LEFT ) {
--selected;
- if(selected < 0)
- {
+ if (selected < 0) {
selected = nrOfLevels-1;
}
}
- if ( event.key.keysym.sym == SDLK_DOWN )
- {
+ if ( event.key.keysym.sym == SDLK_DOWN ) {
selected+=10;
- if(selected >= nrOfLevels)
- {
+ if (selected >= nrOfLevels) {
selected-=10;
}
}
- if ( event.key.keysym.sym == SDLK_UP )
- {
+ if ( event.key.keysym.sym == SDLK_UP ) {
selected-=10;
- if(selected < 0)
- {
+ if (selected < 0) {
selected+=10;
}
}
@@ -2553,19 +2258,16 @@ int PuzzleLevelSelect(int Type)
SDL_GetKeyState(nullptr);
SDL_GetMouseState(&mousex,&mousey);
- if(mousex != oldmousex || mousey != oldmousey)
- {
+ if (mousex != oldmousex || mousey != oldmousey) {
int tmpSelected = -1;
int j;
for (j = 0; (tmpSelected == -1) && ( (j<nrOfLevels/10)||((j<nrOfLevels/10+1)&&(nrOfLevels%10 != 0)) ); j++)
- if ((60+j*50<mousey-yplace)&&(mousey-yplace<j*50+92))
- {
+ if ((60+j*50<mousey-yplace)&&(mousey-yplace<j*50+92)) {
tmpSelected = j*10;
}
if (tmpSelected != -1)
for (int k = 0; (( (!(nrOfLevels%10) || k<nrOfLevels-10*(j-1)) )&&(k<10)); k++)
- if ((10+k*50<mousex-xplace)&&(mousex-xplace<k*50+42))
- {
+ if ((10+k*50<mousex-xplace)&&(mousex-xplace<k*50+42)) {
tmpSelected +=k;
selected = tmpSelected;
}
@@ -2574,44 +2276,37 @@ int PuzzleLevelSelect(int Type)
oldmousex= mousex;
// If the mouse button is released, make bMouseUp equal true
- if (!SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(1))
- {
+ if (!SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(1)) {
bMouseUp=true;
}
- if (SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(1) && bMouseUp)
- {
+ if (SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(1) && bMouseUp) {
bMouseUp = false;
int levelClicked = -1;
int i;
for (i = 0; (i<nrOfLevels/10)||((i<nrOfLevels/10+1)&&(nrOfLevels%10 != 0)); i++)
- if ((60+i*50<mousey-yplace)&&(mousey-yplace<i*50+92))
- {
+ if ((60+i*50<mousey-yplace)&&(mousey-yplace<i*50+92)) {
levelClicked = i*10;
}
i++;
if (levelClicked != -1)
for (int j = 0; ((j<nrOfStageLevels%(i*10))&&(j<10)); j++)
- if ((10+j*50<mousex-xplace)&&(mousex-xplace<j*50+42))
- {
+ if ((10+j*50<mousex-xplace)&&(mousex-xplace<j*50+42)) {
levelClicked +=j;
levelSelected = true;
levelNr = levelClicked;
}
}
- if(Type == 1)
- {
+ if (Type == 1) {
string scoreString = _("Best score: 0");
string timeString = _("Time used: -- : --");
- if(stageScores.at(selected)>0)
- {
+ if (stageScores.at(selected)>0) {
scoreString = _("Best score: ")+itoa(stageScores.at(selected));
}
- if(stageTimes.at(selected)>0)
- {
+ if (stageTimes.at(selected)>0) {
timeString = _("Time used: ")+itoa(stageTimes.at(selected)/1000/60)+" : "+itoa2((stageTimes.at(selected)/1000)%60);
}
@@ -2632,8 +2327,7 @@ int PuzzleLevelSelect(int Type)
//The function that allows the player to choose Level number
-void startVsMenu()
-{
+void startVsMenu() {
const int xplace = 200;
const int yplace = 100;
int mousex, mousey;
@@ -2645,8 +2339,7 @@ void startVsMenu()
MakeBackground(xsize,ysize);
NFont_Write(background, 360,650, _("Press ESC to accept") );
DrawIMG(bBack,background,xsize/2-120/2,600);
- do
- {
+ do {
//nowTime=SDL_GetTicks();
DrawIMG(background, screen, 0, 0);
DrawIMG(changeButtonsBack,screen,xplace,yplace);
@@ -2654,84 +2347,69 @@ void startVsMenu()
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++)
- {
+ 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)
- {
+ if (player1Speed==i) {
DrawIMG(iLevelCheck,screen,xplace+50+i*40,yplace+150);
}
}
- for (int i=0; i<5; i++)
- {
+ 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)
- {
+ 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)
- {
+ 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)
- {
+ 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++)
- {
+ 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)
- {
+ if (player1handicap==i) {
DrawIMG(iLevelCheck,screen,xplace+50+i*40,yplace+330);
}
}
- for (int i=0; i<5; i++)
- {
+ 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)
- {
+ 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 )
- {
+ 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 )
- {
+ if ( event.key.keysym.sym == SDLK_RETURN ) {
done = true;
}
- if ( event.key.keysym.sym == SDLK_KP_ENTER )
- {
+ if ( event.key.keysym.sym == SDLK_KP_ENTER ) {
done = true;
}
}
@@ -2742,53 +2420,40 @@ void startVsMenu()
SDL_GetMouseState(&mousex,&mousey);
// If the mouse button is released, make bMouseUp equal true
- if (!SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(1))
- {
+ if (!SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(1)) {
bMouseUp=true;
}
- if (SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(1) && bMouseUp)
- {
+ if (SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(1) && bMouseUp) {
bMouseUp = false;
- if ((mousex>xplace+50+70)&&(mousey>yplace+200)&&(mousex<xplace+50+70+30)&&(mousey<yplace+200+30))
- {
+ if ((mousex>xplace+50+70)&&(mousey>yplace+200)&&(mousex<xplace+50+70+30)&&(mousey<yplace+200+30)) {
player1AI=!player1AI;
}
- if ((mousex>xplace+50+70+300)&&(mousey>yplace+200)&&(mousex<xplace+50+70+30+300)&&(mousey<yplace+200+30))
- {
+ if ((mousex>xplace+50+70+300)&&(mousey>yplace+200)&&(mousex<xplace+50+70+30+300)&&(mousey<yplace+200+30)) {
player2AI=!player2AI;
}
- for (int i=0; i<5; i++)
- {
- if ((mousex>xplace+50+i*40)&&(mousex<xplace+50+i*40+30)&&(mousey>yplace+150)&&(mousey<yplace+150+30))
- {
+ for (int i=0; i<5; i++) {
+ if ((mousex>xplace+50+i*40)&&(mousex<xplace+50+i*40+30)&&(mousey>yplace+150)&&(mousey<yplace+150+30)) {
player1Speed=i;
}
}
- for (int i=0; i<5; i++)
- {
- if ((mousex>xplace+50+i*40+300)&&(mousex<xplace+50+i*40+30+300)&&(mousey>yplace+150)&&(mousey<yplace+150+30))
- {
+ for (int i=0; i<5; i++) {
+ if ((mousex>xplace+50+i*40+300)&&(mousex<xplace+50+i*40+30+300)&&(mousey>yplace+150)&&(mousey<yplace+150+30)) {
player2Speed=i;
}
}
- for (int i=0; i<5; i++)
- {
- if ((mousex>xplace+50+i*40)&&(mousex<xplace+50+i*40+30)&&(mousey>yplace+330)&&(mousey<yplace+330+30))
- {
+ for (int i=0; i<5; i++) {
+ if ((mousex>xplace+50+i*40)&&(mousex<xplace+50+i*40+30)&&(mousey>yplace+330)&&(mousey<yplace+330+30)) {
player1handicap=i;
}
}
- for (int i=0; i<5; i++)
- {
- if ((mousex>xplace+50+i*40+300)&&(mousex<xplace+50+i*40+30+300)&&(mousey>yplace+330)&&(mousey<yplace+330+30))
- {
+ for (int i=0; i<5; i++) {
+ if ((mousex>xplace+50+i*40+300)&&(mousex<xplace+50+i*40+30+300)&&(mousey>yplace+330)&&(mousey<yplace+330+30)) {
player2handicap=i;
}
}
- if ((mousex>xsize/2-120/2)&&(mousex<xsize/2+120/2)&&(mousey>600)&&(mousey<640))
- {
+ if ((mousex>xsize/2-120/2)&&(mousex<xsize/2+120/2)&&(mousey>600)&&(mousey<640)) {
done = true;
}
}
@@ -2804,19 +2469,15 @@ void startVsMenu()
}
//This function will promt for the user to select another file for puzzle mode
-void changePuzzleLevels()
-{
+void changePuzzleLevels() {
char theFileName[30];
strcpy(theFileName, PuzzleGetName().c_str());
- for (int i=PuzzleGetName().length(); i<30; i++)
- {
+ for (int i=PuzzleGetName().length(); i<30; i++) {
theFileName[i]=' ';
}
theFileName[29]=0;
- if (OpenFileDialogbox(200,100,theFileName))
- {
- for (int i=28; ((theFileName[i]==' ')&&(i>0)); i--)
- {
+ if (OpenFileDialogbox(200,100,theFileName)) {
+ for (int i=28; ((theFileName[i]==' ')&&(i>0)); i--) {
theFileName[i]=0;
}
PuzzleSetName(theFileName);
@@ -2825,12 +2486,10 @@ void changePuzzleLevels()
PuzzleSetSavePath(home+"/.gamesaves/blockattack/"+PuzzleGetName()+".save");
#elif defined(_WIN32)
string home = getMyDocumentsPath();
- if (&home!=nullptr)
- {
+ if (&home!=nullptr) {
PuzzleSetSavePath(home+"/My Games/blockattack/"+PuzzleGetName()+".save");
}
- else
- {
+ else {
PuzzleSetSavePath(PuzzleGetName()+".save");
}
#else
@@ -2840,11 +2499,10 @@ void changePuzzleLevels()
}
-static BlockGameSdl *player1;
-static BlockGameSdl *player2;
+static BlockGameSdl* player1;
+static BlockGameSdl* player2;
-static void StartSinglePlayerEndless()
-{
+static void StartSinglePlayerEndless() {
//1 player - endless
player1->NewGame(SDL_GetTicks());
player1->putStartBlocks(time(0));
@@ -2854,8 +2512,7 @@ static void StartSinglePlayerEndless()
player2->name = player2name;
}
-static void StartSinglePlayerTimeTrial()
-{
+static void StartSinglePlayerTimeTrial() {
player1->NewTimeTrialGame(SDL_GetTicks());
twoPlayers =false;
player2->SetGameOver();
@@ -2864,11 +2521,9 @@ static void StartSinglePlayerTimeTrial()
player2->name = player2name;
}
-static int StartSinglePlayerPuzzle(int level)
-{
+static int StartSinglePlayerPuzzle(int level) {
int myLevel = PuzzleLevelSelect(0);
- if(myLevel == -1)
- {
+ if (myLevel == -1) {
return 1;
}
player1->NewPuzzleGame(myLevel,SDL_GetTicks());
@@ -2883,8 +2538,7 @@ static int StartSinglePlayerPuzzle(int level)
}
-static void StarTwoPlayerTimeTrial()
-{
+static void StarTwoPlayerTimeTrial() {
player1->NewTimeTrialGame(SDL_GetTicks());
player2->NewTimeTrialGame(SDL_GetTicks());
int theTime = time(0);
@@ -2895,20 +2549,17 @@ static void StarTwoPlayerTimeTrial()
player2->setGameSpeed(player2Speed);
player1->setHandicap(player1handicap);
player2->setHandicap(player2handicap);
- if(player1AI)
- {
+ if (player1AI) {
player1->setAIlevel(player1AIlevel);
}
- if(player2AI)
- {
+ if (player2AI) {
player2->setAIlevel(player2AIlevel);
}
player1->name = player1name;
player2->name = player2name;
}
-static void StartTwoPlayerVs()
-{
+static void StartTwoPlayerVs() {
//2 player - VsMode
player1->NewVsGame(player2,SDL_GetTicks());
player2->NewVsGame(player1,SDL_GetTicks());
@@ -2918,12 +2569,10 @@ static void StartTwoPlayerVs()
player2->setGameSpeed(player2Speed);
player1->setHandicap(player1handicap);
player2->setHandicap(player2handicap);
- if(player1AI)
- {
+ if (player1AI) {
player1->setAIlevel(player1AIlevel);
}
- if(player2AI)
- {
+ if (player2AI) {
player2->setAIlevel(player2AIlevel);
}
int theTime = time(0);
@@ -2934,22 +2583,18 @@ static void StartTwoPlayerVs()
}
//The main function, quite big... too big
-int main(int argc, char *argv[])
-{
+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
#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"))
- {
+ if (system("mkdir -p ~/.gamesaves/blockattack/screenshots")) {
cerr << "mkdir error creating ~/.gamesaves/blockattack/screenshots" << endl;
}
- if(system("mkdir -p ~/.gamesaves/blockattack/replays"))
- {
+ if (system("mkdir -p ~/.gamesaves/blockattack/replays")) {
cerr << "mkdir error creating ~/.gamesaves/blockattack/replays" << endl;
}
- if(system("mkdir -p ~/.gamesaves/blockattack/puzzles"))
- {
+ if (system("mkdir -p ~/.gamesaves/blockattack/puzzles")) {
cerr << "mkdir error creating ~/.gamesaves/blockattack/puzzles" << endl;
}
#elif defined(_WIN32)
@@ -2970,12 +2615,10 @@ int main(int argc, char *argv[])
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
- if (argc > 1)
- {
+ if (argc > 1) {
int argumentNr = 1;
forceredraw = 2;
- while (argc>argumentNr)
- {
+ while (argc>argumentNr) {
const char helpString[] = "--help";
const char priorityString[] = "-priority";
const char forceRedrawString[] = "-forceredraw";
@@ -2985,8 +2628,7 @@ int main(int argc, char *argv[])
const char IntegratedEditor[] = "-editor";
const char selectTheme[] = "-theme";
const char verbose[] = "-v";
- if (!(strncmp(argv[argumentNr],helpString,6)))
- {
+ 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 <<
@@ -2999,50 +2641,39 @@ int main(int argc, char *argv[])
#endif
return 0;
}
- if (!(strncmp(argv[argumentNr],priorityString,9)))
- {
- if(verboseLevel)
- {
+ if (!(strncmp(argv[argumentNr],priorityString,9))) {
+ if (verboseLevel) {
cout << "Priority mode" << endl;
}
highPriority = true;
}
- if (!(strncmp(argv[argumentNr],forceRedrawString,12)))
- {
+ if (!(strncmp(argv[argumentNr],forceRedrawString,12))) {
forceredraw = 1;
}
- if (!(strncmp(argv[argumentNr],forcepartdrawString,14)))
- {
+ if (!(strncmp(argv[argumentNr],forcepartdrawString,14))) {
forceredraw = 2;
}
- if (!(strncmp(argv[argumentNr],singlePuzzleString,3)))
- {
+ if (!(strncmp(argv[argumentNr],singlePuzzleString,3))) {
singlePuzzle = true; //We will just have one puzzle
- if (argv[argumentNr+1][1]!=0)
- {
+ if (argv[argumentNr+1][1]!=0) {
singlePuzzleNr = (argv[argumentNr+1][1]-'0')+(argv[argumentNr+1][0]-'0')*10;
}
- else
- {
+ else {
singlePuzzleNr = (argv[argumentNr+1][0]-'0');
}
singlePuzzleFile = argv[argumentNr+2];
argumentNr+=2;
- if(verboseLevel)
- {
+ if (verboseLevel) {
cout << "SinglePuzzleMode, File: " << singlePuzzleFile << " and Level: " << singlePuzzleNr << endl;
}
}
- if (!(strncmp(argv[argumentNr],noSoundAtAll,8)))
- {
+ if (!(strncmp(argv[argumentNr],noSoundAtAll,8))) {
NoSound = true;
}
- if (!(strncmp(argv[argumentNr],IntegratedEditor,7)))
- {
+ if (!(strncmp(argv[argumentNr],IntegratedEditor,7))) {
#if LEVELEDITOR
editorMode = true;
- if(verboseLevel)
- {
+ if (verboseLevel) {
cout << "Integrated Puzzle Editor Activated" << endl;
}
#else
@@ -3050,17 +2681,14 @@ int main(int argc, char *argv[])
return -1;
#endif
}
- if(!(strncmp(argv[argumentNr],selectTheme,6)))
- {
+ if (!(strncmp(argv[argumentNr],selectTheme,6))) {
argumentNr++; //Go to themename (the next argument)
- if(verboseLevel)
- {
+ if (verboseLevel) {
cout << "Theme set to \"" << argv[argumentNr] << '"' << endl;
}
Config::getInstance()->setString("themename",argv[argumentNr]);
}
- if(!(strcmp(argv[argumentNr],verbose)))
- {
+ if (!(strcmp(argv[argumentNr],verbose))) {
verboseLevel++;
}
argumentNr++;
@@ -3086,12 +2714,10 @@ int main(int argc, char *argv[])
#elif defined(_WIN32)
string home = getMyDocumentsPath();
string optionsPath;
- if (&home!=nullptr) //Null if no APPDATA dir exists (win 9x)
- {
+ if (&home!=nullptr) { //Null if no APPDATA dir exists (win 9x)
optionsPath = home+"/My Games/blockattack/options.dat";
}
- else
- {
+ else {
optionsPath = "options.dat";
}
#else
@@ -3102,13 +2728,11 @@ int main(int argc, char *argv[])
stageClearSavePath = home+"/.gamesaves/blockattack/stageClear.SCsave";
PuzzleSetSavePath(home+"/.gamesaves/blockattack/puzzle.levels.save");
#elif defined(_WIN32)
- if (&home!=nullptr)
- {
+ if (&home!=nullptr) {
stageClearSavePath = home+"/My Games/blockattack/stageClear.SCsave";
PuzzleSetSavePath(home+"/My Games/blockattack/puzzle.levels.save");
}
- else
- {
+ else {
stageClearSavePath = "stageClear.SCsave";
PuzzleSetSavePath("puzzle.levels.save");
}
@@ -3119,8 +2743,7 @@ int main(int argc, char *argv[])
PuzzleSetName("puzzle.levels");
//Init SDL
- if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
- {
+ if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
cerr << "Unable to init SDL: " << SDL_GetError() << endl;
exit(1);
}
@@ -3136,8 +2759,7 @@ int main(int argc, char *argv[])
//Open Audio
if (!NoSound) //If sound has not been disabled, then load the sound system
- if (Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 2048) < 0)
- {
+ if (Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 2048) < 0) {
cerr << "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
@@ -3145,8 +2767,7 @@ int main(int argc, char *argv[])
SDL_WM_SetCaption("Block Attack - Rise of the Blocks", nullptr); //Sets title line
- if(verboseLevel)
- {
+ if (verboseLevel) {
//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 <<
@@ -3184,11 +2805,10 @@ int main(int argc, char *argv[])
strcpy(player1name, "Player 1 \0");
strcpy(player2name, "Player 2 \0");
- Config *configSettings = Config::getInstance();
+ Config* configSettings = Config::getInstance();
//configSettings->setString("aNumber"," A string");
//configSettings->save();
- if(configSettings->exists("fullscreen")) //Test if an configFile exists
- {
+ if (configSettings->exists("fullscreen")) { //Test if an configFile exists
bFullscreen = (bool)configSettings->getInt("fullscreen");
MusicEnabled = (bool)configSettings->getInt("musicenabled");
SoundEnabled = (bool)configSettings->getInt("soundenabled");
@@ -3197,62 +2817,57 @@ int main(int argc, char *argv[])
joyplay1 = (bool)configSettings->getInt("joypad1");
joyplay2 = (bool)configSettings->getInt("joypad2");
- if(configSettings->exists("player1keyup")) {
+ if (configSettings->exists("player1keyup")) {
keySettings[0].up = (SDLKey)configSettings->getInt("player1keyup");
}
- if(configSettings->exists("player1keydown")) {
+ if (configSettings->exists("player1keydown")) {
keySettings[0].down = (SDLKey)configSettings->getInt("player1keydown");
}
- if(configSettings->exists("player1keyleft")) {
+ if (configSettings->exists("player1keyleft")) {
keySettings[0].left = (SDLKey)configSettings->getInt("player1keyleft");
}
- if(configSettings->exists("player1keyright")) {
+ if (configSettings->exists("player1keyright")) {
keySettings[0].right = (SDLKey)configSettings->getInt("player1keyright");
}
- if(configSettings->exists("player1keychange")) {
+ if (configSettings->exists("player1keychange")) {
keySettings[0].change = (SDLKey)configSettings->getInt("player1keychange");
}
- if(configSettings->exists("player1keypush")) {
+ if (configSettings->exists("player1keypush")) {
keySettings[0].push = (SDLKey)configSettings->getInt("player1keypush");
}
- if(configSettings->exists("player2keyup")) {
+ if (configSettings->exists("player2keyup")) {
keySettings[2].up = (SDLKey)configSettings->getInt("player2keyup");
}
- if(configSettings->exists("player2keydown")) {
+ if (configSettings->exists("player2keydown")) {
keySettings[2].down = (SDLKey)configSettings->getInt("player2keydown");
}
- if(configSettings->exists("player2keyleft")) {
+ if (configSettings->exists("player2keyleft")) {
keySettings[2].left = (SDLKey)configSettings->getInt("player2keyleft");
}
- if(configSettings->exists("player2keyright")) {
+ if (configSettings->exists("player2keyright")) {
keySettings[2].right = (SDLKey)configSettings->getInt("player2keyright");
}
- if(configSettings->exists("player2keychange")) {
+ if (configSettings->exists("player2keychange")) {
keySettings[2].change = (SDLKey)configSettings->getInt("player2keychange");
}
- if(configSettings->exists("player2keypush")) {
+ if (configSettings->exists("player2keypush")) {
keySettings[2].push = (SDLKey)configSettings->getInt("player2keypush");
}
- if(configSettings->exists("player1name"))
- {
+ if (configSettings->exists("player1name")) {
strncpy(player1name,(configSettings->getString("player1name")).c_str(),28);
}
- if(configSettings->exists("player2name"))
- {
+ if (configSettings->exists("player2name")) {
strncpy(player2name,(configSettings->getString("player2name")).c_str(),28);
}
- if(verboseLevel)
- {
+ if (verboseLevel) {
cout << "Data loaded from config file" << endl;
}
}
- else
- {
+ else {
//Reads options from file:
ifstream optionsFile(optionsPath.c_str(), ios::binary);
- if (optionsFile)
- {
+ if (optionsFile) {
//reads data: xsize,ysize,fullescreen, player1keys, player2keys, MusicEnabled, SoundEnabled,player1name,player2name
optionsFile.read(reinterpret_cast<char*>(&xsize), sizeof(int));
optionsFile.read(reinterpret_cast<char*>(&ysize), sizeof(int));
@@ -3274,23 +2889,19 @@ int main(int argc, char *argv[])
optionsFile.read(player1name, 30*sizeof(char));
optionsFile.read(player2name, 30*sizeof(char));
//mouseplay?
- if (!optionsFile.eof())
- {
+ if (!optionsFile.eof()) {
optionsFile.read(reinterpret_cast<char*>(&mouseplay1), sizeof(bool));
optionsFile.read(reinterpret_cast<char*>(&mouseplay2), sizeof(bool));
optionsFile.read(reinterpret_cast<char*>(&joyplay1),sizeof(bool));
optionsFile.read(reinterpret_cast<char*>(&joyplay2),sizeof(bool));
}
optionsFile.close();
- if(verboseLevel)
- {
+ if (verboseLevel) {
cout << "Data loaded from oldstyle options file" << endl;
}
}
- else
- {
- if(verboseLevel)
- {
+ else {
+ if (verboseLevel) {
cout << "Unable to load options file, using default values" << endl;
}
}
@@ -3299,15 +2910,13 @@ int main(int argc, char *argv[])
#if NETWORK
Config::getInstance()->setDefault("portv4","42200");
strcpy(serverAddress, "192.168.0.2 \0");
- if(configSettings->exists("address0"))
- {
+ if (configSettings->exists("address0")) {
strcpy(serverAddress, " \0");
strncpy(serverAddress,configSettings->getString("address0").c_str(),sizeof(serverAddress)-1);
}
#endif
- if (singlePuzzle)
- {
+ if (singlePuzzle) {
xsize=300;
ysize=600;
}
@@ -3321,8 +2930,7 @@ int main(int argc, char *argv[])
screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_ANYFORMAT);
}
- if ( screen == nullptr )
- {
+ if ( screen == nullptr ) {
cerr << "Unable to set " << xsize << "x" << ysize << " video: " << SDL_GetError() << endl;
exit(1);
}
@@ -3332,11 +2940,10 @@ int main(int argc, char *argv[])
//Load default theme
loadTheme(Config::getInstance()->getString("themename"));
//Now sets the icon:
- SDL_Surface *icon = IMG_Load2("gfx/icon.png");
+ SDL_Surface* icon = IMG_Load2("gfx/icon.png");
SDL_WM_SetIcon(icon,nullptr);
- if(verboseLevel)
- {
+ if (verboseLevel) {
cout << "Images loaded" << endl;
}
@@ -3368,12 +2975,10 @@ int main(int argc, char *argv[])
theGame.NewPuzzleGame(singlePuzzleNr, SDL_GetTicks());
}
//Draws everything to screen
- if (!editorMode)
- {
+ if (!editorMode) {
MakeBackground(xsize,ysize,&theGame,&theGame2);
}
- else
- {
+ else {
MakeBackground(xsize,ysize,&theGame);
}
DrawIMG(background, screen, 0, 0);
@@ -3385,8 +2990,7 @@ int main(int argc, char *argv[])
//Saves options
- if (!editorMode)
- {
+ if (!editorMode) {
configSettings->setInt("fullscreen",(int)bFullscreen);
configSettings->setInt("musicenabled",(int)MusicEnabled);
configSettings->setInt("soundenabled",(int)SoundEnabled);
@@ -3419,14 +3023,12 @@ int main(int argc, char *argv[])
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;
- if(verboseLevel)
- {
+ if (verboseLevel) {
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);
- if(verboseLevel)
- {
+ if (verboseLevel) {
cout << "Total run time is now: " << ct.days << " days " << ct.hours << " hours " << ct.minutes << " mins and " << ct.seconds << " secs" << endl;
}
@@ -3444,9 +3046,8 @@ int main(int argc, char *argv[])
}
-int runGame(int gametype, int level)
-{
- Uint8 *keys;
+int runGame(int gametype, int level) {
+ Uint8* keys;
int mousex, mousey; //Mouse coordinates
bScreenLocked = false;
theTopScoresEndless = Highscore(1);
@@ -3498,18 +3099,15 @@ int runGame(int gametype, int level)
Joypad joypad1 = Joypad(); //Creates a joypad
Joypad joypad2 = Joypad(); //Creates a joypad
- if (singlePuzzle)
- {
+ if (singlePuzzle) {
LoadPuzzleStages();
theGame.NewPuzzleGame(singlePuzzleNr, SDL_GetTicks());
}
//Draws everything to screen
- if (!editorMode)
- {
+ if (!editorMode) {
MakeBackground(xsize,ysize,&theGame,&theGame2);
}
- else
- {
+ else {
MakeBackground(xsize,ysize,&theGame);
}
/*DrawIMG(background, screen, 0, 0);
@@ -3517,28 +3115,22 @@ int runGame(int gametype, int level)
SDL_Flip(screen);*/
//game loop
int done = 0;
- if(verboseLevel)
- {
+ if (verboseLevel) {
cout << "Starting game loop" << endl;
}
bool mustsetupgame = true;
- while (done == 0)
- {
- if(mustsetupgame)
- {
- switch(gametype)
- {
+ while (done == 0) {
+ if (mustsetupgame) {
+ switch (gametype) {
case 1:
StartSinglePlayerTimeTrial();
break;
- case 2:
- {
+ case 2: {
int myLevel = PuzzleLevelSelect(1);
- if(myLevel == -1)
- {
+ if (myLevel == -1) {
return 1;
}
theGame.NewStageGame(myLevel,SDL_GetTicks());
@@ -3551,13 +3143,11 @@ int runGame(int gametype, int level)
}
break;
case 3:
- if(StartSinglePlayerPuzzle(level))
- {
+ if (StartSinglePlayerPuzzle(level)) {
return 1;
}
break;
- case 4:
- {
+ case 4: {
//1 player - Vs mode
int theAIlevel = level; //startSingleVs();
theGame.NewVsGame(&theGame2, SDL_GetTicks());
@@ -3594,14 +3184,12 @@ int runGame(int gametype, int level)
SDL_Delay(10);
}
- if ((standardBackground)&&(!editorMode))
- {
+ if ((standardBackground)&&(!editorMode)) {
MakeBackground(xsize,ysize,&theGame,&theGame2);
DrawIMG(background, screen, 0, 0);
}
- if ((standardBackground)&&(editorMode))
- {
+ if ((standardBackground)&&(editorMode)) {
DrawIMG(backgroundImage, screen, 0, 0);
MakeBackground(xsize,ysize,&theGame);
DrawIMG(background, screen, 0, 0);
@@ -3612,111 +3200,90 @@ int runGame(int gametype, int level)
theExplosionManeger.update();
theTextManeger.update();
- if (!bScreenLocked)
- {
+ if (!bScreenLocked) {
SDL_Event event;
- while ( SDL_PollEvent(&event) )
- {
- if ( event.type == SDL_QUIT )
- {
+ 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 ( event.type == SDL_KEYDOWN ) {
+ if ( event.key.keysym.sym == SDLK_ESCAPE || ( event.key.keysym.sym == SDLK_RETURN && theGame.isGameOver() ) ) {
done=1;
DrawIMG(background, screen, 0, 0);
}
- if ((!editorMode)&&(!editorModeTest)&&(!theGame.GetAIenabled()))
- {
+ if ((!editorMode)&&(!editorModeTest)&&(!theGame.GetAIenabled())) {
//player1:
- if ( event.key.keysym.sym == keySettings[player1keys].up )
- {
+ 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 )
- {
+ 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) )
- {
+ if ( (event.key.keysym.sym == keySettings[player1keys].left) ) {
theGame.MoveCursor('W');
repeatingW[0]=true;
timeHeldP1W=SDL_GetTicks();
timesRepeatedP1W=0;
}
- if ( (event.key.keysym.sym == keySettings[player1keys].right) )
- {
+ if ( (event.key.keysym.sym == keySettings[player1keys].right) ) {
theGame.MoveCursor('E');
repeatingE[0]=true;
timeHeldP1E=SDL_GetTicks();
timesRepeatedP1E=0;
}
- if ( event.key.keysym.sym == keySettings[player1keys].push )
- {
+ if ( event.key.keysym.sym == keySettings[player1keys].push ) {
theGame.PushLine();
}
- if ( event.key.keysym.sym == keySettings[player1keys].change )
- {
+ if ( event.key.keysym.sym == keySettings[player1keys].change ) {
theGame.SwitchAtCursor();
}
}
- if (!editorMode && !theGame2.GetAIenabled())
- {
+ if (!editorMode && !theGame2.GetAIenabled()) {
//player2:
- if ( event.key.keysym.sym == keySettings[player2keys].up )
- {
+ 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 )
- {
+ 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) )
- {
+ if ( (event.key.keysym.sym == keySettings[player2keys].left) ) {
theGame2.MoveCursor('W');
repeatingW[1]=true;
timeHeldP2W=SDL_GetTicks();
timesRepeatedP2W=0;
}
- if ( (event.key.keysym.sym == keySettings[player2keys].right) )
- {
+ if ( (event.key.keysym.sym == keySettings[player2keys].right) ) {
theGame2.MoveCursor('E');
repeatingE[1]=true;
timeHeldP2E=SDL_GetTicks();
timesRepeatedP2E=0;
}
- if ( event.key.keysym.sym == keySettings[player2keys].push )
- {
+ if ( event.key.keysym.sym == keySettings[player2keys].push ) {
theGame2.PushLine();
}
- if ( event.key.keysym.sym == keySettings[player2keys].change )
- {
+ if ( event.key.keysym.sym == keySettings[player2keys].change ) {
theGame2.SwitchAtCursor();
}
}
//common:
- if ((!singlePuzzle)&&(!editorMode))
- {
- if ( event.key.keysym.sym == SDLK_F2 )
- {
+ if ((!singlePuzzle)&&(!editorMode)) {
+ if ( event.key.keysym.sym == SDLK_F2 ) {
/*#if NETWORK
if ((!showOptions)&&(!networkActive)){
#else
@@ -3727,22 +3294,18 @@ int runGame(int gametype, int level)
*/
mustsetupgame = true;
}
- if ( event.key.keysym.sym == SDLK_F10 )
- {
+ if ( event.key.keysym.sym == SDLK_F10 ) {
//StartReplay("/home/poul/.gamesaves/blockattack/quicksave");
}
- if ( event.key.keysym.sym == SDLK_F9 )
- {
+ if ( event.key.keysym.sym == SDLK_F9 ) {
writeScreenShot();
}
if ( event.key.keysym.sym == SDLK_F5 ) {
}
- if ( event.key.keysym.sym == SDLK_F11 )
- {
+ if ( event.key.keysym.sym == SDLK_F11 ) {
} //F11
}
- if ( event.key.keysym.sym == SDLK_F12 )
- {
+ if ( event.key.keysym.sym == SDLK_F12 ) {
done=1;
}
}
@@ -3757,42 +3320,34 @@ int runGame(int gametype, int level)
//Repeating not implemented
//Player 1 start
- if (!(keys[keySettings[player1keys].up]))
- {
+ if (!(keys[keySettings[player1keys].up])) {
repeatingN[0]=false;
}
- while ((repeatingN[0])&&(keys[keySettings[player1keys].up])&&(SDL_GetTicks()>timeHeldP1N+timesRepeatedP1N*repeatDelay+startRepeat))
- {
+ while ((repeatingN[0])&&(keys[keySettings[player1keys].up])&&(SDL_GetTicks()>timeHeldP1N+timesRepeatedP1N*repeatDelay+startRepeat)) {
theGame.MoveCursor('N');
timesRepeatedP1N++;
}
- if (!(keys[keySettings[player1keys].down]))
- {
+ if (!(keys[keySettings[player1keys].down])) {
repeatingS[0]=false;
}
- while ((repeatingS[0])&&(keys[keySettings[player1keys].down])&&(SDL_GetTicks()>timeHeldP1S+timesRepeatedP1S*repeatDelay+startRepeat))
- {
+ while ((repeatingS[0])&&(keys[keySettings[player1keys].down])&&(SDL_GetTicks()>timeHeldP1S+timesRepeatedP1S*repeatDelay+startRepeat)) {
theGame.MoveCursor('S');
timesRepeatedP1S++;
}
- if (!(keys[keySettings[player1keys].left]))
- {
+ if (!(keys[keySettings[player1keys].left])) {
repeatingW[0]=false;
}
- while ((repeatingW[0])&&(keys[keySettings[player1keys].left])&&(SDL_GetTicks()>timeHeldP1W+timesRepeatedP1W*repeatDelay+startRepeat))
- {
+ while ((repeatingW[0])&&(keys[keySettings[player1keys].left])&&(SDL_GetTicks()>timeHeldP1W+timesRepeatedP1W*repeatDelay+startRepeat)) {
timesRepeatedP1W++;
theGame.MoveCursor('W');
}
- if (!(keys[keySettings[player1keys].right]))
- {
+ if (!(keys[keySettings[player1keys].right])) {
repeatingE[0]=false;
}
- while ((repeatingE[0])&&(keys[keySettings[player1keys].right])&&(SDL_GetTicks()>timeHeldP1E+timesRepeatedP1E*repeatDelay+startRepeat))
- {
+ while ((repeatingE[0])&&(keys[keySettings[player1keys].right])&&(SDL_GetTicks()>timeHeldP1E+timesRepeatedP1E*repeatDelay+startRepeat)) {
timesRepeatedP1E++;
theGame.MoveCursor('E');
}
@@ -3800,42 +3355,34 @@ int runGame(int gametype, int level)
//Player 1 end
//Player 2 start
- if (!(keys[keySettings[player2keys].up]))
- {
+ if (!(keys[keySettings[player2keys].up])) {
repeatingN[1]=false;
}
- while ((repeatingN[1])&&(keys[keySettings[player2keys].up])&&(SDL_GetTicks()>timeHeldP2N+timesRepeatedP2N*repeatDelay+startRepeat))
- {
+ while ((repeatingN[1])&&(keys[keySettings[player2keys].up])&&(SDL_GetTicks()>timeHeldP2N+timesRepeatedP2N*repeatDelay+startRepeat)) {
theGame2.MoveCursor('N');
timesRepeatedP2N++;
}
- if (!(keys[keySettings[player2keys].down]))
- {
+ if (!(keys[keySettings[player2keys].down])) {
repeatingS[1]=false;
}
- while ((repeatingS[1])&&(keys[keySettings[player2keys].down])&&(SDL_GetTicks()>timeHeldP2S+timesRepeatedP2S*repeatDelay+startRepeat))
- {
+ while ((repeatingS[1])&&(keys[keySettings[player2keys].down])&&(SDL_GetTicks()>timeHeldP2S+timesRepeatedP2S*repeatDelay+startRepeat)) {
theGame2.MoveCursor('S');
timesRepeatedP2S++;
}
- if (!(keys[keySettings[player2keys].left]))
- {
+ if (!(keys[keySettings[player2keys].left])) {
repeatingW[1]=false;
}
- while ((repeatingW[1])&&(keys[keySettings[player2keys].left])&&(SDL_GetTicks()>timeHeldP2W+timesRepeatedP2W*repeatDelay+startRepeat))
- {
+ while ((repeatingW[1])&&(keys[keySettings[player2keys].left])&&(SDL_GetTicks()>timeHeldP2W+timesRepeatedP2W*repeatDelay+startRepeat)) {
theGame2.MoveCursor('W');
timesRepeatedP2W++;
}
- if (!(keys[keySettings[player2keys].right]))
- {
+ if (!(keys[keySettings[player2keys].right])) {
repeatingE[1]=false;
}
- while ((repeatingE[1])&&(keys[keySettings[player2keys].right])&&(SDL_GetTicks()>timeHeldP2E+timesRepeatedP2E*repeatDelay+startRepeat))
- {
+ while ((repeatingE[1])&&(keys[keySettings[player2keys].right])&&(SDL_GetTicks()>timeHeldP2E+timesRepeatedP2E*repeatDelay+startRepeat)) {
theGame2.MoveCursor('E');
timesRepeatedP2E++;
}
@@ -3851,170 +3398,139 @@ int runGame(int gametype, int level)
**********************************************************************/
//Gameplay
- if (joyplay1||joyplay2)
- {
- if (joypad1.working && !theGame.GetAIenabled())
- {
- if (joyplay1)
- {
+ if (joyplay1||joyplay2) {
+ if (joypad1.working && !theGame.GetAIenabled()) {
+ if (joyplay1) {
joypad1.update();
- if (joypad1.up)
- {
+ if (joypad1.up) {
theGame.MoveCursor('N');
repeatingN[0]=true;
timeHeldP1N=SDL_GetTicks();
timesRepeatedP1N=0;
}
- if (joypad1.down)
- {
+ if (joypad1.down) {
theGame.MoveCursor('S');
repeatingS[0]=true;
timeHeldP1S=SDL_GetTicks();
timesRepeatedP1S=0;
}
- if (joypad1.left)
- {
+ if (joypad1.left) {
theGame.MoveCursor('W');
repeatingW[0]=true;
timeHeldP1W=SDL_GetTicks();
timesRepeatedP1W=0;
}
- if (joypad1.right)
- {
+ if (joypad1.right) {
theGame.MoveCursor('E');
repeatingE[0]=true;
timeHeldP1E=SDL_GetTicks();
timesRepeatedP1E=0;
}
- if (joypad1.but1)
- {
+ if (joypad1.but1) {
theGame.SwitchAtCursor();
}
- if (joypad1.but2)
- {
+ if (joypad1.but2) {
theGame.PushLine();
}
}
- else
- {
+ else {
joypad1.update();
- if (joypad1.up)
- {
+ if (joypad1.up) {
theGame2.MoveCursor('N');
repeatingN[1]=true;
timeHeldP2N=SDL_GetTicks();
timesRepeatedP2N=0;
}
- if (joypad1.down)
- {
+ if (joypad1.down) {
theGame2.MoveCursor('S');
repeatingS[1]=true;
timeHeldP2S=SDL_GetTicks();
timesRepeatedP2S=0;
}
- if (joypad1.left)
- {
+ if (joypad1.left) {
theGame2.MoveCursor('W');
repeatingW[1]=true;
timeHeldP2W=SDL_GetTicks();
timesRepeatedP2W=0;
}
- if (joypad1.right)
- {
+ if (joypad1.right) {
theGame2.MoveCursor('E');
repeatingE[1]=true;
timeHeldP2E=SDL_GetTicks();
timesRepeatedP2E=0;
}
- if (joypad1.but1)
- {
+ if (joypad1.but1) {
theGame2.SwitchAtCursor();
}
- if (joypad1.but2)
- {
+ if (joypad1.but2) {
theGame2.PushLine();
}
}
}
- if (joypad2.working && !theGame2.GetAIenabled())
- {
- if (!joyplay2)
- {
+ if (joypad2.working && !theGame2.GetAIenabled()) {
+ if (!joyplay2) {
joypad2.update();
- if (joypad2.up)
- {
+ if (joypad2.up) {
theGame.MoveCursor('N');
repeatingN[0]=true;
timeHeldP1N=SDL_GetTicks();
timesRepeatedP1N=0;
}
- if (joypad2.down)
- {
+ if (joypad2.down) {
theGame.MoveCursor('S');
repeatingS[0]=true;
timeHeldP1S=SDL_GetTicks();
timesRepeatedP1S=0;
}
- if (joypad2.left)
- {
+ if (joypad2.left) {
theGame.MoveCursor('W');
repeatingW[0]=true;
timeHeldP1W=SDL_GetTicks();
timesRepeatedP1W=0;
}
- if (joypad2.right)
- {
+ if (joypad2.right) {
theGame.MoveCursor('E');
repeatingE[0]=true;
timeHeldP1E=SDL_GetTicks();
timesRepeatedP1E=0;
}
- if (joypad2.but1)
- {
+ if (joypad2.but1) {
theGame.SwitchAtCursor();
}
- if (joypad2.but2)
- {
+ if (joypad2.but2) {
theGame.PushLine();
}
}
- else
- {
+ else {
joypad2.update();
- if (joypad2.up)
- {
+ if (joypad2.up) {
theGame2.MoveCursor('N');
repeatingN[1]=true;
timeHeldP2N=SDL_GetTicks();
timesRepeatedP2N=0;
}
- if (joypad2.down)
- {
+ if (joypad2.down) {
theGame2.MoveCursor('S');
repeatingS[1]=true;
timeHeldP2S=SDL_GetTicks();
timesRepeatedP2S=0;
}
- if (joypad2.left)
- {
+ if (joypad2.left) {
theGame2.MoveCursor('W');
repeatingW[1]=true;
timeHeldP2W=SDL_GetTicks();
timesRepeatedP2W=0;
}
- if (joypad2.right)
- {
+ if (joypad2.right) {
theGame2.MoveCursor('E');
repeatingE[1]=true;
timeHeldP2E=SDL_GetTicks();
timesRepeatedP2E=0;
}
- if (joypad2.but1)
- {
+ if (joypad2.but1) {
theGame2.SwitchAtCursor();
}
- if (joypad2.but2)
- {
+ if (joypad2.but2) {
theGame2.PushLine();
}
}
@@ -4035,62 +3551,50 @@ int runGame(int gametype, int level)
********************************************************************/
if ((mouseplay1)&&( ( (!editorMode)&&(!theGame.GetAIenabled()) ) ||(editorModeTest))) //player 1
- if ((mousex > 50)&&(mousey>100)&&(mousex<50+300)&&(mousey<100+600))
- {
+ 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))
- {
+ if ((yLine>10)&&(theGame.GetTowerHeight()<12)) {
yLine=10;
}
- if (((theGame.GetPixels()==50)||(theGame.GetPixels()==0)) && (yLine>11))
- {
+ if (((theGame.GetPixels()==50)||(theGame.GetPixels()==0)) && (yLine>11)) {
yLine=11;
}
- if (yLine<0)
- {
+ if (yLine<0) {
yLine=0;
}
- if (xLine<0)
- {
+ if (xLine<0) {
xLine=0;
}
- if (xLine>4)
- {
+ if (xLine>4) {
xLine=4;
}
theGame.MoveCursorTo(xLine,yLine);
}
if ((mouseplay2)&&(!editorMode)&&(!theGame2.GetAIenabled())) //player 2
- if ((mousex > xsize-500)&&(mousey>100)&&(mousex<xsize-500+300)&&(mousey<100+600))
- {
+ if ((mousex > xsize-500)&&(mousey>100)&&(mousex<xsize-500+300)&&(mousey<100+600)) {
int yLine, xLine;
yLine = ((100+600)-(mousey-100+theGame2.GetPixels()))/50;
xLine = (mousex-(xsize-500)+25)/50;
yLine-=2;
xLine-=1;
- if ((yLine>10)&&(theGame2.GetTowerHeight()<12))
- {
+ if ((yLine>10)&&(theGame2.GetTowerHeight()<12)) {
yLine=10;
}
- if (((theGame2.GetPixels()==50)||(theGame2.GetPixels()==0)) && (yLine>11))
- {
+ if (((theGame2.GetPixels()==50)||(theGame2.GetPixels()==0)) && (yLine>11)) {
yLine=11;
}
- if (yLine<0)
- {
+ if (yLine<0) {
yLine=0;
}
- if (xLine<0)
- {
+ if (xLine<0) {
xLine=0;
}
- if (xLine>4)
- {
+ if (xLine>4) {
xLine=4;
}
theGame2.MoveCursorTo(xLine,yLine);
@@ -4101,22 +3605,18 @@ int runGame(int gametype, int level)
********************************************************************/
// If the mouse button is released, make bMouseUp equal true
- if (!SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(1))
- {
+ if (!SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(1)) {
bMouseUp=true;
}
// If the mouse button 2 is released, make bMouseUp2 equal true
- if ((SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(3))!=SDL_BUTTON(3))
- {
+ if ((SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(3))!=SDL_BUTTON(3)) {
bMouseUp2=true;
}
- if ((!singlePuzzle)&&(!editorMode))
- {
+ if ((!singlePuzzle)&&(!editorMode)) {
//read mouse events
- if (SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(1) && bMouseUp)
- {
+ if (SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(1) && bMouseUp) {
bMouseUp = false;
DrawIMG(background, screen, 0, 0);
@@ -4126,13 +3626,11 @@ int runGame(int gametype, int level)
********************************************************************/
{
if (mouseplay1 && !theGame.GetAIenabled()) //player 1
- if ((mousex > 50)&&(mousey>100)&&(mousex<50+300)&&(mousey<100+600))
- {
+ 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<xsize-500+300)&&(mousey<100+600))
- {
+ if ((mousex > xsize-500)&&(mousey>100)&&(mousex<xsize-500+300)&&(mousey<100+600)) {
theGame2.SwitchAtCursor();
}
}
@@ -4140,17 +3638,15 @@ int runGame(int gametype, int level)
**************** Here ends mouse play *******************************
********************************************************************/
- if(stageButtonStatus != SBdontShow && (mousex > theGame.GetTopX()+cordNextButton.x)
+ if (stageButtonStatus != SBdontShow && (mousex > theGame.GetTopX()+cordNextButton.x)
&&(mousex < theGame.GetTopX()+cordNextButton.x+cordNextButton.xsize)
- &&(mousey > theGame.GetTopY()+cordNextButton.y)&&(mousey < theGame.GetTopY()+cordNextButton.y+cordNextButton.ysize))
- {
+ &&(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)
+ 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))
- {
+ &&(mousey > theGame.GetTopY()+cordRetryButton.y)&&(mousey < theGame.GetTopY()+cordRetryButton.y+cordRetryButton.ysize)) {
//Clicked the retry button
theGame.retryLevel(SDL_GetTicks());
}
@@ -4160,8 +3656,7 @@ int runGame(int gametype, int level)
}
//Mouse button 2:
- if ((SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(3))==SDL_BUTTON(3) && bMouseUp2)
- {
+ if ((SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(3))==SDL_BUTTON(3) && bMouseUp2) {
bMouseUp2=false; //The button is pressed
/********************************************************************
**************** Here comes mouse play ******************************
@@ -4184,35 +3679,28 @@ int runGame(int gametype, int level)
********************************************************************/
}
} //if !singlePuzzle
- else
- {
+ else {
}
} //if !bScreenBocked;
//Sees if music is stopped and if music is enabled
- if ((!NoSound)&&(!Mix_PlayingMusic())&&(MusicEnabled)&&(!bNearDeath))
- {
+ if ((!NoSound)&&(!Mix_PlayingMusic())&&(MusicEnabled)&&(!bNearDeath)) {
// then starts playing it.
Mix_VolumeMusic(MIX_MAX_VOLUME);
Mix_PlayMusic(bgMusic, -1); //music loop
}
- if(bNearDeath!=bNearDeathPrev)
- {
- if(bNearDeath)
- {
- if(!NoSound &&(MusicEnabled))
- {
+ if (bNearDeath!=bNearDeathPrev) {
+ if (bNearDeath) {
+ if (!NoSound &&(MusicEnabled)) {
Mix_VolumeMusic(MIX_MAX_VOLUME);
Mix_PlayMusic(highbeatMusic, 1);
}
}
- else
- {
- if(!NoSound &&(MusicEnabled))
- {
+ else {
+ if (!NoSound &&(MusicEnabled)) {
Mix_VolumeMusic(MIX_MAX_VOLUME);
Mix_PlayMusic(bgMusic, -1);
}
@@ -4232,32 +3720,25 @@ int runGame(int gametype, int level)
#if NETWORK
if (!networkPlay)
#endif
- if (twoPlayers)
- {
- if ((theGame.isGameOver()) && (theGame2.isGameOver()))
- {
- if (theGame.GetScore()+theGame.GetHandicap()>theGame2.GetScore()+theGame2.GetHandicap())
- {
+ if (twoPlayers) {
+ if ((theGame.isGameOver()) && (theGame2.isGameOver())) {
+ if (theGame.GetScore()+theGame.GetHandicap()>theGame2.GetScore()+theGame2.GetHandicap()) {
theGame.setPlayerWon();
}
- else if (theGame.GetScore()+theGame.GetHandicap()<theGame2.GetScore()+theGame2.GetHandicap())
- {
+ else if (theGame.GetScore()+theGame.GetHandicap()<theGame2.GetScore()+theGame2.GetHandicap()) {
theGame2.setPlayerWon();
}
- else
- {
+ else {
theGame.setDraw();
theGame2.setDraw();
}
//twoPlayers = false;
}
- if ((theGame.isGameOver()) && (!theGame2.isGameOver()))
- {
+ if ((theGame.isGameOver()) && (!theGame2.isGameOver())) {
theGame2.setPlayerWon();
//twoPlayers = false;
}
- if ((!theGame.isGameOver()) && (theGame2.isGameOver()))
- {
+ if ((!theGame.isGameOver()) && (theGame2.isGameOver())) {
theGame.setPlayerWon();
//twoPlayers = false;
}
diff --git a/source/code/menudef.cpp b/source/code/menudef.cpp
index fc4afaf..454ee88 100644
--- a/source/code/menudef.cpp
+++ b/source/code/menudef.cpp
@@ -32,14 +32,12 @@ using namespace std;
extern int verboseLevel;
//Menu
-static void PrintHi(Button* b)
-{
+static void PrintHi(Button* b) {
cout << "Hi" <<endl;
}
//Stores the controls
-struct control
-{
+struct control {
SDLKey up;
SDLKey down;
SDLKey left;
@@ -48,50 +46,43 @@ struct control
SDLKey push;
};
-bool OpenDialogbox(int x, int y, char *name);
+bool OpenDialogbox(int x, int y, char* name);
void OpenScoresDisplay();
extern control keySettings[3];
//Function to return the name of a key, to be displayed...
-static string getKeyName(SDLKey key)
-{
+static string getKeyName(SDLKey key) {
string keyname(SDL_GetKeyName(key));
- if(verboseLevel) {
+ if (verboseLevel) {
cout << key << " translated to " << keyname << endl;
}
return keyname;
}
-class Button_changekey : public Button
-{
+class Button_changekey : public Button {
private:
- SDLKey *m_key2change;
+ SDLKey* m_key2change;
string m_keyname;
public:
- Button_changekey(SDLKey *key, string keyname);
+ Button_changekey(SDLKey* key, string keyname);
void doAction();
};
-Button_changekey::Button_changekey(SDLKey* key, string keyname)
-{
+Button_changekey::Button_changekey(SDLKey* key, string keyname) {
m_key2change = key;
m_keyname = keyname;
setLabel(m_keyname+" : "+getKeyName(*m_key2change));
}
-void Button_changekey::doAction()
-{
+void Button_changekey::doAction() {
SDL_Event event;
bool finnish = false;
- while (!finnish)
- {
+ while (!finnish) {
SDL_Delay(10);
- while ( SDL_PollEvent(&event) )
- {
- if (event.type == SDL_KEYDOWN)
- {
+ while ( SDL_PollEvent(&event) ) {
+ if (event.type == SDL_KEYDOWN) {
if (event.key.keysym.sym != SDLK_ESCAPE) {
*m_key2change = event.key.keysym.sym;
}
@@ -102,98 +93,81 @@ void Button_changekey::doAction()
setLabel(m_keyname+" : "+getKeyName(*m_key2change));
}
-void InitMenues()
-{
+void InitMenues() {
standardButton.setSurfaces(menuMarked,menuUnmarked);
standardButton.thefont = nf_scoreboard_font;
}
void runGame(int gametype,int level);
-static void runSinglePlayerEndless(Button* b)
-{
+static void runSinglePlayerEndless(Button* b) {
runGame(0,0);
}
-static void runSinglePlayerTimeTrial(Button* b)
-{
+static void runSinglePlayerTimeTrial(Button* b) {
runGame(1,0);
}
-static void runStageClear(Button* b)
-{
+static void runStageClear(Button* b) {
runGame(2,0);
}
-static void runSinglePlayerPuzzle(Button* b)
-{
+static void runSinglePlayerPuzzle(Button* b) {
runGame(3,0);
}
-static void runSinglePlayerVs(Button* b)
-{
+static void runSinglePlayerVs(Button* b) {
runGame(4,b->iGeneric1);
}
-static void runTwoPlayerTimeTrial(Button* b)
-{
+static void runTwoPlayerTimeTrial(Button* b) {
runGame(10,0);
}
-static void runTwoPlayerVs(Button* b)
-{
+static void runTwoPlayerVs(Button* b) {
runGame(11,0);
}
-static void runHostGame(Button* b)
-{
+static void runHostGame(Button* b) {
runGame(12,0);
}
-static void runJoinGame(Button* b)
-{
+static void runJoinGame(Button* b) {
runGame(13,0);
}
-static void buttonActionMusic(Button* b)
-{
+static void buttonActionMusic(Button* b) {
MusicEnabled = !MusicEnabled;
b->setLabel(MusicEnabled? "Music: On" : "Music: Off");
}
-static void buttonActionSound(Button* b)
-{
+static void buttonActionSound(Button* b) {
SoundEnabled = !SoundEnabled;
b->setLabel(SoundEnabled? _("Sound: On") : _("Sound: Off") );
}
-static void buttonActionFullscreen(Button* b)
-{
+static void buttonActionFullscreen(Button* b) {
bFullscreen = !bFullscreen;
b->setLabel(bFullscreen? _("Fullscreen: On") : _("Fullscreen: Off") );
ResetFullscreen();
}
-static void buttonActionPlayer1Name(Button *b)
-{
+static void buttonActionPlayer1Name(Button* b) {
if (OpenDialogbox(200,100,player1name)) {
return; //must save if true
}
}
-static void buttonActionPlayer2Name(Button *b)
-{
+static void buttonActionPlayer2Name(Button* b) {
if (OpenDialogbox(200,100,player2name)) {
return; //must save if true
}
}
-static void buttonActionPortChange(Button *b)
-{
+static void buttonActionPortChange(Button* b) {
char port[30];
snprintf(port,sizeof(port),"%i",Config::getInstance()->getInt("portv4") );
- if (OpenDialogbox(200,100,port) && atoi(port))
- {
+ if (OpenDialogbox(200,100,port) && atoi(port)) {
Config::getInstance()->setInt("portv4",atoi(port));
boost::format f(_("Port: %1%") );
f % port;
@@ -201,12 +175,10 @@ static void buttonActionPortChange(Button *b)
}
}
-static void buttonActionIpChange(Button *b)
-{
+static void buttonActionIpChange(Button* b) {
char ip[30];
snprintf(ip,sizeof(ip),"%s",Config::getInstance()->getString("address0").c_str() );
- if (OpenDialogbox(200,100,ip))
- {
+ if (OpenDialogbox(200,100,ip)) {
Config::getInstance()->setString("address0",ip);
boost::format f(_("Address: %1%") );
f % ip;
@@ -214,13 +186,11 @@ static void buttonActionIpChange(Button *b)
}
}
-static void buttonActionHighscores(Button *b)
-{
+static void buttonActionHighscores(Button* b) {
OpenScoresDisplay();
}
-static void ChangeKeysMenu(long playernumber)
-{
+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") );
@@ -237,18 +207,15 @@ static void ChangeKeysMenu(long playernumber)
km.run();
}
-static void ChangeKeysMenu1(Button *b)
-{
+static void ChangeKeysMenu1(Button* b) {
ChangeKeysMenu(0);
}
-static void ChangeKeysMenu2(Button *b)
-{
+static void ChangeKeysMenu2(Button* b) {
ChangeKeysMenu(2);
}
-static void ConfigureMenu(Button *b)
-{
+static void ConfigureMenu(Button* b) {
Menu cm(&screen,_("Configuration"),true);
Button bMusic,bSound,buttonFullscreen,bPlayer1Name,bPlayer2Name;
Button bPlayer1Keys, bPlayer2Keys;
@@ -276,8 +243,7 @@ static void ConfigureMenu(Button *b)
cm.run();
}
-static void SinglePlayerVsMenu(Button *b)
-{
+static void SinglePlayerVsMenu(Button* b) {
Menu spvs(&screen,_("Single player VS"),true);
Button d1,d2,d3,d4,d5,d6,d7;
d1.setAction(runSinglePlayerVs);
@@ -318,8 +284,7 @@ static void SinglePlayerVsMenu(Button *b)
spvs.run();
}
-static void MultiplayerMenu(Button *b)
-{
+static void MultiplayerMenu(Button* b) {
Menu mm(&screen,_("Multiplayer"),true);
Button bTT, bVs, bNet;
bTT.setLabel(_("Two player - time trial"));
@@ -331,8 +296,7 @@ static void MultiplayerMenu(Button *b)
mm.run();
}
-void MainMenu()
-{
+void MainMenu() {
InitMenues();
Menu m(&screen,_("Block Attack - Rise of the blocks"),false);
Button bHi,bTimetrial1, bStageClear, bPuzzle, bVs1, bMulti, bConfigure,bHighscore;
diff --git a/source/code/puzzlehandler.cpp b/source/code/puzzlehandler.cpp
index 9275adf..b6ca3f4 100644
--- a/source/code/puzzlehandler.cpp
+++ b/source/code/puzzlehandler.cpp
@@ -45,20 +45,17 @@ void PuzzleSetSavePath(const std::string& filepath) {
}
void PuzzleSetClear(int Level) {
- if(puzzleCleared[Level]==false) {
+ if (puzzleCleared[Level]==false) {
Stats::getInstance()->addOne("puzzlesSolved");
}
puzzleCleared[Level] = true;
std::ofstream outfile;
outfile.open(puzzleSavePath.c_str(), ios::binary |ios::trunc);
- if (!outfile)
- {
+ if (!outfile) {
std::cerr << "Error writing to file: " << puzzleSavePath << endl;
}
- else
- {
- for (int i=0; i<nrOfPuzzles; i++)
- {
+ else {
+ for (int i=0; i<nrOfPuzzles; i++) {
bool tempBool = puzzleCleared[i];
outfile.write(reinterpret_cast<char*>(&tempBool), sizeof(bool));
}
@@ -67,10 +64,8 @@ void PuzzleSetClear(int Level) {
}
/*Loads all the puzzle levels*/
-int LoadPuzzleStages( )
-{
- if (!PHYSFS_exists(((std::string)("puzzles/"+puzzleName)).c_str()))
- {
+int LoadPuzzleStages( ) {
+ if (!PHYSFS_exists(((std::string)("puzzles/"+puzzleName)).c_str())) {
std::cerr << "Warning: File not in blockattack.data: " << ("puzzles/"+puzzleName) << endl;
return -1; //file doesn't exist
}
@@ -80,28 +75,23 @@ int LoadPuzzleStages( )
if (nrOfPuzzles>maxNrOfPuzzleStages) {
nrOfPuzzles=maxNrOfPuzzleStages;
}
- for (int k=0; (k<nrOfPuzzles) /*&&(!inFile.eof())*/ ; k++)
- {
+ for (int k=0; (k<nrOfPuzzles) /*&&(!inFile.eof())*/ ; k++) {
inFile >> nrOfMovesAllowed[k];
for (int i=11; i>=0; i--)
- for (int j=0; j<6; j++)
- {
+ for (int j=0; j<6; j++) {
inFile >> puzzleLevels[k][j][i];
}
}
bool tempBool;
std::ifstream puzzleFile(puzzleSavePath.c_str(), std::ios::binary);
- if (puzzleFile)
- {
- for (int i=0; (i<nrOfPuzzles)&&(!puzzleFile.eof()); i++)
- {
+ if (puzzleFile) {
+ for (int i=0; (i<nrOfPuzzles)&&(!puzzleFile.eof()); i++) {
puzzleFile.read(reinterpret_cast<char*>(&tempBool),sizeof(bool));
puzzleCleared[i] = tempBool;
}
puzzleFile.close();
}
- else
- {
+ else {
tempBool = false;
for (int i=0; i<nrOfPuzzles; i++) {
puzzleCleared[i] = tempBool;
diff --git a/source/code/stats.cpp b/source/code/stats.cpp
index 627a805..7c00c27 100644
--- a/source/code/stats.cpp
+++ b/source/code/stats.cpp
@@ -28,22 +28,18 @@ using namespace std;
Stats* Stats::instance = nullptr;
-Stats::Stats()
-{
+Stats::Stats() {
statMap.clear();
load();
}
-void Stats::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())
- {
+ 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.
@@ -53,36 +49,29 @@ void Stats::load()
}
}
-Stats* Stats::getInstance()
-{
- if(Stats::instance==nullptr)
- {
+Stats* Stats::getInstance() {
+ if (Stats::instance==nullptr) {
Stats::instance = new Stats();
}
return Stats::instance;
}
-void Stats::save()
-{
+void Stats::save() {
string filename = getPathToSaveFiles()+"/statsFile";
ofstream outFile(filename.c_str(),ios::trunc);
- if(outFile)
- {
+ if (outFile) {
//outFile << statMap.size() << endl;
map<string,unsigned int>::iterator iter;
- for(iter = statMap.begin(); iter != statMap.end(); iter++)
- {
+ for (iter = statMap.begin(); iter != statMap.end(); iter++) {
outFile << iter->first << " " << iter->second << endl;
}
}
}
-unsigned int Stats::getNumberOf(const string &statName)
-{
- if(exists(statName))
- {
+unsigned int Stats::getNumberOf(const string& statName) {
+ if (exists(statName)) {
return statMap[statName];
}
else {
@@ -90,21 +79,17 @@ unsigned int Stats::getNumberOf(const string &statName)
}
}
-void Stats::addOne(const string &statName)
-{
+void Stats::addOne(const string& statName) {
map<string,unsigned int>::iterator iter = statMap.find(statName);
- if(iter == statMap.end())
- {
+ if (iter == statMap.end()) {
statMap[statName] = 1;
}
- else
- {
+ else {
iter->second++;
}
}
-bool Stats::exists(const string &statName)
-{
+bool Stats::exists(const string& statName) {
//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/ttfont.cpp b/source/code/ttfont.cpp
index 82ec757..08b0b4c 100644
--- a/source/code/ttfont.cpp
+++ b/source/code/ttfont.cpp
@@ -27,35 +27,33 @@ http://blockattack.sf.net
//#define CONVERTA(n) tmp = SDL_DisplayFormatAlpha(n); SDL_FreeSurface(n); n = tmp
-TTFont::TTFont()
-{
+TTFont::TTFont() {
font = nullptr;
actualInstance = false;
}
int TTFont::count = 0;
-TTFont::TTFont(TTF_Font *f)
-{
- if(!(TTF_WasInit()))
- {
+TTFont::TTFont(TTF_Font *f) {
+ if (!(TTF_WasInit())) {
//Init TTF for the first time
TTF_Init();
}
- if(f == nullptr)
+ if (f == nullptr) {
cout << "Font was null!" << endl;
+ }
actualInstance = false; //We have not yet copied to final location
font = f;
}
-TTFont::~TTFont()
-{
- if(!actualInstance)
+TTFont::~TTFont() {
+ if (!actualInstance) {
return;
+ }
cout << "Closing a font" << endl;
@@ -63,49 +61,43 @@ TTFont::~TTFont()
font = nullptr;
count--;
- if(count==0)
+ if (count==0) {
TTF_Quit();
+ }
}
//Copy constructor, you cannot copy an actual instance
-TTFont::TTFont(const TTFont &t)
-{
- if(t.font == nullptr || t.actualInstance)
- {
+TTFont::TTFont(const TTFont &t) {
+ if (t.font == nullptr || t.actualInstance) {
font = nullptr;
actualInstance = false;
}
- else
- {
+ else {
font = t.font;
actualInstance = true;
count++;
}
}
-int TTFont::getTextHeight()
-{
+int TTFont::getTextHeight() {
return TTF_FontHeight(font);
}
-int TTFont::getTextWidth(string text)
-{
+int TTFont::getTextWidth(string text) {
int width = 0;
- if(TTF_SizeText(font,text.c_str(),&width,nullptr)!=0)
+ if (TTF_SizeText(font,text.c_str(),&width,nullptr)!=0) {
cout << "Failed to get text width!" << endl;
+ }
return width;
}
-void TTFont::writeText(string text, SDL_Surface *target, int x, int y)
-{
+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)))
- {
+ if (!(text_surface=TTF_RenderText_Solid(font,text.c_str(), color))) {
cout << "Error writing text: " << TTF_GetError() << endl;
}
- else
- {
+ else {
SDL_Rect dest;
dest.x = x;
dest.y = y;