Ejemplo n.º 1
0
void Render() 
{ 
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();

	SetCamera();
	DrawBall(GL_FALSE);		
	DrawLifes();
	DrawScores();
	DrawCubes();
	DrawRoom();

	projection.Init(ROOM_HALF_LENGTH - 0.01, X, Y, -ROOM_LENGTH*10);
	glPushMatrix();
		glMultMatrixf((GLfloat*)projection.shadowMat);
		DrawBall(GL_TRUE);
	glPopMatrix();

	DrawReflector();
	RoomCollision();
	CubesCollision();

	glClearColor(0.3, 0.3, 0.3, 0);
    glutSwapBuffers();
}
Ejemplo n.º 2
0
/**
 * Display callback. Draws the curves, points, and object
 */
void Display(void) {
	
	// clear buffers
  glClear(GL_COLOR_BUFFER_BIT);
  
	DrawGround(); // draw the ground
	
	// option to hide the controls
	if (!hide) {

		DrawControlPoints(); // draw all control points

		DrawAnimationPoints(); // draw the path for animation
	}

	// which scene
	if (scene1) {
		
		DrawBall(); // draw the ball
	} else {

		DrawLamp(); // draw the pixar lamp
	}

  glutSwapBuffers();
}
Ejemplo n.º 3
0
/*!****************************************************************************
 @Function		RenderScene
 @Return		bool		true if no error occured
 @Description	Main rendering loop function of the program. The shell will
				call this function every frame.
				eglSwapBuffers() will be performed by PVRShell automatically.
				PVRShell will also manage important OS events.
				Will also manage relevent OS events. The user has access to
				these events through an abstraction layer provided by PVRShell.
******************************************************************************/
bool OGLES2Glass::RenderScene()
{
	if (PVRShellIsKeyPressed(PVRShellKeyNameLEFT))	m_iEffect -= 1;
	if (PVRShellIsKeyPressed(PVRShellKeyNameRIGHT))	m_iEffect += 1;
	m_iEffect = (m_iEffect + g_iNumEffects) % g_iNumEffects;

	UpdateScene();

	DrawIntoParaboloids(PVRTVec3(0, 0, 0));

	// Clear the color and depth buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Draw the ball
	DrawBall();

	// Draw the balloons
	DrawBalloons(&m_DefaultProgram, m_mProjection, m_mView, m_mModels, 2);

	// Draw the skybox
	DrawSkybox();

	// Displays the demo name using the tools. For a detailed explanation, see the training course IntroducingPVRTools
	m_Print3D.DisplayDefaultTitle("Glass", g_aszEffectNames[m_iEffect], ePVRTPrint3DSDKLogo);
	m_Print3D.Flush();

	return true;
}
Ejemplo n.º 4
0
void TriangleMan::Render()
{
	//DrawTriMan();
	DrawBall();
	//DrawRegions();
	//mRenderComp->render();
}
Ejemplo n.º 5
0
DrawBallz(ball * ballz, SDL_Surface* screen){

   ball * head = ballz;

   while (head){
      DrawBall(head, screen);
      head = head->next;
   }
}
Ejemplo n.º 6
0
static void ProcessGameOver(struct BALL *Ball, struct PADDLE *Paddle)
{
	char OutBuf[255];
	
	snprintf(OutBuf, sizeof OutBuf, "GAME OVER! Score is %d. Hit ESC to exit or space to play again.", Score);

	Lives = 0;
	
	DrawStats();
	
	Lives = 3;
	Score = 0;
	
	DrawMessage(OutBuf);
	
	cbreak();
	
AskAgain:
	switch (getch())
	{
		case 27: /*27 is ESC.*/
			endwin();
			exit(0);
			break;
		case ' ':
			break;
		default:
			goto AskAgain;
	}
	
	halfdelay(1);
	DeleteMessage();
	
	DeleteBall(Ball);
	DeletePaddle(Paddle);
	DeleteAllBricks();
	DeleteAllCharms();
	SetLevel(1); /*Set back to the default level again.*/
	
	ResetPaddle(Paddle);
	ResetBricks();
	
	DrawPaddle(Paddle);
	DrawAllBricks();
	
	DrawStats();
	
	/*Assume they want to play again.*/
	WaitForUserLaunch();
	ResetBall(Ball);
	DrawBall(Ball);
	DrawAllBricks(); /*Redraw to fix WaitForUserLaunch() goofing.*/

}
Ejemplo n.º 7
0
/**
 * @brief RBall::paintGL
 */
void RBall::paintGL(){

    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );//清楚屏幕和深度缓存。

    glLoadIdentity();//重置当前的模型观察矩阵

  // glTranslatef( 0, 0.0, -1.0 );// move current point from original point(0,0,0)
    //glRotatef( 0, 0.0, 1.0, 0.0 );

for(auto ball:VB)
   DrawBall(ball);
}
Ejemplo n.º 8
0
void CBoxManMain::DrawGameArea(CDC* pDC)
{
	int i,j,x,y;
	for (i=0;i<M_TAB_HEIGHT;i++)
	{
		for (j=0;j<M_TAB_WIDTH;j++)
		{
			x=j*BLOCK_WIDTH;
			y=i*BLOCK_HEIGHT;
			switch (m_cMap[i][j])
			{
			case MAP_BACKGROUP:
				DrawBackGroup(x,y,pDC);
				break;
			case MAP_WHITEWALL:
				DrawWhiteWall(x,y,pDC);
				break;
			case MAP_BLUEWALL:
				DrawBlueWall(x,y,pDC);
				break;
			case MAP_BALL:
				DrawBall(x,y,pDC);
				break;
			case MAP_YELLOWBOX:
				DrawYellowBox(x,y,pDC);
				break;
			case MAP_REDBOX:
				DrawRedBox(x,y,pDC);
				break;
			case MAP_MANWALL:
				DrawManWall(x,y,pDC);
				break;
			case MAP_MANBALL:
				DrawManBall(x,y,pDC);
				break;
			}
			
		}
	}
	COLORREF clrOldText=pDC->GetTextColor();
	int BkOldModle=pDC->GetBkMode();
	pDC->SetTextColor(RGB(102,0,0));
	pDC->SetBkMode(TRANSPARENT);
	CString sTmp;
	sTmp.Format("当前关数:%d",m_iMissionNum);
	pDC->TextOut(50,382,sTmp);
	pDC->SetTextColor(clrOldText);
	pDC->SetBkMode(BkOldModle);
}
Ejemplo n.º 9
0
void BreakOut::Draw(game_info* gi)
{
	engine.tetris.DrawBoard(gi);

	if (gi->state == STATE_BREAKOUT_TRANS)
	{
		engine.tetris.DrawPiece(gi, (0.5) * (double)gi->pos, gi->fine);
	}
	else
	{
		engine.tetris.DrawPiece(gi, gi->fine, 0);
	}

	DrawBall(gi);
}
Ejemplo n.º 10
0
int ball_thread(int size, Ball *b) {
	int inPlay = 1;
	// Loop until game ends or until ball is no longer in play.
	while (_gameState != GAME_OVER && inPlay) {
		if (_gameState == GAME_PAUSED) {
			sceKernelWaitSema(_pauseSem, 1, 0); // Block on semaphore
			sceKernelSignalSema(_pauseSem, 1); // Once awake, signal semaphore so next in line wakes up 
		}
		inPlay = DrawBall(b);
		sceKernelDelayThread(10000);
	}
	_activeBalls[b->ballId] = 0; // Remove this ball from array of active balls
	sceKernelExitThread(0);
	return 0;
}
void ArkanoidRemakeSdl::Frame()
{
  if (mSdlApp.ExistsSurface(mSnowfallSurf))
  {
    // Scroll the background
    mBkgndScroll += 20.0*(mCurrTime-mPrevTime);
    if (mBkgndScroll>0) mBkgndScroll=-mSdlApp.GetSurfHeight(mSnowfallSurf);
  }
  DrawBackground();
  DrawPlayArea();
  DrawBlocks();
  DrawBall();
  DrawShip();
  DrawBonus();
  DrawText();
  mSdlApp.UpdateWindow();
}
Ejemplo n.º 12
0
 void World::Draw()
 {
     if(m_state == IDLE)
     {
         if(m_texBanner != nullptr && m_texBanner->GetTexId() != 0)
         {
             DrawBanner();
         }
     }
     else if(m_state == PLAYING)
     {
         DrawPlayField();
         DrawScore();
         DrawBall();
         DrawPlayer1();
         DrawPlayer2();
     } 
     else if(m_state == GAMEOVER) 
     {
         glClear(GL_COLOR_BUFFER_BIT);
         DrawPlayField();
         DrawScore();
     }
 }
Ejemplo n.º 13
0
void View::Draw(const Model &model) const {
  ofPushMatrix();
  SetupViewpoint();
  ofBackground(ofColor::white);
  //CHASERS-------------------
  for (int i = 0; i < model.nChasers; i++){
    model.topChaser[i]->draw();
    model.botChaser[i]->draw();
    model.rightChaser[i]->draw();
    model.leftChaser[i]->draw();
  }
  DrawGravity(model);
  DrawPlayers(model);
  
  ofColor ball_color = model.last_hit_player == 1 ? color_p1 :
      model.last_hit_player == 2 ? color_p2 : ofColor::white;
  DrawBallTrail(model, model.ball_trail, ball_color);
  DrawStrikeIndicator(model);
  DrawBall(model.ball, ball_color);
  
  for (float x=-10; x<GRID_W; x+=(1.0/6.0)) {
    for (float y=-5; y<GRID_H; y+=(1.0/6.0)) {
      if (ofDist(model.ball->GetPosition().x, model.ball->GetPosition().y, x, y)<0.3) {
        if (ball_color==color_p1){
          ofSetColor(color_p1.r,ofRandom(10,60),color_p1.b, 100);
        }else if(ball_color==color_p2){
          ofSetColor(ofRandom(10,60),color_p2.g,color_p2.b, 100);
        }else{
          ofSetColor(ofRandom(200,250),ofRandom(200,250),ofRandom(200,250), 200);
        }
        ofCircle(x, y, 0.1);
      }
      else if (ofDist(model.player1_top->GetPosition().x, model.player1_top->GetPosition().y, x, y)<0.4 ||
               ofDist(model.player1_bottom->GetPosition().x, model.player1_bottom->GetPosition().y, x, y)<0.4) {
        ofSetColor(color_p1.r,ofRandom(10,60),color_p1.b, 155);
        ofCircle(x, y, 0.12);
      }
      else if (ofDist(model.player2_top->GetPosition().x, model.player2_top->GetPosition().y, x, y)<0.4 ||
               ofDist(model.player2_bottom->GetPosition().x, model.player2_bottom->GetPosition().y, x, y)<0.4) {
        ofSetColor(ofRandom(10,60),color_p2.g,color_p2.b, 155);
        ofCircle(x, y, 0.12);
      }
      else if (ofDist(model.ball->GetPosition().x, model.ball->GetPosition().y, x, y)< model.p1glowMax){
        ofNoFill();
        ofSetColor(color_p1.r,ofRandom(10,60),color_p1.b, 135);
        ofCircle(x, y, 0.12);
        ofFill();
      }
      else if (ofDist(model.ball->GetPosition().x, model.ball->GetPosition().y, x, y)< model.p2glowMax){
        ofNoFill();
        ofSetColor(ofRandom(10,60),color_p2.g,color_p2.b, 135);
        ofCircle(x, y, 0.12);
        ofFill();
      }
      
      
      else {
        ofFill();
        ofSetColor(ofRandom(0,10),ofRandom(0,10),ofRandom(10,20), 20);
        ofTriangle(x, y+0.7, x-0.6, y-0.6, x+0.6, y-0.6);

      }

    }



    
  }
  DrawCourt(model);
  DrawScore(model);
  if (model.show_winning_state) {
    DrawTriangles(model);
  }
  ofPopMatrix();

  //DrawFramesPerSecond(model);
}
Ejemplo n.º 14
0
inline void
update(GameState *state)
{
    localPersist vector2 ballMoveVector = {0,0};
    clearBackgroundToColor(Vector3(0,0,0));
    DrawCenterLine();
    DrawPlayerPaddle(&state->playerPaddle);
    DrawComputerPaddle(&state->computerPaddle);
    //TODO:Handle Ball Math
    if(state->gameInprogress)
    {
        if(ballMoveVector == Vector2(0,0))
        {
            ballMoveVector.x = -state->ball.moveSpeed;
        }
        if((state->ball.locationOnScreen.x <= 30
            && state->ball.locationOnScreen.x >= 20)
            || (state->ball.locationOnScreen.x >= (screenWidth-30)
            && state->ball.locationOnScreen.x <= (screenWidth-20)))
        {
            r32 playerPaddleTop= \
                state->playerPaddle.originLocationHeight + (state->playerPaddle.height/2.0f);
            r32 playerPaddleBottom= \
                state->playerPaddle.originLocationHeight - (state->playerPaddle.height/2.0f);
            r32 computerPaddleTop= \
                state->computerPaddle.originLocationHeight + (state->computerPaddle.height/2.0f);
            r32 computerPaddleBottom= \
                state->computerPaddle.originLocationHeight - (state->computerPaddle.height/2.0f);
            if((state->ball.locationOnScreen.y <= playerPaddleTop
               && state->ball.locationOnScreen.y >= playerPaddleBottom)
               || (state->ball.locationOnScreen.y <= computerPaddleTop
               && state->ball.locationOnScreen.y >= computerPaddleBottom))
            {
                    ballMoveVector = -ballMoveVector;
            }
        }

        state->ball.locationOnScreen += ballMoveVector; // moveball

        if(state->ball.locationOnScreen.x <= 0)
        {
            state->gameScore.y += 1;
            ResetBallPostition(&state->ball);
            if(state->gameScore.y == 10)
            {
                //TODO: Game over section (player Loses)
                state->gameInprogress=false;
                ballMoveVector = Vector2(0,0);
            }
        }
        else if(state->ball.locationOnScreen.y >= screenWidth)
        {
            state->gameScore.x += 1;
            ResetBallPostition(&state->ball);
            if(state->gameScore.x == 10)
            {
                //TODO: Game over section (player wins)
                state->gameInprogress=false;
                ballMoveVector = Vector2(0,0);
            }
        }
    }
    DrawBall(&state->ball);

}
Ejemplo n.º 15
0
int main()
{
	Circle[1] = BuffPos.y - 25;
	Circle[2] = BuffPos.y + 25;
	Circle[3] = Circle[1];
	Circle[4] = Circle[2];
	/*gateRadius[1] = 1 * sfw::getDeltaTime();
	gateRadius[2] = 1 * sfw::getDeltaTime();
	gateRadius[3] = 1 * sfw::getDeltaTime();
	gateRadius[4] = 1 * sfw::getDeltaTime();*/
	BuffDurations buffDurations = {};
	Position LeftPlayer = {};
	LeftPlayer.y = screenHeight / 2;
	LeftPlayer.x = 50;
	Position RightPlayer = {};
	RightPlayer.y = screenHeight / 2;
	RightPlayer.x = screenWidth - 100;
	CirclePos.x = 700;
	CirclePos.y = 500;
	Point BallPos;
	BallPos.x = screenWidth / 2;
	BallPos.y = screenHeight / 2;

	bool countingUP = false;
	bool approachingCenter = true;

	sfw::initContext(screenWidth, screenHeight, "Window");

	int radius;
	radius = Radius;
	int Timer = radius;

	float circleX = CirclePos.x;
	float circleY = CirclePos.y;



	//const int resetTimer = 5000;
	//400
	//600
	
	bool isIncreasing = false;
	
	bool buffDeleted = false;
	int pickRandomBuff;
	int numberOfBuffs = 3;
	srand(time(NULL));
	pickRandomBuff = rand() % numberOfBuffs;
	float buffMovementTimer = 500;
	buffMovementTimer += sfw::getDeltaTime();
	float timer = 1 * sfw::getDeltaTime();
	bool tuggingLeft = false;
	bool buffMovement = false;
	bool isKeyPressed = false;
	float tugOWar = 25 * sfw::getDeltaTime();
	float scale = 1;
	int InitialballDirection = rand() % 2;
	bool BallHasSpawned = false;
	static int bounce = 0;


	 float tempBallPos = BallPos.x;
		
	while (sfw::stepContext())
	{
		Player1Score = 3;
		std::cout << buffDurations.speedBoostDuration << "\n";
		LeftPowerUpLines();
		RightPowerUpLines();
		DrawRectangle(LeftPlayer.x, LeftPlayer.y, paddleWidth, PaddleHeight); //Left Paddle
		DrawRectangle(RightPlayer.x, RightPlayer.y, paddleWidth, PaddleHeight);//Right Paddle
		DrawPlayerScores(Player1Score, Player2Score);
		sfw::drawLine(boundingBoxLeft, 0, boundingBoxLeft, screenHeight);//boundLeft
		sfw::drawLine(boundingBoxRight, 0, boundingBoxRight, screenHeight);//boundRight
		DrawBall(BallPos.x, BallPos.y); // Pong Ball
		if (BallPos.x + ballRadius > screenWidth)
		{
			//BallPos.x -= 200 * sfw::getDeltaTime();
			collidedRight = true;
		}
		if (BallPos.x - ballRadius < 0)
		{
			collidedLeft = true;
		}
		if (BallPos.y + ballRadius > screenHeight)
		{
			collidedBottom = true;
		}
		if (BallPos.y - ballRadius < 0)
		{
			collidedTop = true;
		}
		if (collidedBottom == true)
		{
			BallPos.y -= 25;
		}
		if (collidedTop == true)
		{
			BallPos.y += 25;
		}
		
		switch (InitialballDirection)
		{
		case 0:
			BallPos.x += 150 * sfw::getDeltaTime();
			/*if (collidedRight == true)
			{
				BallPos.x -= 200 * sfw::getDeltaTime();
				collidedRight = false;
			}*/
			break;
		case 1:
			BallPos.x -= 150 * sfw::getDeltaTime();
			/*if (collidedLeft == true)
			{
				BallPos.x += 200 * sfw::getDeltaTime();
				collidedLeft = false;
			}*/
			break;
		}
		switch (InitialballDirection)
		{
		case 0:
			BallPos.y += 150 * sfw::getDeltaTime();
			break;
		case 1:
			BallPos.y -= 150 * sfw::getDeltaTime();
			break;
		}
		
		
		
		if (BallPos.x + ballRadius < boundingBoxRight && BallPos.x - ballRadius > boundingBoxLeft)
		{
			if (collidedLeft == true)
			{
				BallPos.x -= 250 * sfw::getDeltaTime();
				BallPos.x += 200 * sfw::getDeltaTime();
				collidedRight = false;
			}
			if (collidedRight == true)
			{
				BallPos.x -= 100 * sfw::getDeltaTime();
				collidedLeft = false;
			}
		}

		if (collidedTop == true)
		{
			BallPos.y += 200 * sfw::getDeltaTime();
			BallPos.y -= 100 * sfw::getDeltaTime();
		}
		if (collidedBottom == true)
		{
			BallPos.y -= 200 * sfw::getDeltaTime();
		}

		//if (BallPos.x + ballRadius >= screenWidth)
		//{
		//	collidedRight = true;
		//	//BallPos.x = -(BallPos.x * 2);

		//}
		

		if (buffOnScreen == true)
		{
			Player1HasBuff = true;
			if (Player1HasBuff == true)
			{
				//pickRandomBuff = 1;
				if (pickRandomBuff == 0)
				{
					if (!(RightPlayer.x + paddleWidth > screenWidth))
					{
						RightPlayer.x += 100 * sfw::getDeltaTime();
						RightPlayer.y += 100 * sfw::getDeltaTime();
					}
					if (!(RightPlayer.y + PaddleHeight > screenHeight))
					{
						
						RightPlayer.y += 100 * sfw::getDeltaTime();
					}
				}
				if (pickRandomBuff == 1)
				{
					if (sfw::getKey('c') == true)
					{
						BallPos.x = LeftPlayer.x + paddleWidth + ballRadius;
						BallPos.y = LeftPlayer.y + (PaddleHeight / 2);
					}
					DrawStickySpikesLeft(LeftPlayer.x, LeftPlayer.y);
					
					if (BallPos.x - ballRadius <= LeftPlayer.x + paddleWidth && BallPos.y + (ballRadius / 2) <= LeftPlayer.y && BallPos.y - (ballRadius / 2) >= LeftPlayer.y)
					{
						BallPos.x = LeftPlayer.x + paddleWidth;
						BallPos.y = LeftPlayer.y + (PaddleHeight / 2);
					}
				}
				if (pickRandomBuff == 2)
				{
					RightPlayer.x = RightPlayer.x;
					RightPlayer.y = RightPlayer.y;
				}
				//speed 0   spike 1 frozen 2

			}
			sfw::drawCircle(boundingBoxLeft, Circle[1] + buffMovementY, gateRadius);
			//Left PowerGrabLines
			sfw::drawLine(boundingBoxLeft, Circle[1] + buffMovementY,boundingBoxLeft - 25, (Circle[1] + buffMovementY) + 12.5);
			sfw::drawLine(boundingBoxLeft, Circle[2] + buffMovementY, boundingBoxLeft - 25, (Circle[2] + buffMovementY) - 12.5);
			sfw::drawLine(boundingBoxLeft - 25, (Circle[3] + buffMovementY) + 12.5, boundingBoxLeft - 25, (Circle[4] + buffMovementY) - 12.5);
			//Right PowerGrabLines
			sfw::drawLine(boundingBoxRight, Circle[3] + buffMovementY, boundingBoxRight + 25, (Circle[3] + buffMovementY) + 12.5);
			sfw::drawLine(boundingBoxRight, Circle[4] + buffMovementY, boundingBoxRight + 25, (Circle[4] + buffMovementY) - 12.5);
			sfw::drawLine(boundingBoxRight + 25, (Circle[3] + buffMovementY) + 12.5, boundingBoxRight + 25, (Circle[4] + buffMovementY) - 12.5);
			gateRadius += .5;
			if (gateRadius >= 10)
			{
				gateRadius = 10;

			}
			sfw::drawCircle(boundingBoxLeft, Circle[2] + buffMovementY, gateRadius);
		 
			sfw::drawCircle(boundingBoxRight, Circle[3] + buffMovementY, gateRadius);
		
			sfw::drawCircle(boundingBoxRight, Circle[4] + buffMovementY, gateRadius);
			if (isKeyPressed == true)
			{
				
			}
		
		}
		else if (buffOnScreen == false)
		{
			sfw::drawCircle(boundingBoxLeft, Circle[1], gateRadius);
			gateRadius -= .5;
			if (gateRadius <= 0)
			{
				gateRadius = 0;

			}
			sfw::drawCircle(boundingBoxLeft, Circle[2], gateRadius);
		
			sfw::drawCircle(boundingBoxRight, Circle[3], gateRadius);
			
			sfw::drawCircle(boundingBoxRight, Circle[4], gateRadius);
		
		}

	
		/*switch (totalScore)
		{
		case 0:
			break;
		case 4:
			sfw::drawCircle(boundingBoxRight, Circle[4], gateRadius[4]);
			gateRadius[4] += .5;
			if (gateRadius[4] >= 10)
			{
				gateRadius[4] = 10;

			}
		case 3:
			sfw::drawCircle(boundingBoxRight, Circle[3], gateRadius[3]);
			gateRadius[3] += .5;
			if (gateRadius[3] >= 10)
			{
				gateRadius[3] = 10;

			}
		case 2:
			sfw::drawCircle(boundingBoxLeft, Circle[2], gateRadius[2]);
			gateRadius[2] += .5;
			if (gateRadius[2] >= 10)
			{
				gateRadius[2] = 10;

			}
		case 1:
			sfw::drawCircle(boundingBoxLeft, Circle[1], gateRadius[1]);
			gateRadius[1] += .5;
			if (gateRadius[1] >= 10)
			{
				gateRadius[1] = 10;

			}
			break;
		
			
		}*/
		//if (buffOnScreen == true)
		//{
		//	//LeftPowerUpLines();
		//	RightPowerUpLines();
		//}

		//sfw::drawLine(boundingBoxLeft, 0, boundingBoxLeft, topGate); // Left Top Gate
		//sfw::drawLine(boundingBoxLeft, screenHeight, boundingBoxLeft, bottomGate); // Left Bottom Gate
		//sfw::drawLine(boundingBoxRight, 0, boundingBoxRight, topGate); // Right Top Gate
		//sfw::drawLine(boundingBoxRight, screenHeight, boundingBoxRight, bottomGate); // Right Bottom Gate
		sfw::drawCircle(circleX, circleY, sin(timer)*Radius); //Pulsating Circle
		
		if (sfw::getKey('q') == false && sfw::getKey('/') == false)
		{
			buffMovementTimer--;
		}
			
		
		
		if (buffMovementTimer <= 0)
		{
			buffMovementTimer = 500;
			buffOnScreen = true;
			totalScore++;
		}
		if (buffOnScreen == true)
		{
			//buffMovementX -= sfw::getDeltaTime() * sfw::getDeltaTime();

			if (sfw::getKey('8'))
			{
				pickRandomBuff = 0;
			}


			switch (pickRandomBuff)
			{
			case 0:
			default:
				DrawSpeedBoost(buffMovementX, buffMovementY);//Speed Boost Buff
				if (sfw::getKey('q') == false && sfw::getKey('/') == false)
				{
					buffDurations.speedBoostDuration -= sfw::getDeltaTime();
				}
				break;
			case 1:
			
				DrawSpikeBuff(buffMovementX, buffMovementY);//Spike Buff
				if (sfw::getKey('q') == false && sfw::getKey('/') == false)
				{
					buffDurations.spikeBuffDuration -= sfw::getDeltaTime();
				}
				break;
			case 2:
				DrawFrozenBuff(buffMovementX, buffMovementY);//frozen buff
				if (sfw::getKey('q') == false && sfw::getKey('/') == false)
				{
					buffDurations.frozenBuffDuration -= sfw::getDeltaTime();
				}
				break;

			}
			
			
		}
		else if (buffOnScreen == false)
		{
			//buffMovementX -= sfw::getDeltaTime() * sfw::getDeltaTime();
			buffMovementY = BuffPos.y * sfw::getDeltaTime();
			BuffPos.x = screenWidth / 2;
			BuffPos.y -= 0;
			buffDurations.speedBoostDuration = 9;
			buffDurations.spikeBuffDuration = 9;
			buffDurations.frozenBuffDuration = 9;
		}
		if (buffDurations.speedBoostDuration <= -2 || buffDurations.spikeBuffDuration <= -2 || buffDurations.frozenBuffDuration <= -2)
		{
			buffDeleted = true;
			pickRandomBuff = rand() % numberOfBuffs;
			buffOnScreen = false;
			
		    

		}
	
		  							                /*if (buffMovementY < screenHeight / 2)
													{
													DrawStickySpikesRight(RightPlayer.x, RightPlayer.y);
													}
													if (buffMovementY > screenHeight / 2)
													{
													DrawStickySpikesLeft(LeftPlayer.x, LeftPlayer.y);
													}*/

		buffMovementY += 100 * sfw::getDeltaTime(); // get the buff to move down the screen initially
		if (sfw::getKey('q') == false && sfw::getKey('/') == false)
		{
			static float OriginalBuffMoveXPos = BuffPos.x;
			buffMovementX = sin(timer * 10);// *tugOWar;
			//scale = 1;
		}

		

		if (sfw::getKey('q'))
		{
			isKeyPressed = true;
			if (buffMovementY > screenHeight / 2)
			{
				buffMovementY -= 150 * sfw::getDeltaTime();
				buffMovementX -= 150 * sfw::getDeltaTime();
			}
			if (buffMovementY < screenHeight / 2)
			{
				//buffMovementY += 150 * sfw::getDeltaTime();
				buffMovementY += 150 * sfw::getDeltaTime();
				buffMovementX -= 150 * sfw::getDeltaTime();
			}
			buffMovementY -= 100 * sfw::getDeltaTime();
			//buffMovementX -= (10 * sfw::getDeltaTime()) * scale;
			//buffMovementX -= scale;
			//scale += .1;

			/*if (buffMovementX  < boundingBoxLeft + (boundingBoxLeft - buffMovementX))
			{
				buffMovementX = 0;
				scale = 0;
			}*/
			

		}
		
		if (sfw::getKey('/'))
		{
			isKeyPressed = true;
			if (buffMovementY > screenHeight / 2)
			{
				buffMovementY -= 150 * sfw::getDeltaTime();
				buffMovementX += 150 * sfw::getDeltaTime();
			}
			if (buffMovementY < screenHeight / 2)
			{
				buffMovementY += 150 * sfw::getDeltaTime();
				buffMovementX += 150 * sfw::getDeltaTime();
			}
			buffMovementY -= 100 * sfw::getDeltaTime();
			/*buffMovementX -= (10 * sfw::getDeltaTime()) * scale;
			buffMovementX += scale;*/
			//scale += .1;

		}
//
//		if (buffMovementX > screenWidth / 3 && buffOnScreen == true)
//		{
//			if(buffDurations.spikeBuffDuration >= 0)
//			DrawStickySpikesRight(RightPlayer.x, RightPlayer.y);
//		}
//
//
//		if (buffMovementY + 50 > screenHeight)
//		{
//			buffMovementY = 0;
//		}
//		if (approachingCenter)
//		{
//			buffMovementY -= 400 * sfw::getDeltaTime();
//		}
//		if (sfw::getKey('-'))
//		{
//			buffMovementX -= 200 * sfw::getDeltaTime();
//		}
//		if (sfw::getKey('='))// '+' key
//		{
//			buffMovementX += 200 * sfw::getDeltaTime();
//		}
		

		timer += sfw::getDeltaTime();
		
		sin(timer)*Radius;
		circleX -= (sin(timer) * 5); // Circle path

									 //circleY++;
		CirclePos.x = circleX;
		CirclePos.y = circleY;
		if (sfw::getKey(','))//  <
		{
			topGate -= 300 * sfw::getDeltaTime();
			bottomGate -= 300 * sfw::getDeltaTime();
		}
		if (sfw::getKey('.'))// >
		{
			topGate += 300 * sfw::getDeltaTime();
			bottomGate += 300 * sfw::getDeltaTime();
		}

		if (!buffMovement)
		{
			tugOWar--;
			if (tugOWar < -19)
				buffMovement = true;
		}
		else
		{
			tugOWar++;
			if (tugOWar >= 20)
				buffMovement = false;

		}



		//////////////////////////////
		//if (Timer > 10)
		//{
		//	Timer--;
		//}
		//if (Timer <= 10)
		//{
		//	Timer = (radius -= 50);
		//	if (radius <= 0)
		//	{
		//		radius = Radius;
		//	}
		//}
		///////////////////////////

		if (sfw::getKey('w'))
		{
			LeftPlayer.y -= 500 * sfw::getDeltaTime();;
			if (LeftPlayer.y + PaddleHeight <= 0)
			{
				LeftPlayer.y = screenHeight;
			}

		}
		if (sfw::getKey('s'))
		{
			LeftPlayer.y += 500 * sfw::getDeltaTime();
			if (LeftPlayer.y >= screenHeight)
			{
				LeftPlayer.y = 0 - PaddleHeight;
			}
		}

		if (sfw::getKey('a'))
		{
			LeftPlayer.x -= 500 * sfw::getDeltaTime();;
			if (LeftPlayer.x < 0)
			{
				LeftPlayer.x = 0;
			}
		}

		if (sfw::getKey('d'))
		{
			LeftPlayer.x += 500 * sfw::getDeltaTime();;
			if (LeftPlayer.x + paddleWidth >= boundingBoxLeft)
			{
				LeftPlayer.x = 0 - paddleWidth;
			}
		}

		if (Player1HasBuff == false || pickRandomBuff != 2)
		{
			
			if (sfw::getKey('u'))
			{
				RightPlayer.y -= 500 * sfw::getDeltaTime();;
				if (RightPlayer.y + PaddleHeight <= 0)
				{
					RightPlayer.y = screenHeight;
				}

			}
			if (sfw::getKey('j'))
			{
				RightPlayer.y += 500 * sfw::getDeltaTime();
				if (RightPlayer.y >= screenHeight)
				{
					RightPlayer.y = 0 - PaddleHeight;
				}
			}

			if (sfw::getKey('h'))
			{
				RightPlayer.x -= 500 * sfw::getDeltaTime();
				if (RightPlayer.x <= boundingBoxRight)
				{
					RightPlayer.x = screenWidth;
				}
			}
			if (sfw::getKey('k'))
			{
				RightPlayer.x += 500 * sfw::getDeltaTime();
				if (RightPlayer.x + paddleWidth >= screenWidth)
				{
					RightPlayer.x = screenWidth - paddleWidth;
				}
			}
		}


	}
	sfw::termContext();



}
Ejemplo n.º 16
0
void intro()
{
    bool StartGame = false;
    bool QuitGame = false;
    int StartLevel = 1;  
    int q;
	for(q = 1;q<6;q++)
	{
		speedhor[q] = 2;
		speedvert[q] = 2;
		speedhor[5+q] = -2;
		speedvert[5+q] = -2;
	}

	positionx[1] = 16;	positiony[1] = 64;
	positionx[2] = 106;	positiony[2] = 78;
	positionx[3] = 240;	positiony[3] = 120;
	positionx[4] = 18;	positiony[4] = 210;
	positionx[5] = 300;	positiony[5] = 84;
	positionx[6] = 50;	positiony[6] = 92;
	positionx[7] = 83;	positiony[7] = 100;
	positionx[8] = 16;	positiony[8] = 108;
	positionx[9] = 106;	positiony[9] = 116;
	positionx[10] = 240;positiony[10] = 120;

	DrawBackground();
	timecounter_intro = SDL_GetTicks();
   
	while(QuitGame==false && StartGame==false)
	{
		if(SDL_GetTicks() - timecounter_intro > 10)
			{
			timecounter_intro = SDL_GetTicks(); 	// reset counter
			DrawBackground();
			
			for(q = 1; q < 11; q++)
			{
				positionx[q] = positionx[q] + speedhor[q];
				positiony[q] = positiony[q] + speedvert[q];
				if (positionx[q] > 320-16-1)	{speedhor[q] = - 2;}
				if (positiony[q] > 240-16-1)	{speedvert[q] = - 2;}
				if (positionx[q] < 0)		    {speedhor[q] = 2;}
				if (positiony[q] < 80)		    {speedvert[q] = 2;}
			}

			for(q = 1; q<4;q++)	{DrawBall(positionx[q], positiony[q], 1);}
			for(q = 4; q<8;q++)	{DrawBall(positionx[q], positiony[q], 2);}
			for(q = 8; q<11;q++){DrawBall(positionx[q], positiony[q], 3);}

			Print (8*24	,0,  "Port by BruceLee");
			Print (8*13	,24, "OK   - Start");
			Print (8*13	,40, "PLUS - Quit");
   			Print (0	,72, "________________________________________");

			SDL_UpdateRect(DisplaySurface,0,0,0,0);
			}	
		getInput();
		if(Key_ENTER_pressed == true) {StartGame = true;}
		if(Key_ESCAPE_pressed == true) {QuitGame = true;}
		if(Key_9_pressed == true & StartLevel>1) {StartLevel--;}
		if(Key_0_pressed == true & StartLevel<12) {StartLevel++;}		
	}
	
    if(StartGame == true){LevelNumber = StartLevel; LoadLevel(LevelNumber); game_singleplayer();}

}
Ejemplo n.º 17
0
LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
   switch(Message)
   {
      case WM_CREATE:
         hbmBall = LoadBitmap(g_hInst, "BALLBMP");
         hbmMask = LoadBitmap(g_hInst, "MASKBMP");
         if(!hbmBall || !hbmMask){
            MessageBox(hwnd, "Load of resources failed.", "Error",
               MB_OK | MB_ICONEXCLAMATION);
            return -1;
         }

         GetObject(hbmBall, sizeof(bm), &bm);
         SetTimer(hwnd, idTimer1, nTimerDelay, NULL);

         ballX = 0;
         ballY = 0;
         deltaX = deltaValue;
         deltaY = deltaValue;

      break;
      case WM_TIMER:
         if(hbmBall && hbmMask)
         {
            HDC hdcWindow;
            hdcWindow = GetDC(hwnd);

            EraseBall(hdcWindow);
            UpdateBall(hwnd);
            DrawBall(hdcWindow);

            ReleaseDC(hwnd, hdcWindow);
         }
      break;
      case WM_PAINT:
         if(hbmBall && hbmMask)
         {
            PAINTSTRUCT ps;
            HDC hdcWindow;
            hdcWindow = BeginPaint(hwnd, &ps);

            DrawBall(hdcWindow);
            
            EndPaint(hwnd, &ps);
         }
      break;
      case WM_CLOSE:
         DestroyWindow(hwnd);
      break;
      case WM_DESTROY:
         KillTimer(hwnd, idTimer1);
         
         DeleteObject(hbmBall);
         DeleteObject(hbmMask);
         PostQuitMessage(0);
      break;
      default:
         return DefWindowProc(hwnd, Message, wParam, lParam);
   }
   return 0;
}
Ejemplo n.º 18
0
gint main(gint argc, char** argv) {
    gtk_init(&argc, &argv);
    ball = g_slice_new(balls);
    paddle = g_slice_new(paddles);
    white = g_slice_new(GdkGC);
    black = g_slice_new(GdkGC);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_widget_set_size_request(window, DISPLAY_WIDTH, DISPLAY_HEIGHT);
    gtk_window_set_resizable(GTK_WINDOW(window), false);
    gtk_window_set_title(GTK_WINDOW(window), "GTK Pong");

    draw = gtk_drawing_area_new();
    gtk_container_add(GTK_CONTAINER(window), draw);
    InitCallback();
    gtk_widget_show_all(window);

    pixmap = gdk_pixmap_new(draw->window, draw->allocation.width,
                            draw->allocation.height, -1);

    black = draw->style->black_gc;
    white = draw->style->white_gc;

    GtkWidget *ballimagetmp = gtk_image_new_from_file("data/chromium.png");
    ballimage = gtk_image_get_pixbuf(GTK_IMAGE(ballimagetmp));
    BallInfo();

    paddle->width = 100;
    paddle->height = 10;
    paddle->y = DISPLAY_HEIGHT - paddle->height;
    paddle->x = (DISPLAY_WIDTH / 2) - (paddle->width / 2);
    paddle->speed = paddle->width / 2;

    if (DISPLAY_WIDTH < paddle->width) {
        printf("Paddle too big");
        return 2;
    }
    if (DISPLAY_WIDTH < ball->width) {
        printf("Ball too big");
        return 2;
    }
    if (DISPLAY_HEIGHT < paddle->height + ball->height) {
        printf("Height of paddle and ball too big");
        return 2;
    }

    ball->x = UniformRandom(0, DISPLAY_WIDTH - ball->width); //Initial position
    ball->y = UniformRandom(0, (DISPLAY_HEIGHT - ball->height - paddle->height)
                            / 2);
    ball->dx = UniformRandom(3, 7); //Initial speed/direction of travel
    ball->dy = UniformRandom(3, 7);
    if (UniformRandom(1, 2) == 1)//Allow negative values initially
        ball->dx *= -1;
    if (UniformRandom(1, 2) == 1)
        ball->dy *= -1;

    Fill(white, 0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT);
    DrawPaddle(true);
    DrawBall(true);

#ifdef DEBUG
    ball->dx = 0;
    ball->dy = 0;
#else
    for (g_usleep(2 * G_USEC_PER_SEC); g_main_context_iteration(NULL, 0);)
        ;
#endif
    while (true) {
        DrawBall(false);
        gint i;
        for (i = 0; i < ABS(ball->dx) || i < ABS(ball->dy); ++i) {//Move ball
            if (i < ABS(ball->dx)) {
                ball->x += ABS(ball->dx) / ball->dx;
                if (!checkPos()) {
                    ball->dx *= -1;
                    ball->x += 2 * ABS(ball->dx) / ball->dx;
                }
            }
            if (i < ABS(ball->dy)) {
                ball->y += ABS(ball->dy) / ball->dy;
                if (!checkPos()) {
                    ball->dy *= -1;
                    ball->y += 2 * ABS(ball->dy) / ball->dy;
                }
            }
        }
        DrawBall(true);
        for (g_usleep(20000); g_main_context_iteration(NULL, 0);)
            ;
    }
    return 0;
}
Ejemplo n.º 19
0
/** Game event loop. */
void EventLoop() {

   struct timeval last, current;
   unsigned long elapsedTime;
   int repeat;
   XEvent event;

   SetFirstLevel();

   XSelectInput(display, mainWindow, KeyPressMask | KeyReleaseMask
      | ButtonPressMask | ButtonReleaseMask | ExposureMask);

   shouldExit = 0;

   DoStartDelay();

   gettimeofday(&last, NULL);

   while(!shouldExit) {

      if(didWin) {
         WinLoop();
         NextLevel();
         moveRight = 0;
         moveLeft = 0;
         gettimeofday(&last, NULL);
      }
      if(didLose) {
         Redraw();
         DoStartDelay();
         break;
      }

      while(XPending(display) > 0) {
         XNextEvent(display, &event);
         switch(event.type) {
         case Expose:
            HandleExposeEvent(&event.xexpose);
            break;
         case KeyPress:
            HandleKeyPressEvent(&event.xkey);
            break;
         case KeyRelease:
            HandleKeyReleaseEvent(&event.xkey);
            break;
         case ButtonPress:
            HandleButtonPressEvent();
            break;
         default:
            break;
         }
      }

      if(isPaused) {
         gettimeofday(&last, NULL);
         continue;
      }

      gettimeofday(&current, NULL);
      elapsedTime = (current.tv_sec - last.tv_sec) * 1000000;
      elapsedTime += current.tv_usec - last.tv_usec;

      if(elapsedTime >= SPEED) {
         last = current;

         EraseBall();
         repeat = (int)(((float)elapsedTime / SPEED) + 0.5);
         do {
            if(moveRight && !moveLeft) {
               MoveBallRight();
            } else if(moveLeft && !moveRight) {
               MoveBallLeft();
            }
            MoveBall();
            --repeat;
         } while(repeat);
         DrawBall();

         Redraw();

         if(didDie) {
            didDie = 0;
            DoStartDelay();
            gettimeofday(&last, NULL);
         }

      }

   }
}
Ejemplo n.º 20
0
int main(int argc, char **argv)
{
	int Inc = 1;
	struct BALL Ball = { 0 };
	struct PADDLE Paddle = { 0 };
	Bool DoLoadGame = false;
	int GotoLevel = 0;
	
	for (; Inc < argc; ++Inc)
	{ /*Argument parsing.*/
		if (!strcmp("--nocolor", argv[Inc]))
		{
			UseColor = false;
		}
		else if (!strcmp("--version", argv[Inc]))
		{
			printf("Bricktick brick breaker v" BRICKTICK_VERSION "\n"
					"By Subsentient.\n");
			fflush(NULL);
			exit(0);
		}
		else if (!strcmp("--help", argv[Inc]))
		{
			printf("Command line options:\n\t"
					"--help: Show this help.\n\t"
					"--nocolor: Run Bricktick with no color.\n\t"
					"--version: Display version and exit.\n");
			fflush(NULL);
			exit(0);
		}
		else if (!strncmp("--level=", argv[Inc], sizeof "--level=" - 1))
		{
			GotoLevel = atoi(argv[Inc] + sizeof "--level=" - 1);
			
			if (GotoLevel > sizeof Levels / sizeof *Levels)
			{
				fprintf(stderr, "The maximum level is %d.\n", sizeof Levels / sizeof *Levels); fflush(NULL);
				exit(1);
			}
		}
		else
		{
			fprintf(stderr, "Bad command line argument \"%s\".\n"
					"Use --help for command line options.\n", argv[Inc]);
			exit(1);
		}
	}
	
	
	initscr(); /*Fire up ncurses.*/
	
	if (COLS < BRICKTICK_MAX_X || LINES < BRICKTICK_MAX_Y)
	{
		endwin();
		fprintf(stderr, "Please use a console with a resolution of at least %dx%d.\n", BRICKTICK_MAX_X, BRICKTICK_MAX_Y);
		exit(1);
		
	}
	
	/*Color not supported.*/
	if (!has_colors()) UseColor = false;
	
	/*Various ncurses things.*/
	noecho();
	
	if (UseColor)
	{ /*Color fireup.*/
		start_color();
		init_pair(1, COLOR_CYAN, COLOR_BLACK);
		init_pair(2, COLOR_GREEN, COLOR_BLACK);
		init_pair(3, COLOR_BLACK, COLOR_WHITE);
		init_pair(4, COLOR_BLUE, COLOR_BLACK);
		init_pair(5, COLOR_GREEN, COLOR_BLACK);
		init_pair(6, COLOR_YELLOW, COLOR_BLACK);
		init_pair(7, COLOR_RED, COLOR_BLACK);
		
		
		/*Fire up colors for the bricks.*/
		init_pair(BRICK_COLORS_START, COLOR_GREEN, COLOR_BLACK);
		init_pair(BRICK_COLORS_START + 1, COLOR_BLUE, COLOR_BLACK);
		init_pair(BRICK_COLORS_START + 2, COLOR_YELLOW, COLOR_BLACK);
		init_pair(BRICK_COLORS_START + 3, COLOR_MAGENTA, COLOR_BLACK);
		init_pair(BRICK_COLORS_START + 4, COLOR_CYAN, COLOR_BLACK);
		init_pair(BRICK_COLORS_END, COLOR_RED, COLOR_BLACK);
	}
	
	/*Draw borders for consoles bigger than our 80x24 playing area.*/
	DrawBorders();
	
	/*Greeting.*/
GreetAsk:

	if (!GotoLevel)
	{ /*If they specified a level let them go straigth to game start.*/
		DrawGreeting();
		switch (getch())
		{
			case 27: /*27 is ESC key*/
				endwin();
				exit(0);
				break;
			case ' ':
				clear(); /*Wipe the message from the screen.*/
				DrawBorders(); /*Redraw borders.*/
				break;
			case 'o':
				clear();
				DrawBorders();
				DoLoadGame = true;
				LoadGame(&Ball, &Paddle);
				break;
			default:
				goto GreetAsk;
		}
	}
	else
	{
		clear();
		DrawBorders();
	}
	
	halfdelay(1);
	keypad(stdscr, true);
#if NCURSES_VERSION_MAJOR >= 5 && NCURSES_VERSION_MINOR >=4
	set_escdelay(25);
#endif
	curs_set(0);
	

	if (DoLoadGame)
	{
		DrawStats();
		DrawBall(&Ball);
		DrawPaddle(&Paddle);
		DrawAllBricks();
	}
	else
	{
		/*Show our initial lives count.*/
		DrawStats();
	
		/*Reset to level 1 if we haven't specified a level.*/
		SetLevel(GotoLevel ? GotoLevel : 1);
		
		ResetBall(&Ball);
		ResetPaddle(&Paddle);
		
		DrawBall(&Ball);
		DrawPaddle(&Paddle);
		ResetBricks();
		DrawAllBricks();
	}
	
	/*Wait for L key.*/
	WaitForUserLaunch();
	DrawAllBricks(); /*Redraw to fix goofing by WaitForUserLaunch().*/
	
	/*Set up the number generator.*/
	srand(time(NULL));

	/**
	 * Main loop for the game!
	 **/
Reloop:
	GameLoop(&Ball, &Paddle);
	
	DrawMessage("Really quit Bricktick? y/n");
	cbreak();
	
	/*When the game loop exits.*/
	switch (getch())
	{
		case 'y':
		case 'Y':
			break;
		default:
			DeleteMessage();
			refresh();
			halfdelay(1);
			DrawAllBricks(); /*Fix damage to brick display resulting from the message.*/
			goto Reloop;
			break;
	}
	DeleteBall(&Ball);
	DeletePaddle(&Paddle);
	
	endwin();
	
	return 0;
}
Ejemplo n.º 21
0
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch(msg)
	{
		case WM_CREATE:
		{
			UINT ret;
			BITMAP bm;

			g_hbmBall = LoadBitmap(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_BALL));
			if(g_hbmBall == NULL)
				MessageBox(hwnd, "Could not load IDB_BALL!", "Error", MB_OK | MB_ICONEXCLAMATION);

			g_hbmMask = CreateBitmapMask(g_hbmBall, RGB(0, 0, 0));
			if(g_hbmMask == NULL)
				MessageBox(hwnd, "Could not create mask!", "Error", MB_OK | MB_ICONEXCLAMATION);

			GetObject(g_hbmBall, sizeof(bm), &bm);

			ZeroMemory(&g_ballInfo, sizeof(g_ballInfo));
			g_ballInfo.width = bm.bmWidth;
			g_ballInfo.height = bm.bmHeight;

			g_ballInfo.dx = BALL_MOVE_DELTA;
			g_ballInfo.dy = BALL_MOVE_DELTA;

			ret = SetTimer(hwnd, ID_TIMER, 50, NULL);
			if(ret == 0)
				MessageBox(hwnd, "Could not SetTimer()!", "Error", MB_OK | MB_ICONEXCLAMATION);
		}
		break;
		case WM_CLOSE:
			DestroyWindow(hwnd);
		break;
		case WM_PAINT:
		{
			RECT rcClient;
			PAINTSTRUCT ps;
			HDC hdc = BeginPaint(hwnd, &ps);

			GetClientRect(hwnd, &rcClient);
			DrawBall(hdc, &rcClient);

			EndPaint(hwnd, &ps);
		}
		break;
		case WM_TIMER:
		{
			RECT rcClient;
			HDC hdc = GetDC(hwnd);

			GetClientRect(hwnd, &rcClient);

			UpdateBall(&rcClient);
			DrawBall(hdc, &rcClient);

			ReleaseDC(hwnd, hdc);
		}
		break;
		case WM_DESTROY:
			KillTimer(hwnd, ID_TIMER);

			DeleteObject(g_hbmBall);
			DeleteObject(g_hbmMask);

			PostQuitMessage(0);
		break;
		default:
			return DefWindowProc(hwnd, msg, wParam, lParam);
	}
	return 0;
}
Ejemplo n.º 22
0
void render_window()
{
    game_config = GetGameConfig();
    game_levels = GetGameLevels();
    game_levels_count = GetGameLevelsCount();

    arguments = GetArguments();
    user_set = GetUserSettings();
    int start_level = get_start_level();

    save_dir_full = GetSaveDir();
    cache_dir_full = GetCacheDir();
    can_cache = (save_dir_full && cache_dir_full);

//------------------------------------------------------------------------------
    ApplyArguments();

    const SDL_VideoInfo *video_info = SDL_GetVideoInfo();
    if (user_set->geom_x > 0 && user_set->geom_y > 0)
    {
        disp_x = user_set->geom_x;
        disp_y = user_set->geom_y;
    }
    else
    {
        disp_x = video_info->current_w;
        disp_y = video_info->current_h;
    }

    int probe_bpp = (user_set->bpp == 0 ? video_info->vfmt->BitsPerPixel : user_set->bpp);
    disp_bpp = (probe_bpp == 32 ? probe_bpp : 16);

    bool rot = TransformGeom();

//------------------------------------------------------------------------------
#define BTN_SPACE_KOEF 4.5
    int btn_side = disp_y / 7;
    int btn_space = btn_side / BTN_SPACE_KOEF;
    int btns_padded_width = btn_side * 4 + btn_space * 5;
    if (btns_padded_width > disp_x)
    {
        //btn_side = ( wnd_w - 5 * ( btn_side / BTN_SPACE_KOEF ) ) / 4
        btn_side = (int)(disp_x / (4 + 5 / BTN_SPACE_KOEF));
        btn_space = btn_side / BTN_SPACE_KOEF;
    }
    int btns_width = btn_side * 4 + btn_space * 3;
    int font_height = btn_side / 3;
    int font_padding = font_height / 2;

//-- font and labels -----------------------------------------------------------
    TTF_Font *font = TTF_OpenFont(DEFAULT_FONT_FILE, font_height);
    if (!font)
    {
        log_error("Can't load font '%s'. Exiting.", DEFAULT_FONT_FILE);
        return;
    }

    SDL_Surface *levelTextSurface = NULL;
    SDL_Rect levelTextLocation;
    levelTextLocation.y = font_padding;

    SDL_Color fontColor = {0};
#ifndef RGBSWAP
    fontColor.r = 231;
    fontColor.g = 190;
    fontColor.b = 114;
#else
    //--enable-rgb-swap
    fontColor.r = 114;
    fontColor.g = 190;
    fontColor.b = 231;
#endif

    /* Window initialization */
    ingame = true;
    Uint32 sdl_flags = SDL_SWSURFACE;
    if (user_set->fullscreen_mode != FULLSCREEN_NONE)
        sdl_flags |= SDL_FULLSCREEN;
    SDL_Surface *disp = SDL_SetVideoMode(disp_x, disp_y, disp_bpp, sdl_flags);
    if (disp == NULL)
    {
        log_error("Can't set video mode %dx%dx%dbpp. Exiting.", disp_x, disp_y, disp_bpp);
        return;
    }
    screen = disp;
    SDL_Surface *gui_surface = disp;
    SDL_WM_SetCaption("Mokomaze", "Mokomaze");

    /* Draw loading screen */
    SDL_Color whiteColor = {0};
    whiteColor.r = whiteColor.g = whiteColor.b = 255;
    SDL_Surface *titleSurface = TTF_RenderText_Blended(font, "Loading...", whiteColor);
    SDL_Rect title_rect;
    title_rect.x = (disp_x - titleSurface->w) / 2;
    title_rect.y = (disp_y - titleSurface->h) / 2;
    title_rect.w = titleSurface->w;
    title_rect.h = titleSurface->h;
    SDL_BlitSurface(titleSurface, NULL, screen, &title_rect);
    SDL_UpdateRect(screen, title_rect.x, title_rect.y, title_rect.w, title_rect.h);
    SDL_FreeSurface(titleSurface);

//-- load pictures -------------------------------------------------------------
    SDL_Surface *back_pic     = LoadSvg(MDIR "prev-main.svg", btn_side, btn_side, false, false);
    SDL_Surface *forward_pic  = LoadSvg(MDIR "next-main.svg", btn_side, btn_side, false, false);
    SDL_Surface *settings_pic = LoadSvg(MDIR "settings-main.svg", btn_side, btn_side, false, false);
    SDL_Surface *exit_pic     = LoadSvg(MDIR "close-main.svg", btn_side, btn_side, false, false);

    SDL_Surface *back_i_pic    = LoadSvg(MDIR "prev-grey.svg", btn_side, btn_side, false, false);
    SDL_Surface *forward_i_pic = LoadSvg(MDIR "next-grey.svg", btn_side, btn_side, false, false);

    SDL_Surface *back_p_pic    = LoadSvg(MDIR "prev-light.svg", btn_side, btn_side, false, false);
    SDL_Surface *forward_p_pic = LoadSvg(MDIR "next-light.svg", btn_side, btn_side, false, false);

    int tmpx = (rot ? game_config.wnd_h : game_config.wnd_w);
    int tmpy = (rot ? game_config.wnd_w : game_config.wnd_h);
    desk_pic = LoadSvg(MDIR "desk.svg", tmpx, tmpy, rot, true);
    wall_pic = LoadSvg(MDIR "wall.svg", tmpx, tmpy, rot, true);
    int hole_d = game_config.hole_r * 2;
    fin_pic = LoadSvg(MDIR "openmoko.svg", hole_d, hole_d, rot, false);

    if (LoadImgErrors > 0)
    {
        log_error("Some images were not loaded. Exiting.");
        return;
    }

//-- positions of buttons ------------------------------------------------------
    SDL_Rect gui_rect_1, gui_rect_2, gui_rect_3, gui_rect_4;
    gui_rect_1.y = gui_rect_2.y = gui_rect_3.y = gui_rect_4.y = levelTextLocation.y + font_height + font_padding;
    gui_rect_1.x = (disp_x - btns_width) / 2;
    gui_rect_2.x = gui_rect_1.x + btn_side + btn_space;
    gui_rect_3.x = gui_rect_2.x + btn_side + btn_space;
    gui_rect_4.x = gui_rect_3.x + btn_side + btn_space;
//-- for click detection -------------------------------------------------------
    Box gui_box_1, gui_box_2, gui_box_3, gui_box_4;
    gui_box_1.x1 = gui_rect_1.x;
    gui_box_1.y1 = gui_rect_1.y;
    gui_box_1.x2 = gui_rect_1.x + btn_side;
    gui_box_1.y2 = gui_rect_1.y + btn_side;
    gui_box_2.x1 = gui_rect_2.x;
    gui_box_2.y1 = gui_rect_2.y;
    gui_box_2.x2 = gui_rect_2.x + btn_side;
    gui_box_2.y2 = gui_rect_2.y + btn_side;
    gui_box_3.x1 = gui_rect_3.x;
    gui_box_3.y1 = gui_rect_3.y;
    gui_box_3.x2 = gui_rect_3.x + btn_side;
    gui_box_3.y2 = gui_rect_3.y + btn_side;
    gui_box_4.x1 = gui_rect_4.x;
    gui_box_4.y1 = gui_rect_4.y;
    gui_box_4.x2 = gui_rect_4.x + btn_side;
    gui_box_4.y2 = gui_rect_4.y + btn_side;

    //create surface for rendering the level
    render_pic = CreateSurface(SDL_SWSURFACE, game_config.wnd_w, game_config.wnd_h, disp);

    if (user_set->scrolling)
        screen = CreateSurface(SDL_SWSURFACE, game_config.wnd_w, game_config.wnd_h, disp);

    if (user_set->fullscreen_mode != FULLSCREEN_NONE)
        SDL_ShowCursor(!ingame);

    desk_rect.x = 0;
    desk_rect.y = 0;
    desk_rect.w = game_config.wnd_w;
    desk_rect.h = game_config.wnd_h;

    SDL_Rect ball_rect;

    int disp_scroll_border = min(disp_x, disp_y) * 0.27;
    SDL_Rect screen_rect;
    screen_rect.x = 0;
    screen_rect.y = 0;
    screen_rect.w = disp_x;
    screen_rect.h = disp_y;
    SDL_Rect disp_rect;
    disp_rect = screen_rect;

    SDL_Color ballColor = {0};
    ballColor.r = 255;
    ballColor.g = 127;
    ballColor.b = 0;

    User user_set_new = *user_set;
    bool video_set_modified = false;

    /* Settings window initialization */
    settings_init(disp, font_height, user_set, &user_set_new);

    /* Render initialization */
    InitRender();

    /* Input system initialization */
    input_get_dummy(&input);
    SetInput();

    /* Vibro system initialization */
    vibro_get_dummy(&vibro);
    SetVibro();

    /* MazeCore initialization */
    maze_init();
    maze_set_config(game_config);
    maze_set_vibro_callback(BumpVibrate);
    maze_set_levels_data(game_levels, game_levels_count);

    cur_level = start_level;
    RenderLevel();
    RedrawDesk();
    maze_set_level(cur_level);
    ResetPrevPos();

    SDL_Event event;
    bool done = false;
    bool redraw_all = true;
    bool ingame_changed = false;
    int prev_ticks = SDL_GetTicks();
    Point mouse = {0};

//== Game Loop =================================================================
    while (!done)
    {
        bool wasclick = false;
        bool show_settings = false;
        while (SDL_PollEvent(&event))
        {
            bool btndown = false;
            bool btnesc = false;
            if (event.type == SDL_QUIT)
            {
                done = true;
            }
            else if (event.type == SDL_ACTIVEEVENT)
            {
                int g = event.active.gain;
                int s = event.active.state;
                if (ingame && !g && ((s & SDL_APPINPUTFOCUS) || (s & SDL_APPACTIVE)))
                {
                    btndown = true;
                }
            }
            else if (event.type == SDL_MOUSEMOTION)
            {
                mouse.x = event.motion.x;
                mouse.y = event.motion.y;
            }
            else if (event.type == SDL_MOUSEBUTTONUP)
            {
                StopFastChange();
            }
            else if (event.type == SDL_MOUSEBUTTONDOWN)
            {
                btndown = true;
            }
            else if (event.type == SDL_KEYDOWN)
            {
                switch(event.key.keysym.sym)
                {
                case SDLK_q:
                case SDLK_ESCAPE:
                    btnesc = true;
                case SDLK_SPACE:
                case SDLK_p:
                case SDLK_PAUSE:
                    btndown = true;
                    break;
                default:
                    break;
                }
            }
            else if (event.type == SDL_KEYUP)
            {
                switch(event.key.keysym.sym)
                {
                case SDLK_q:
                case SDLK_ESCAPE:
                    if( !wasclick || ingame || show_settings )
                        StopFastChange();
                    else
                        done = true;
                    break;
                case SDLK_SPACE:
                case SDLK_p:
                case SDLK_PAUSE:
                    StopFastChange();
                    break;
                default:
                    break;
                }
            }

            if (btndown)
            {
                if (!ingame)
                {
                    if (inbox(mouse.x, mouse.y, gui_box_1) && !btnesc)
                    {
                        if (cur_level > 0)
                        {
                            SDL_BlitSurface(back_p_pic, NULL, gui_surface, &gui_rect_1);
                            SDL_UpdateRect(gui_surface, gui_rect_1.x, gui_rect_1.y, gui_rect_1.w, gui_rect_1.h);

                            ChangeLevel(cur_level-1, &redraw_all, &wasclick);

                            fastchange_step = -10;
                            StopFastChange();
                            fastchange_timer = SDL_AddTimer(FASTCHANGE_INTERVAL, fastchange_callback, NULL);
                        }
                        continue;
                    }
                    else if (inbox(mouse.x, mouse.y, gui_box_2) && !btnesc)
                    {
                        if (cur_level < game_levels_count - 1)
                        {
                            SDL_BlitSurface(forward_p_pic, NULL, gui_surface, &gui_rect_2);
                            SDL_UpdateRect(gui_surface, gui_rect_2.x, gui_rect_2.y, gui_rect_2.w, gui_rect_2.h);

                            ChangeLevel(cur_level+1, &redraw_all, &wasclick);

                            fastchange_step = +10;
                            StopFastChange();
                            fastchange_timer = SDL_AddTimer(FASTCHANGE_INTERVAL, fastchange_callback, NULL);
                        }
                        continue;
                    }
                    else if (inbox(mouse.x, mouse.y, gui_box_3) && !btnesc)
                    {
                        show_settings = true;
                        RedrawDesk();
                        redraw_all = true;
                        wasclick = true;
                        continue;
                    }
                    else if (inbox(mouse.x, mouse.y, gui_box_4) || btnesc)
                    {
                        done = true;
                        continue;
                    }
                }
                ingame_changed = true;
            } //if (btndown)
        }

        if (ingame_changed)
        {
            ingame = !ingame;
            if (!ingame)
            {
                wasclick = true;
            }
            else
            {
                RedrawDesk();
                redraw_all = true;
            }

            if (user_set->fullscreen_mode == FULLSCREEN_INGAME)
                SDL_WM_ToggleFullScreen(disp);
            if (user_set->fullscreen_mode != FULLSCREEN_NONE)
                SDL_ShowCursor(!ingame);

            prev_ticks = SDL_GetTicks();
            ingame_changed = false;
        }

        if ((!ingame) && (!wasclick) && (must_fastchange))
        {
            int new_cur_level = cur_level + fastchange_dostep;
            clamp_max(new_cur_level, game_levels_count - 1);
            clamp_min(new_cur_level, 0);

            if (new_cur_level != cur_level)
            {
                if (fastchange_dostep < 0)
                {
                    SDL_BlitSurface(back_p_pic, NULL, gui_surface, &gui_rect_1);
                    SDL_UpdateRect(gui_surface, gui_rect_1.x, gui_rect_1.y, gui_rect_1.w, gui_rect_1.h);
                }
                else
                {
                    SDL_BlitSurface(forward_p_pic, NULL, gui_surface, &gui_rect_2);
                    SDL_UpdateRect(gui_surface, gui_rect_2.x, gui_rect_2.y, gui_rect_2.w, gui_rect_2.h);
                }

                ChangeLevel(new_cur_level, &redraw_all, &wasclick);
            }
            must_fastchange = false;
        }

        if (!ingame && !wasclick)
        {
            SDL_Delay(user_set->frame_delay);
            continue;
        }

//-- physics step --------------------------------------------------------------
        int ticks = SDL_GetTicks();
        int delta_ticks = ticks - prev_ticks;
        prev_ticks = ticks;
        clamp_min(delta_ticks, 1);
        clamp_max(delta_ticks, 1000 / 15);

        float acx = 0, acy = 0;
        input.read(&acx, &acy, NULL);
        if (input_cal_cycle)
            input_cal_cycle = (input_calibration_sample(&user_set->input_calibration_data, &acx, &acy, NULL) < MAX_CALIBRATION_SAMPLES);
        input_calibration_adjust(&user_set->input_calibration_data, &acx, &acy, NULL);
        maze_set_speed(user_set->ball_speed);
        maze_set_tilt(acx, acy, 0);
        GameState game_state = maze_step(delta_ticks);

        const dReal *R;
        int tk_px, tk_py, tk_pz;
        maze_get_ball(&tk_px, &tk_py, &tk_pz, &R);
        maze_get_animations(&keys_anim, &final_anim);
//------------------------------------------------------------------------------

        //restore the background
        ball_rect.w = game_config.ball_r * 2;
        ball_rect.h = game_config.ball_r * 2; //
        ball_rect.x = prev_px - game_config.ball_r;
        ball_rect.y = prev_py - game_config.ball_r;
        SDL_BlitSurface(render_pic, &ball_rect, screen, &ball_rect);

        UpdateBufAnimation();
        DrawBall(tk_px, tk_py, tk_pz, R, ballColor);

        //update the screen
        if (!redraw_all && !user_set->scrolling)
        {
            int min_px, max_px;
            int min_py, max_py;
            if (prev_px <= tk_px)
            {
                min_px = prev_px;
                max_px = tk_px;
            }
            else
            {
                min_px = tk_px;
                max_px = prev_px;
            }

            if (prev_py <= tk_py)
            {
                min_py = prev_py;
                max_py = tk_py;
            }
            else
            {
                min_py = tk_py;
                max_py = prev_py;
            }
            min_px -= game_config.ball_r;
            max_px += game_config.ball_r;
            min_py -= game_config.ball_r;
            max_py += game_config.ball_r;
            clamp_min(min_px, 0);
            clamp_max(max_px, game_config.wnd_w - 1);
            clamp_min(min_py, 0);
            clamp_max(max_py, game_config.wnd_h - 1);
            SDL_UpdateRect(screen, min_px, min_py, max_px - min_px, max_py - min_py);
            UpdateScreenAnimation();
        }

        if (user_set->scrolling)
        {
            clamp_min(screen_rect.x, tk_px - disp_x + disp_scroll_border);
            clamp_max(screen_rect.x, tk_px - disp_scroll_border);
            clamp_min(screen_rect.y, tk_py - disp_y + disp_scroll_border);
            clamp_max(screen_rect.y, tk_py - disp_scroll_border);
            clamp(screen_rect.x, 0, game_config.wnd_w - disp_x);
            clamp(screen_rect.y, 0, game_config.wnd_h - disp_y);
            SDL_BlitSurface(screen, &screen_rect, disp, &disp_rect);
        }

        prev_px = tk_px;
        prev_py = tk_py;

//-- GUI -----------------------------------------------------------------------
        if (wasclick && !ingame && !show_settings)
        {
            char txt[32];
            sprintf(txt, "Level %d/%d", cur_level + 1, game_levels_count);
            SDL_FreeSurface(levelTextSurface);
            levelTextSurface = TTF_RenderText_Blended(font, txt, fontColor);
            levelTextLocation.x = (disp_x - levelTextSurface->w) / 2;
            SDL_BlitSurface(levelTextSurface, NULL, gui_surface, &levelTextLocation);

            if (cur_level > 0)
                SDL_BlitSurface(back_pic, NULL, gui_surface, &gui_rect_1);
            else
                SDL_BlitSurface(back_i_pic, NULL, gui_surface, &gui_rect_1);

            if (cur_level < game_levels_count - 1)
                SDL_BlitSurface(forward_pic, NULL, gui_surface, &gui_rect_2);
            else
                SDL_BlitSurface(forward_i_pic, NULL, gui_surface, &gui_rect_2);

            SDL_BlitSurface(settings_pic, NULL, gui_surface, &gui_rect_3);
            SDL_BlitSurface(exit_pic, NULL, gui_surface, &gui_rect_4);
            redraw_all = true;
        }
//------------------------------------------------------------------------------

        //update the whole screen if needed
        if (user_set->scrolling)
        {
            SDL_Flip(disp);
        }
        else if (redraw_all)
        {
            SDL_Flip(screen);
        }
        redraw_all = false;

        if (show_settings)
        {
            bool _video_set_modified = false;
            bool _input_set_modified = false;
            bool _vibro_set_modified = false;
            settings_show(&input_cal_cycle, &_video_set_modified, &_input_set_modified, &_vibro_set_modified);
            if (input_cal_cycle)
                input_calibration_reset();
            if (_video_set_modified)
                video_set_modified = true;
            if (_input_set_modified)
                SetInput();
            if (_vibro_set_modified)
                SetVibro();
            SDL_GetMouseState(&mouse.x, &mouse.y);
            ingame_changed = true;
        }

        switch (game_state)
        {
        case GAME_STATE_FAILED:
            RedrawDesk();
            maze_restart_level();
            ResetPrevPos();
            redraw_all = true;
            break;
        case GAME_STATE_SAVED:
            RedrawDesk();
            maze_reload_level();
            ResetPrevPos();
            redraw_all = true;
            break;
        case GAME_STATE_WIN:
            if (++cur_level >= game_levels_count) cur_level=0;
            RenderLevel();
            RedrawDesk();
            maze_set_level(cur_level);
            ResetPrevPos();
            redraw_all = true;
            break;
        default:
            break;
        }

        SDL_Delay(user_set->frame_delay);
    }
//==============================================================================

    if (video_set_modified)
    {
        user_set->scrolling = user_set_new.scrolling;
        user_set->geom_x = user_set_new.geom_x;
        user_set->geom_y = user_set_new.geom_y;
        user_set->bpp = user_set_new.bpp;
        user_set->fullscreen_mode = user_set_new.fullscreen_mode;
        user_set->frame_delay = user_set_new.frame_delay;
    }

    user_set->level = cur_level + 1;
    SaveUserSettings();

    settings_shutdown();

    SDL_FreeSurface(levelTextSurface);
    TTF_CloseFont(font);
    vibro.shutdown();
    input.shutdown();
}
Ejemplo n.º 23
0
// This function draws to the screen
static void RenderScreen(){

    AnimateFrame();  //animate the objects in the frame

    
    if( (screen_dirty) || (frame_counter<1) ){ 
        //Full background rect clearing
        //SDL_FillRect(screen, NULL, grass_color);
		SDL_BlitSurface(grassField, &screen_rect, screen, &screen_rect);

        
        //draw the goal posts
        SDL_BlitSurface(goalPost, NULL, screen, &right_goal_rect);
        SDL_BlitSurface(goalPost, NULL, screen, &left_goal_rect);
        
        //Reset screen dirty flag
        screen_dirty = 0;     
    }
    else{    
        //Debug ball clear rect
        //SDL_FillRect(screen, &ball_clear_rect, debug_color);
        
        //clear old ball rect
        //SDL_FillRect(screen, &ball_clear_rect, grass_color);
        SDL_BlitSurface(grassField, &ball_clear_rect, screen, &ball_clear_rect);

        //draw the goal posts
        SDL_BlitSurface(goalPost, NULL, screen, &right_goal_rect);
        SDL_BlitSurface(goalPost, NULL, screen, &left_goal_rect);
        
        //Clear old character rect

        //SDL_FillRect(screen, &yellow_guy_clear_rect, grass_color);
		SDL_BlitSurface(grassField, &yellow_guy_clear_rect, screen, &yellow_guy_clear_rect);

        //SDL_FillRect(screen, &purple_guy_clear_rect, grass_color);
		SDL_BlitSurface(grassField, &purple_guy_clear_rect, screen, &purple_guy_clear_rect);
        


        //debug the character clear rects
        //SDL_FillRect(screen, &yellow_guy_clear_rect, debug_color);
        //SDL_FillRect(screen, &purple_guy_clear_rect, debug_color);
    }
	 
    //----------------------
    //Draw the soccer ball
    //----------------------
    DrawBall(ball.frame, ball.x, ball.y);


    //----------------------
    //Draw the goal posts
    //----------------------

    //Redraw the left goal post when the ball is near by
    //if(ball.x < 22 ){
    SDL_BlitSurface(goalPost, NULL, screen, &left_goal_rect);
    //}
    
    //Redraw the right goal post when the ball is near by
    //if((ball.x+ball.w) > (screen->w-22) ){
    SDL_BlitSurface(goalPost, NULL, screen, &right_goal_rect);
    //}
    
    
    //----------------------
    //Draw the characters
    //----------------------
    SDL_BlitSurface(purple_player.image, NULL, screen, &purple_guy_rect);
    SDL_BlitSurface(yellow_player.image, NULL, screen, &yellow_guy_rect);



    //-------------------------
    //Update the screen
    //-------------------------
    
    /* Make sure everything is displayed on screen */
    SDL_Flip(screen);
    
    /* Don't run too fast */
    #ifdef _WIN32
    SDL_Delay(15);
    #endif

    #ifdef __sgi
    SDL_Delay(1);
    #endif
    
    SDL_Delay(1);
    
    
    //increment the current frame number
    frame_counter++;
    
    //Save the settings from the previous frame
    SavePrevious(); 
}
Ejemplo n.º 24
0
static void GameLoop(struct BALL *const Ball, struct PADDLE *const Paddle)
{ /*Primary loop where most events get processed.*/
	
	struct BRICKSTRIKE Strike;
	int Key = 0;
	int SecTick = 0;
	Bool PaddleMovedLastTick;
	DirectionX PaddleMoveDir;
	int Inc = 0;
	Bool Flip = false;
	int SlowBallTicks = 0, BallNukeTicks = 0;
	
	while ((Key = getch()) != 27) /*27 is ESC*/
	{		
		if (SecTick == 10)
		{ /*We get score every second for just surviving.*/
			Score += 2;
			DrawStats();
			SecTick = 0;
		}
		++SecTick;

		if (Ball->Y == 1)
		{ /*We hit the ceiling.*/
			BounceBallY(Ball, DOWN);
		}
		else if (Ball->Y >= BRICKTICK_MAX_Y - 2)
		{ /*More happens when we hit the floor.*/
			if (!CheckBallHitPaddle(Ball, Paddle))
			{
				DeleteBall(Ball);
				Ball->Y = BRICKTICK_MAX_Y - 1;
				DrawBall(Ball);
				
				if (Lives == 1)
				{ /*We ran out of lives.*/
					ProcessGameOver(Ball, Paddle);
				}
				else
				{
					--Lives;
					DrawStats();
					
					WaitForUserLaunch();
							
					DeleteBall(Ball);
					DeletePaddle(Paddle);
					
					ResetBall(Ball);
					ResetPaddle(Paddle);
					
					DrawPaddle(Paddle);
					DrawBall(Ball);
					
					/*Redraw but don't reset.*/
					DrawAllBricks();
				}
			}
			else
			{
				BounceBallY(Ball, UP);
				
				if (PaddleMovedLastTick)
				{ /*We can "whack" the ball with our Paddle->*/
					Ball->DirX = PaddleMoveDir;
				}
				else
				{ /*We cut the paddle into thirds for the X direction after bounce.*/
#define PADDLE_THIRD (Paddle->Length / 3)
					if (Ball->X <= Paddle->X + PADDLE_THIRD)
					{
						Ball->DirX = LEFT;
					}
					else if (Ball->X  > Paddle->X + PADDLE_THIRD && Ball->X <= Paddle->X + (PADDLE_THIRD * 2))
					{
						/*Make whether we hit up or not as a chance.*/
						Bool StraightUp = rand() & 1;
						if (StraightUp) Ball->DirX = X_NEUTRAL;
					}
					else
					{
						Ball->DirX = RIGHT;
					}
				}
			}
		}
		PaddleMovedLastTick = false;
		/*Bounce off left and right walls.*/
		if (Ball->X >= BRICKTICK_MAX_X - 1)
		{
			Ball->X = BRICKTICK_MAX_X - 1;
			BounceBallX(Ball, LEFT);
		}
		else if (Ball->X <= 0)
		{
			Ball->X = 0;
			BounceBallX(Ball, RIGHT);
		}
			
	
		/*Check if a charm hit the paddle.*/
		for (Inc = 0; Inc < BRICK_MAX_NUMLINES * BRICK_MAX_PERLINE; ++Inc)
		{
			if (Charms[Inc].Type == CHARM_NONE || !Charms[Inc].Dropped || Charms[Inc].Y != BRICKTICK_MAX_Y - 2) continue;
			
			if (CheckCharmHitPaddle(Paddle, Charms + Inc))
			{
				void *Ptr = NULL;
				const char *const Strings[] = { "+1,000 Score", "+1 Lives",
											"10 Second Slow Ball", "3 second nuke mode" };
					
				switch (Charms[Inc].Type)
				{
					case CHARM_SCORE:
						Ptr = &Score;
						break;
					case CHARM_LIFE:
						Ptr = &Lives;
						break;
					case CHARM_SLOW:
						Ptr = &SlowBallTicks;
						break;
					case CHARM_NUKE:
						Ptr = &BallNukeTicks;
						break;
					default:
						break;
				}
				
				if (Charms[Inc].Type != CHARM_NONE)
				{ /*Show a message on what type of charm we have here.*/
					DrawMessage(Strings[Charms[Inc].Type - 1]); fflush(NULL);
					usleep(500000);
					DeleteMessage();
					DrawAllBricks();
					DrawStats();
				}
				
				/*Do the thing the charm does.*/
				ProcessCharmAction(Charms + Inc, Ptr);
			}
			
			/*In any case, we're done with it.*/
			DeleteCharm(Charms + Inc);
			Charms[Inc].Type = CHARM_NONE;
		}
		
		/*We hit a brick.*/
		if (BallStruckBrick(Ball, &Strike))
		{
			
			if (BallNukeTicks == 0) /*Nuclear ball passes through.*/
			{
				switch (Strike.StrikeV)
				{
					case STRIKE_TOP:
						Ball->DirY = UP;
						break;
					case STRIKE_BOTTOM:
						Ball->DirY = DOWN;
						break;
					default:
						break;
				}
				
				switch (Strike.StrikeH)
				{
					case STRIKE_LEFT:
						Ball->DirX = LEFT;
						break;
					case STRIKE_RIGHT:
						Ball->DirX = RIGHT;
						break;
					default:
					{
						if (Ball->DirX != X_NEUTRAL) break;
						else
						{
							Bool Dir = rand() & 1;
							Ball->DirX = (DirectionX)Dir;
						}
						break;
					}
				}
			}
			
			DeleteBrick(Strike.Brick);
			Score += 100;
			DrawStats();
			
			if (!BricksLeft())
			{ /*Move to next level.*/

				if (SetLevel(Level + 1))
				{ /*We have more levels to go before we win.*/
					DeleteAllBricks();
					DeleteAllCharms();
					DeleteBall(Ball);
					DeletePaddle(Paddle);
					DrawStats();
					
					Score += 1000; /*Reward for making it this far.*/
					Lives = BRICKTICK_NUMLIVES;
					
					ResetBall(Ball);
					ResetPaddle(Paddle);
					ResetBricks();
					
					DrawAllBricks();
					DrawPaddle(Paddle);
					WaitForUserLaunch();
					DrawBall(Ball);
					DrawAllBricks(); /*Redraw to fix WaitForUserLaunch() goofing.*/
				}
				else
				{ /*WE WON!!!!*/
					char WonBuf[256];
					
					snprintf(WonBuf, sizeof WonBuf, "You Won! Score is %d! Hit ESC to exit or space to play again.", Score);
					DrawMessage(WonBuf);
					
				WinRegetch:
					switch (getch())
					{
						case 27: /*27 is ESC*/
							endwin();
							exit(0);
							break;
						case ' ':
						{
							DeleteMessage();
							
							SetLevel(1);
							
							Lives = BRICKTICK_NUMLIVES;
							Score = 0;
							
							DeleteAllBricks();
							DeleteAllCharms();
							DeleteBall(Ball);
							DeletePaddle(Paddle);
							DrawStats();
							
							ResetBall(Ball);
							ResetPaddle(Paddle);
							ResetBricks();
							
							DrawAllBricks();
							DrawPaddle(Paddle);
							WaitForUserLaunch();
							DrawBall(Ball);
							DrawAllBricks(); /*Redraw to fix WaitForUserLaunch() goofing.*/

							continue; /*For the loop we are in.*/
						}
						default:
							goto WinRegetch;
					}
				}

				continue;
			}
			else
			{ /*Charm drops.*/
				struct CHARM *Charm = GetCharmByBrick(Strike.Brick);
				
				if (Charm)
				{ /*We DO have a charm for this brick.*/
					PerformCharmDrop(Charm); /*Mark it dropped.*/

					/*Now draw the charm.*/
					DrawCharm(Charm);
				}
			}
		}
		
		switch (Key)
		{ /*Paddle movement.*/
			case KEY_LEFT:
				MovePaddle(Paddle, LEFT);
				PaddleMovedLastTick = true;
				PaddleMoveDir = LEFT;
				break;
			case KEY_RIGHT:
				MovePaddle(Paddle, RIGHT);
				PaddleMovedLastTick = true;
				PaddleMoveDir = RIGHT;
				break;
			case 's': /*They want to save the game.*/
				if (SaveGame(Ball, Paddle))
				{
					DrawMessage("Game saved.");
				}
				else
				{
					DrawMessage("Failed to save game.");
				}
				fflush(NULL);
				usleep(500000);
				
				DeleteMessage();
				DrawAllBricks(); /*Redraw bricks if damaged.*/
				
				break;
			case 'o': /*They want us to load a game.*/
			{
				const Bool LoadedOk = LoadGame(Ball, Paddle);
				
				if (LoadedOk)
				{
					/*Restore the state.*/
					clear();
					DrawBorders(); /*Need to redraw these after clearing the screen.*/
					
					DrawBall(Ball);
					DrawPaddle(Paddle);
					DrawStats();
					DrawAllBricks();
					
					DrawMessage("Game loaded.");
				}
				else
				{
					DrawMessage("Failed to load game.");
				}

				fflush(NULL);
				usleep(500000);
				
				DeleteMessage();
				DrawAllBricks();
				break;
			}
			case ' ':
			{
				DrawMessage("PAUSED");
				cbreak();
				
			PauseRegetch:
				switch (getch())
				{
					case ' ':
						DeleteMessage();
						DrawAllBricks(); /*Redraw to fix what deleting the message messed up.*/
						halfdelay(1);
						break;
					case 27: /*27 is ESC*/
						endwin();
						exit(0);
						break;
					default:
						goto PauseRegetch;
				}
			}
			default:
				break;
		}
		
		Flip = !Flip;

		/*Ball movement, obviously. Flip is used to keep it at half speed if we got a 'slow' charm.*/
		if (Flip || SlowBallTicks == 0) MoveBall(Ball);
		
		/*Decrement slow ball ticks until zero, then the ball goes fast again.*/
		if (SlowBallTicks > 0) --SlowBallTicks;
		
		/*Decrement nuclear ball until ticks hit zero.*/
		if (BallNukeTicks > 0) --BallNukeTicks;
		
		/*Charm movement.*/		
		for (Inc = 0; Inc < BRICK_MAX_NUMLINES * BRICK_MAX_PERLINE; ++Inc)
		{
			if (Charms[Inc].Type == CHARM_NONE || !Charms[Inc].Dropped) continue;
			
			if (Flip) MoveCharm(Charms + Inc);
		}
		
		/*Redraw borders in case of terminal resize.*/
		DrawBorders();
	}
}