Exemple #1
0
int main (int argc, char** argv) {

    int N;	//mber of rounds
    int score1 = 0,score2 = 0;
    int result = 0;
    int i;

    Player* player1;
    Player* player2;
    Ball* ball;
    Spell* spell;

    if(argc==1) {
        srand (time(NULL));
        N = -1;
    }

    if(argc==2) {
        srand (time(NULL));
        N = atoi(argv[1]);
    }

    if(argc==3) {
        srand (atoi(argv[2]));
        N = atoi(argv[1]);
    }

    for (i=0; i=N-1; i++) {

        int random = rand()%4;

        if(random==0) player1= new Chasers;
        else if(random==1) player1= new Beaters;
        else if(random==2) player1= new Keepers;
        else player1= new Seekers;

        random=rand()%4;
        if(random==0) player2= new Chasers;
        else if(random==1) player2= new Beaters;
        else if(random==2) player2= new Keepers;
        else player2= new Seekers;

        random=rand()%4;
        if(random==0) spell= new InvalidSpells;
        else if(random==1) spell= new PenaltySpells;
        else if(random==2) spell= new BonusSpells;
        else spell= new JamSpells;

        random=rand()%3;
        if(random==0) ball= new Quaffle;
        else if(random==1) ball= new Bludger;
        else ball= new GoldenSnitch;

        if(result==1) {
            player1->add_spell(-2);
        }

        if(result==2) {
            player2->add_spell(-2);
        }

        result = 0;

        random=rand()%2;

        if(random==0) spell->witchcraft(player1);
        else spell->witchcraft(player2);
        result= ball->battle(&score1,&score2,player1,player2);

        delete player1;
        delete player2;
        delete spell;
        delete ball;

        cout<<result<<endl;
        if(result==3) break;

    }

    cout<<" Team1 "<<score1<<" ,"<<" Team2 "<<score2<<endl;

    return 0;

}
Exemple #2
0
bool is_intersecting(Brick &brick, Ball &ball){
    return 	brick.right() >= ball.left() &&
    brick.left() <= ball.right() &&
    brick.bottom() >= ball.top() &&
    brick.top() <= ball.bottom();
}
Exemple #3
0
void Pong::Update(double simLength)
{
	// Swap between models 2D and 3D
	if (swapProjection)
	{
		if (projectionMode == Game::Orthographic)
		{
			gameObjectRegister[0]->ChangeModel(modelRegister[0], 1.0f, shaderLocations, "Assets/Textures/WhiteTexture.bmp");
			gameObjectRegister[0]->boundingBox.dimensions = glm::vec3(1.0f, 1.0f, 1.0f);
			gameObjectRegister[0]->boundingBoxOffset = glm::vec3(0.0f, 0.0f, 0.0f);
			gameObjectRegister[1]->LoadTextures("Assets/Textures/WhiteTexture.bmp");
			gameObjectRegister[2]->LoadTextures("Assets/Textures/WhiteTexture.bmp");
			gameObjectRegister[3]->LoadTextures("Assets/Textures/WhiteTexture.bmp");
			gameObjectRegister[4]->ChangeModel(modelRegister[0], 1.0f, shaderLocations, "Assets/Textures/WhiteTexture.bmp");
			gameObjectRegister[5]->LoadTextures("Assets/Textures/BlackTexture.bmp");
		}
		if (projectionMode == Game::Perspective)
		{
			gameObjectRegister[0]->ChangeModel(modelRegister[5], 0.005f, shaderLocations, "Assets/Textures/Elephant.bmp");
			gameObjectRegister[0]->boundingBox.dimensions = glm::vec3(3.0f, 3.0f, 2.0f);
			gameObjectRegister[0]->boundingBoxOffset = glm::vec3(0.0f, 0.0f, 0.0f);
			gameObjectRegister[1]->LoadTextures("Assets/Textures/RedTexture.bmp");
			gameObjectRegister[2]->LoadTextures("Assets/Textures/BlueTexture.bmp");
			gameObjectRegister[3]->LoadTextures("Assets/Textures/WoodTexture.bmp");
			gameObjectRegister[4]->ChangeModel(modelRegister[4], 0.02f, shaderLocations, "Assets/Textures/GraniteTexture.bmp");
			gameObjectRegister[5]->LoadTextures("Assets/Textures/NightSkyTexture.bmp");
		}
		swapProjection = false;
	}
	// Score Update
	Ball* tempBallObject = dynamic_cast<Ball*>(gameObjectRegister[0]);		// Casts the ball object in the gameobject list so its derived methods can be accessed.
	GUI* tempGUIObject = dynamic_cast<GUI*>(gameObjectRegister[4]);
	WorldBounds* tempWorldBoundsObject = dynamic_cast<WorldBounds*>(gameObjectRegister[3]);
	tempBallObject->UpdateGUIScore(*tempGUIObject);							// Updates the score by passing references to the games UI.
	if (projectionMode == Perspective)
	{
		tempGUIObject->UpdateScore(true);
		tempWorldBoundsObject->UpdateDrawMode(true);
	}
	else
	{
		tempGUIObject->UpdateScore(false);
		tempWorldBoundsObject->UpdateDrawMode(false);
	}
	bool gameEnd = tempGUIObject->CheckEndCondition();
	if (gameEnd)
	{
		done = true;
	}

	// Update each GameObject.
	for (int i = 0; i < gameObjectRegister.size(); i++)
	{
		gameObjectRegister[i]->Update(simLength, gameObjectRegister);
	}
	
	CameraMovement();
	if (followBall)
	{
		cameraPosition = glm::vec3(tempBallObject->position.x, tempBallObject->position.y, tempBallObject->position.z + 75.0f);
		cameraLookAt = tempBallObject->position;
	}

	gameObjectRegister.back()->position = cameraPosition;		// Update the skybox location, causing it to be infinitely far away.

	viewMatrix = glm::lookAt(cameraPosition, cameraLookAt, upVector);	// Update the view matrix.

	// Clear the pointers.
	tempBallObject = nullptr;
	tempGUIObject = nullptr;
	tempWorldBoundsObject = nullptr;
	delete tempBallObject, tempGUIObject, tempWorldBoundsObject;		// Deletes the memory pointer to avoid memory leaks.
}
Exemple #4
0
int main() {
  //GAME SETUP
  sf::RenderWindow window(sf::VideoMode(gDisplayx,gDisplayy), "PONG - Obrecht");
  window.setFramerateLimit(60);

  // Initialize the Menu
  Menu menu( window.getSize().x, window.getSize().y );
  bool menuBool = true; //Boolean to clear Menu

  Options options( window.getSize().x, window.getSize().y );
  bool optionsBool = false;
  bool computerAIBool = false;
  bool playertwoBool = true; //default behavior

  // Initialize Score
  Score score( window.getSize().x, window.getSize().y );
  ScoreWindow scorewindow( window.getSize().x, window.getSize().y );
  sf::Time elapsed;
  bool scoreBool = true;

  // Initialize the TableMap
  sf::Color PongTableColor = sf::Color(4,27,90);
  TableMap tablemap( window.getSize().x, window.getSize().y );
  
  // Initialize the Paddles - Two Players
  Paddle Paddles("Player 1","Player 2");

  // AI Paddle - One Player
  Paddle Paddle("Player 1");

  // Initialize the Ball
  Ball ball;
  ball.loadsound();

  //Initialize Gameover Screen
  int winningscore = 5;
  Gameover gameover( window.getSize().x, window.getSize().y );
  gameover.loadsound();
  sf::Time elapsedGameOver;
  bool gameoverBool = false;

  while( window.isOpen() ) {
    sf::Event event;
    while( window.pollEvent(event) ) {
	if( event.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) ) {
	  window.close();
	}
	// Handling Menu Options:
	if( menuBool ) {
	  if( sf::Keyboard::isKeyPressed( sf::Keyboard::Up ) ) {
	    menu.MoveUp();
	  }
	  else if( sf::Keyboard::isKeyPressed( sf::Keyboard::Down ) ) {
	    menu.MoveDown();
	  }
	  else if( sf::Keyboard::isKeyPressed( sf::Keyboard::Return ) ) {
	    switch( menu.getPressedItem() ) {
	    case 0:
	      menuBool = false;
	      break;
	    case 1:
	      menuBool = false;
	      optionsBool = true;
	      break;
	    case 2:
	      window.close();
	      break;
	    }
	  }
	}
	if( optionsBool ) {
	  if( sf::Keyboard::isKeyPressed( sf::Keyboard::Up ) ) {
	      options.MoveUp();
	    }
	    else if( sf::Keyboard::isKeyPressed( sf::Keyboard::Down ) ) {
	      options.MoveDown();
	    }
	    else if( sf::Keyboard::isKeyPressed( sf::Keyboard::Return ) ) {
	      switch( options.getPressedItem() ) {
	      case 1:
		computerAIBool = true;
		playertwoBool = false;
		break;
	      case 2:
		playertwoBool = true;
		break;
	      case 3:
		optionsBool = false;
		menuBool = true;
		break;
	      }
	    }
	}
	if( gameoverBool ) {
	  if( sf::Keyboard::isKeyPressed( sf::Keyboard::Space )) {
	    menuBool = true;
	    optionsBool = false;
	    ball.setRightScore(0);
	    ball.setLeftScore(0);
	    ball.ballupdate();
	    gameoverBool = false;
	  }
	}
    }
    
    //DRAWING - Layers of draw commands, i.e. first is layer one
    // Menu at beginning of game
    if( menuBool && !optionsBool) {
      window.clear();
      window.draw(menu); 
    }
    // If Options is pushed
    if( optionsBool ) {
      window.clear();
      window.draw(options); 
    }
    if( !menuBool && !optionsBool ) {
      // Table Lines
      window.clear(PongTableColor);
      window.draw(tablemap);

      // Score
      window.draw(score);

      // Paddles
      if( playertwoBool ) {
	window.draw(Paddles);
	Paddles.movePaddle();
      }

      // Computer AI
      if( computerAIBool ){
      }

      // Ball
      window.draw(ball);
      ball.update(&Paddles);

      // Score Keeper
      if(ball.didLeftPaddleScore() || ball.didRightPaddleScore() ) {
	sf::Clock scoreClock; //reset clock each time
	window.clear();
	scorewindow.updateScore( ball.getLeftScore(), ball.getRightScore() );
	window.draw(scorewindow);
	elapsed+=scoreClock.getElapsedTime();
	
	if( elapsed.asSeconds() >= 0.009 ) {
	  ball.setLeftBool(false);
	  ball.setRightBool(false);	  
	  elapsed-=elapsed; 
	  ball.ballupdate();
	}
	scoreClock.restart();
      }

      // Clean up / Updates
      score.updateScore( ball.getLeftScore(), ball.getRightScore() );
      
      // Gameover
      if( ball.getRightScore() == winningscore ) {
	gameoverBool = true;
	ball.setLeftBool(false);
	ball.setRightBool(false);
	//gameover.playsound();
	std::string winner = Paddles.getRightName() + " WINS!";
	gameover.setWinner( winner );
	window.clear();
	if(gameoverBool)
	  window.draw(gameover);
      }

      if( ball.getLeftScore() == winningscore ) {
	gameoverBool = true;
	ball.setLeftBool(false);
	ball.setRightBool(false);
	//gameover.playsound();
	std::string winner = Paddles.getLeftName() + " WINS!";
	gameover.setWinner( winner );
	window.clear();
	if(gameoverBool)
	  window.draw(gameover);	
      }
    }
    
    window.display();
    
  }
  return 0;
}
void EnvironmentClass::init(const GLint &width, const GLint &height)
{

    for (int i = 0; i < 1; i++)
    {

        GLPosition robotPos;
        robotPos.posX=400;
        robotPos.posY=400;
        GLint robotRadius=10;
        Ball *pRobot = new(std::nothrow) Ball(robotPos, robotRadius, 0);
        
        if (NULL == pRobot)
            continue;

        //pRobot->type = Object::eRobot;
        pRobot->setSpeed(100);
        pRobot->setOrientation(90);
        //pRobot->direction=120;
        
           
//        pRobot->setTarget(i * 2 + 1010);
        pRobot->render(glColorVec(0.0f, 80.0f, 100.0f));
//         
//        if (i % 2)
//            pRobot->setDirectionColor(glColorVec(100, 0, 0));
//        else
//            pRobot->setDirectionColor(glColorVec(200, 0, 100));
             
        vecRobot.push_back(pRobot);
        //printf("direction is %d\n",pRobot->direction);
        //printf("direction is %d\n",vecRobot[i]->getOrientation());
    }
    /**
     *@endcode
     */
    
    /**
     *@todo must create 2 robots
     */ 
    assert(1 == vecRobot.size());
   
    /** 
     * @code  
     * initialize obstacle objects,
     * rand generater radius for obstacle, it between [16, 48) pixels
     * generate a rand posion for the obstacle and new circular obstacle instance
     * set obstacle id,type, default color, 
     * if this obstacle is appointed to a robot, use the robot's direction line color to draw it
     * add to the obstacle vector
     */ 
    for (int i = 0; i < 2; i++)
    {

        GLPosition obsPos;
        obsPos.posX=300;
        obsPos.posY=790-i*790;
        
        Bat *pCircObs = new(std::nothrow) Bat(obsPos, 200, 10);
        
        if (NULL == pCircObs)
            continue;
            pCircObs->direction=90;
        pCircObs->motionless = false;
        pCircObs->id = 1010 + i;
       
        pCircObs->type = Object::eCircular;
        
        pCircObs->render(glColorVec(0, 100, 0));
        
        vecbat.push_back(pCircObs);
    }
    /**
     *@endcode
     */
    
    /**
     *@todo must create 6 circular obstacle
     */ 
    assert(2 == vecbat.size());
    
    /**
     *@todo remember the gui windows's size
     */ 
    winWidth = width;
    winHeight = height;
}
bool Paddle::checkCollision(int yres, Ball &ball)
{
	float ballspeed = 15.0f;
	float ballXVel = ballspeed * cos(0)+10;
	float ballYVel = ballspeed * -sin(35);
    
	//ball collision with paddles
	bool onLeftSide = ball.getXPos() < 150 && xPos < 150;
	bool onRightSide = ball.getXPos() > 150 && xPos > 150;
	bool hitLeftPaddle = (ball.getXPos()-ball.getRadius() <= xPos) &&
		ball.getYPos() >= yPos && ball.getYPos() <= yPos + height;
	bool hitRightPaddle  = (ball.getXPos() >= xPos) &&
		ball.getYPos() >= yPos && ball.getYPos() <= yPos + height;


	//check if paddle is moving up or down
	bool paddleMovingUp = yVel > 0;
	bool paddleMovingDown = yVel < 0;


	checkAI(yres, ball);
	checkScreenCollision(yres);
	float angle = PI/2;


	//collision with ball
	//left paddle
	if(onLeftSide && hitLeftPaddle){
		ball.setXVel(ballXVel);
		createSound(1);
        
		if(paddleMovingUp){
			ballYVel = ballspeed * -sin(-angle);
			ball.setYVel(ballYVel);
			ball.setXVel(ballXVel);
		}
		else if(paddleMovingDown){
			ballYVel = ballspeed * -sin(-angle);
			ball.setYVel(-ballYVel);
			ball.setXVel(ballXVel);
		}
		return true;
	}
	//right paddle
	else if(onRightSide && hitRightPaddle){
		ball.setXVel(-ballXVel);
		createSound(1);
		if(paddleMovingUp){
			ballYVel = ballspeed * -sin(angle);
			ball.setYVel(ballYVel);
			ball.setXVel(-ballXVel);
		}
		else if(paddleMovingDown){
			ballYVel = ballspeed * -sin(-angle);
			ball.setYVel(-ballYVel);
			ball.setXVel(-ballXVel);
		}
		return true;
	}
	

	return false;
}
Exemple #7
0
void GLAnalyzer3::paintGL()
{
    // limit max dT to 0.05 and update color and scroll constants
    if ( show.dT > 0.05 )
    show.dT = 0.05;
    show.colorK += show.dT * 0.4;
    if ( show.colorK > 3.0 )
    show.colorK -= 3.0;
    show.gridScrollK += 0.2 * show.peakEnergy * show.dT;

    // Switch to MODEL matrix and clear screen
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glClear( GL_COLOR_BUFFER_BIT );

    // Draw scrolling grid
    if ( (show.gridEnergyK > 0.05) || (!frame.silence && frame.dEnergy < -0.3) )
    {
    show.gridEnergyK *= exp( -show.dT / 0.1 );
    if ( -frame.dEnergy > show.gridEnergyK )
        show.gridEnergyK = -frame.dEnergy*2.0;
    float gridColor[4] = { 0.0, 1.0, 0.6, show.gridEnergyK };
    drawScrollGrid( show.gridScrollK, gridColor );
    }

    // Roll camera up/down handling the beat
    show.camRot += show.camRoll * show.dT;        // posision
    show.camRoll -= 400 * show.camRot * show.dT;    // elasticity
    show.camRoll *= (1 - 2.0 * show.dT);        // friction
    if ( !frame.silence && frame.dEnergy > 0.4 )
    show.camRoll += show.peakEnergy*2.0;
    glRotatef( show.camRoll / 2.0, 1,0,0 );

    // Translate the drawing plane
    glTranslatef( 0.0f, 0.0f, -1.8f );

    // Draw upper/lower planes and paddles
    drawHFace( -1.0 );
    drawHFace( 1.0 );
    leftPaddle->renderGL();
    rightPaddle->renderGL();

    // Draw Balls
    if ( ballTexture ) {
    glEnable( GL_TEXTURE_2D );
    glBindTexture( GL_TEXTURE_2D, ballTexture );
    } else
    glDisable( GL_TEXTURE_2D );
    glEnable( GL_BLEND );
    Ball * ball = balls.first();
    for ( ; ball; ball = balls.next() )
    {
    float color[3],
          angle = show.colorK;
    // Rotate the color based on 'angle' value [0,3)
    if ( angle < 1.0 )
    {
        color[ 0 ] = ball->color[ 0 ] * (1 - angle) + ball->color[ 1 ] * angle;
        color[ 1 ] = ball->color[ 1 ] * (1 - angle) + ball->color[ 2 ] * angle;
        color[ 2 ] = ball->color[ 2 ] * (1 - angle) + ball->color[ 0 ] * angle;
    }
    else if ( angle < 2.0 )
    {
        angle -= 1.0;
        color[ 0 ] = ball->color[ 1 ] * (1 - angle) + ball->color[ 2 ] * angle;
        color[ 1 ] = ball->color[ 2 ] * (1 - angle) + ball->color[ 0 ] * angle;
        color[ 2 ] = ball->color[ 0 ] * (1 - angle) + ball->color[ 1 ] * angle;
    }
    else
    {
        angle -= 2.0;
        color[ 0 ] = ball->color[ 2 ] * (1 - angle) + ball->color[ 0 ] * angle;
        color[ 1 ] = ball->color[ 0 ] * (1 - angle) + ball->color[ 1 ] * angle;
        color[ 2 ] = ball->color[ 1 ] * (1 - angle) + ball->color[ 2 ] * angle;
    }
    // Draw the dot and update its physics also checking at bounces
    glColor3fv( color );
    drawDot3s( ball->x, ball->y, ball->z, 1.0 );
    ball->updatePhysics( show.dT );
    if ( ball->x < 0 )
        leftPaddle->bounce( ball );
    else
        rightPaddle->bounce( ball );
    }
    glDisable( GL_BLEND );
    glDisable( GL_TEXTURE_2D );

    // Update physics of paddles
    leftPaddle->updatePhysics( show.dT );
    rightPaddle->updatePhysics( show.dT );
    if ( !frame.silence )
    {
    leftPaddle->impulse( frame.energy*3.0 + frame.dEnergy*6.0 );
    rightPaddle->impulse( -frame.energy*3.0 - frame.dEnergy*6.0 );
    }
}
Exemple #8
0
Ball MotionBoard(Ball B) {
	Ball B1;
	if (B.position.x + B.dr().x > TableLength - BallRadius){
		B1.position = B.position + B.dr() - vector3f(2*(B.position.x + B.dr().x - TableLength + BallRadius), 0 , 0);
		B1.speed.x = -0.8 * B.speed.x;
		B1.speed.y = B.speed.y / (abs(B.speed.x)/10 + 1);
	}
	if (B.position.x + B.dr().x < - TableLength + BallRadius){
		B1.position = B.position + B.dr() - vector3f(2*(B.position.x + B.dr().x + TableLength - BallRadius), 0 , 0);
		B1.speed.x = -0.8 * B.speed.x;
		B1.speed.y = B.speed.y / (abs(B.speed.x)/20 + 1);
	}
	if (B.position.y + B.dr().y > TableWidth - BallRadius){
		B1.position = B.position + B.dr() - vector3f(0, 2*(B.position.y + B.dr().y - TableWidth + BallRadius), 0);
		B1.speed.y = -0.8 * B.speed.y;
		B1.speed.x = B.speed.x / (abs(B.speed.y)/10 + 1);
	}
	if (B.position.y + B.dr().y < - TableWidth + BallRadius){
		B1.position = B.position + B.dr() - vector3f(0, 2*(B.position.y + B.dr().y + TableWidth - BallRadius), 0);
		B1.speed.y = -0.8 * B.speed.y;
		B1.speed.x = B.speed.x / (abs(B.speed.y)/20 + 1);
	}
	return B1;
}
Exemple #9
0
int main()
{	
	//	Objects declaration
	srand(time(NULL));

	Paddle paddle(200,50);
	paddle.setX(paddle.getX());
	paddle.setY(paddle.getY());
	Ball ball;
	Stage level1;
	std::vector<Brick*> brick;
	for (int y = 0; y < 7; y++){
		for (int x = 0; x < 10; x++)
		{
			brick.push_back(new Brick(x*85+100,y*45+100,1,"red"));
		}
	}
	RenderWindow window(VideoMode(SCREEN_WIDTH, SCREEN_HEIGHT), "Arkanoid");
	
	Keyboard keyboard;
	
	//if (!music.openFromFile("musictheme.mp3"))
	//{
	//	exit;// error...
	//}
	//music.setPosition(0, 1, 10); // change its 3D position
	//music.setPitch(2);           // increase the pitch
	//music.setVolume(50);         // reduce the volume
	//music.setLoop(true);
	//music.play();
	while (window.isOpen())
	{
		Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
			//	ruch paletki myszk¹ i klawiatura
			if (event.type == Event::MouseMoved)
			{
				paddle.setX(event.mouseMove.x - paddle.getWidth()/2);
			}
		}
		
		Collision::BallPaddle(&ball, &paddle);
		
		ball.setX(ball.getX() + ball.getSpeed().x_speed);
		ball.setY(ball.getY() + ball.getSpeed().y_speed);
		
		// Clear scene, render elements
		window.clear();
		window.draw(level1.getSprite());
		window.draw(paddle.getSprite());
		window.draw(ball.getSprite());
		for(auto &b : brick){
			window.draw(b->getSprite());
		}

		window.display();
	}

	return 0;
}
Exemple #10
0
int main() 
{
	if (!init())
	{
		return 1;
	}

	ballImg = loadImage ("ball.png");
	Ball ball = Ball (screen, ballImg, SCREEN_WIDTH/2 - 8, SCREEN_HEIGHT/2 - 8, 1, 1);

	Paddle p1 = Paddle (screen, SCREEN_WIDTH-20, SCREEN_HEIGHT/2-PADDLE_HEIGHT/2, 
			PADDLE_WIDTH, PADDLE_HEIGHT);

	Paddle p2 = Paddle (screen, 20, SCREEN_HEIGHT/2-PADDLE_HEIGHT/2, 
			PADDLE_WIDTH, PADDLE_HEIGHT);

	// p1 can use default keys, p2 needs new ones bound.
	p2.setKeys (SDLK_w, SDLK_s);

	bool quit = false;
	bool winner = false;
	SDL_Event event;

	Timer fps;

	int bounceCount = 0;

	while (!quit)
	{
		fps.start();

		if (SDL_PollEvent (&event))
		{
			p1.handleEvents (event);
			p2.handleEvents (event);

			if (event.type == SDL_QUIT)
			{
				quit = true;
			}
		}

		// white out the background
		SDL_FillRect (screen, &screen->clip_rect, SDL_MapRGB (screen->format, 0xFF, 0xFF, 0xFF));

		// update the paddles
		p1.draw ();
		p2.draw ();

		// update the ball
		ball.update();

		if (!winner) 
		{
			// check to see if the ball is past the paddle
			if (ball.getXPos() < 20)
			{
				// left player win
				std::cout << "right player win!" << std::endl;
				winner = true;
			}
			else if (ball.getXPos() > SCREEN_WIDTH - 20 - PADDLE_WIDTH)
			{
				// right player win
				std::cout << "left player win!" << std::endl;
				winner = true;
			}
		}

		// check to see if the ball should bounce off the right paddle
		if (ball.getXPos() + 6 == SCREEN_WIDTH - 20 - PADDLE_WIDTH 
				&& ball.getYPos() < p1.getYPos() + PADDLE_HEIGHT 
				&& ball.getYPos() > p1.getYPos())
		{
			std::cout << "right bounce!" << std::endl;
			ball.bounce();
		}

		SDL_UpdateWindowSurface (window);

		if (fps.get_ticks() < 1000 / FRAMES_PER_SECOND)
		{
			SDL_Delay ((1000 / FRAMES_PER_SECOND) - fps.get_ticks());
		}
	}

	clean();

	return 0;
}
Exemple #11
0
int main ()
{
	GameStatus gameStatus;
	Converter converter;
	Player homePlayer1;
	Player homePlayer2; 
	Player awayPlayer1;
	Player awayPlayer2; 
	Ball ball;

	srand(time(NULL));
	int pohotnostRand, pozicioniranjeRand, dodavanjeRand, strat;
	bool stratFlipFlop, scoreFlipFlop;
	int successCounter [12];
	int mainMainCounter = 0;



		 double px0,py0,px1,py1,px2,py2,px3,py3;
		 bool presreci01,presreci02,presreci03;   // homePlayer1
		 bool presreci11,presreci12,presreci13;   // homePlayer2
		 bool presreci21,presreci22,presreci23;   // awayPlayer1
		 bool presreci31,presreci32,presreci33;   // awayPlayer2
		 double vremePr0,vremePr1,vremePr2,vremePr3;

		 for (int i=0;i<12;i++) successCounter[i]=0;

	while (true)
	{/*if (LogFajl.is_open() != true) 
	  LogFajl.open("Izlaz.txt",ios::app);*/
	
		
		//start input
		//10 //20 //30 //40
		gameStatus.inputGameStatus();
		//50 //60 //70 //80
		homePlayer1.inputPos();
		homePlayer2.inputPos();
		awayPlayer1.inputPos();
		awayPlayer2.inputPos();
		//90 //100 //110 //120
		ball.inputPos();
		ball.inputVel();
		//130 //140 //150
		homePlayer1.inputHasKicked();
		homePlayer2.inputHasKicked();
		awayPlayer1.inputHasKicked();
		awayPlayer2.inputHasKicked();
		//end input
		//Player nizIgraca[4] = {homePlayer1,homePlayer2,awayPlayer1,awayPlayer2};
		
		

		// IN CONVERSION
		converter.convertIn(homePlayer1,homePlayer2,awayPlayer1,awayPlayer2,ball,gameStatus);

  //      double a1,b1;
		//odrediTackuOdbijanja(1,-398,a1,b1,ball); // !!!!!******!!!!!*******!!!!!!
		//cout << "INTERSECTION POINT: " << a1 << " " << b1 << endl;

		//start calc

		if ((ball.getXPos()>0) && (ball.getXPos()<g_fieldLength)) mainMainCounter++;

		if ((mainMainCounter<6000) && gameStatus.getReset() && stratFlipFlop)
		{
			stratFlipFlop = false;
			strat = rand() % 12;
			if (strat < 12)
			{
				pohotnostRand = strat % 3;
				pozicioniranjeRand = strat % 2;
				dodavanjeRand = strat / 6;
			}
		}

		if (mainMainCounter >= 6000)
		{
			int pohotnostSuccess[3]={0,0,0},pozicioniranjeSuccess[2]={0,0},dodavanjeSuccess[2]={0,0};
			for (int i=0;i<12;i++)
			{
				pohotnostSuccess[i%3] += successCounter[i];
				pozicioniranjeSuccess[i%2] += successCounter[i];
				dodavanjeSuccess[i/6] += successCounter[i];
			}
			int pohotnostMaxI = maximumN(pohotnostSuccess,3),pozicioniranjeMaxI = maximumN(pozicioniranjeSuccess,2),dodavanjeMaxI = maximumN(dodavanjeSuccess,2);
			if (pohotnostMaxI == 0)
			{
				if (pozicioniranjeMaxI == 0) strat = 0 + 6*dodavanjeMaxI;
				else strat = 3 + 6*dodavanjeMaxI;
			}
			if (pohotnostMaxI == 1)
			{
				if (pozicioniranjeMaxI == 0) strat = 4 + 6*dodavanjeMaxI;
				else strat = 1 + 6*dodavanjeMaxI;
			}
			if (pohotnostMaxI == 2)
			{
				if (pozicioniranjeMaxI == 0) strat = 2 + 6*dodavanjeMaxI;
				else strat = 5 + 6*dodavanjeMaxI;
			}
		}

//Vreme::Primerak()->postaviPrviTajmer();


  homePlayer1.setWillMove(true);                    // *** 
  homePlayer1.setWillKick(true);
  homePlayer2.setWillMove(true);
  homePlayer2.setWillKick(true);

  // potrebno da bi se izracunavala brzina igraca:
  homePlayer1.setPastPos();
  homePlayer2.setPastPos();
  awayPlayer1.setPastPos();
  awayPlayer2.setPastPos();





         odrediTackuPresretanja(homePlayer1,ball,px0,py0,vremePr0,presreci01,presreci02,presreci03,3);
		 odrediTackuPresretanja(homePlayer2,ball,px1,py1,vremePr1,presreci11,presreci12,presreci13,0);
		 odrediTackuPresretanja(awayPlayer1,ball,px2,py2,vremePr2,presreci21,presreci22,presreci23,0);
		 odrediTackuPresretanja(awayPlayer2,ball,px3,py3,vremePr3,presreci31,presreci32,presreci33,0);

		 //LogFajl << vremePr0 << " " << vremePr3 << " " << vectorDistance(ball.getXPos(), ball.getYPos(), homePlayer1.getXPos(), homePlayer1.getYPos()) << " " << vectorDistance(ball.getXPos(), ball.getYPos(), awayPlayer2.getXPos(), awayPlayer2.getYPos()) << " " ;

		 double niz[4] = {vremePr0,vremePr1,vremePr2,vremePr3};

		 int koCePrvi = minimum(niz);

		 // if ((0 == koCePrvi) || (1 == koCePrvi))



		 //if ()
 


        // ODBRAMBENI IGRAC (kretanje)

  double destX, destY;

  //if (0 == koCePrvi) {destX = px0; destY = py0;}else
   odrediKretanjeGolmana (homePlayer1,homePlayer2,awayPlayer1,awayPlayer2,koCePrvi,ball,destX,destY,px0,py0,pohotnostRand);

  homePlayer1.setDestinationX(destX);  
  homePlayer1.setDestinationY(destY);  

  //if (sqrt(pow((homePlayer2.getXPos()-ball.getXPos()),2)+pow((homePlayer2.getYPos()-ball.getYPos()),2)) < 40) // ***
  //{
	 // homePlayer1.setDestinationX(500);
	 // homePlayer2.setDestinationY(200);
  //}

 


  // NAPADACKI IGRAC  (kretanje)

	double pX,pY,vremePr;
	//Vreme::Primerak()->postaviPrviTajmer();
	odrediTackuPresretanja(homePlayer2,ball,pX,pY,vremePr,presreci11,presreci12,presreci13,0);
	//Vreme::Primerak()->postaviDrugiTajmer();
	//Vreme::Primerak()->ispisiTrajanjeIzvrsavanjaULog();

	if (true == (presreci11 || presreci12 || presreci13))  // moze i samo true == presreci 13
	{
		homePlayer2.setDestinationX(pX);
		homePlayer2.setDestinationY(pY);
	}
	else
	{
		homePlayer2.setDestinationX(homePlayer2.getXPos());       // ball.getXPos()
		homePlayer2.setDestinationY(homePlayer2.getYPos());       // ball.getYpos()
	}

 Player awayGoalie = ((awayPlayer1.getXPos() > awayPlayer2.getXPos()) ? awayPlayer1 : awayPlayer2);
 int AGIndex = ((awayPlayer1.getXPos() > awayPlayer2.getXPos()) ? 2 : 3);
 //LogFajl << " AGIndex " << AGIndex << "  koCePrvi " << koCePrvi << " " ; 
 
 if ((koCePrvi != 1) && (koCePrvi != AGIndex) && (pozicioniranjeRand == 1))
 {
  //LogFajl << " DA ";
  homePlayer2.setDestinationX((awayPlayer1.getXPos() + awayPlayer2.getXPos()) / 2);
  homePlayer2.setDestinationY((awayPlayer1.getYPos() + awayPlayer2.getYPos()) / 2);
 }

 if (((0 == koCePrvi) && (awayGoalie.getXPos() > g_fieldLength - 150) && (abs(awayGoalie.getYPos()) < 150)) && (pozicioniranjeRand==0))
 {
  //LogFajl << " DA ";
  homePlayer2.setDestinationX(awayGoalie.getXPos() - 30);
  homePlayer2.setDestinationY(-1*awayGoalie.getYPos());
 }
 if(((0 == koCePrvi) && (!((awayGoalie.getXPos() > g_fieldLength - 150) && (abs(awayGoalie.getYPos()) < 150)))) && (pozicioniranjeRand==0))
 {
  homePlayer2.setDestinationX(awayGoalie.getXPos() + 60);
  homePlayer2.setDestinationY(-1*awayGoalie.getYPos());
  //homePlayer2.setDestinationX((awayPlayer1.getXPos() + awayPlayer2.getXPos()) / 2);
  //homePlayer2.setDestinationY((awayPlayer1.getYPos() + awayPlayer2.getYPos()) / 2);
 }
  




	// ========SUTIRANJE======== //

	double xkick,ykick;
	double intenzitet;
	bool mozeSigurno;

	sutUgol(ball,awayPlayer1,awayPlayer2,xkick,ykick,intenzitet,mozeSigurno);

   //LogFajl << koCePrvi << " " << setw(15) ;
   
  if (mozeSigurno)
  {//LogFajl << "Sut Sigurica";
	homePlayer1.setKickVectorX(xkick);  //**********
	homePlayer1.setKickVectorY(ykick);  //**********
	homePlayer1.setKickIntensity(intenzitet); // treba 100 za precisionShotMax

	homePlayer2.setKickVectorX(xkick);
	homePlayer2.setKickVectorY(ykick);
	homePlayer2.setKickIntensity(intenzitet);
  }
  else
  {
	  bool mozeVodjenje; double xkickV,ykickV,intenzitetV;
	  if (sqrt(pow((homePlayer1.getXPos()-ball.getXPos()),2)+pow((homePlayer1.getYPos()-ball.getYPos()),2)) < sqrt(pow((homePlayer2.getXPos()-ball.getXPos()),2)+pow((homePlayer2.getYPos()-ball.getYPos()),2)))
    vodiLoptu(g_fieldLength,0,ball,homePlayer1,awayPlayer1,awayPlayer2,xkickV,ykickV,intenzitetV,mozeVodjenje);
	  else vodiLoptu(g_fieldLength,0,ball,homePlayer2,awayPlayer1,awayPlayer2,xkickV,ykickV,intenzitetV,mozeVodjenje);

	  

	  if (mozeVodjenje)
   {//LogFajl << "Vodi Loptu";
    homePlayer1.setKickVectorX(xkickV);  
    homePlayer1.setKickVectorY(ykickV);  
    homePlayer1.setKickIntensity(intenzitetV); 

    homePlayer2.setKickVectorX(xkickV);
    homePlayer2.setKickVectorY(ykickV);
    homePlayer2.setKickIntensity(intenzitetV);
   }  
	  else
	  {
			
			double AP1DoGolmana = vectorDistance(awayPlayer1.getXPos(),awayPlayer1.getYPos(),homePlayer1.getXPos(),homePlayer1.getYPos()),
				AP2DoGolmana = vectorDistance(awayPlayer2.getXPos(),awayPlayer2.getYPos(),homePlayer1.getXPos(),homePlayer1.getYPos()),
				bliziDoGolmana = (AP1DoGolmana < AP2DoGolmana) ? AP1DoGolmana : AP2DoGolmana;
			
			double dodajX,dodajY,dodajInt;

			bool mozeDodajHP1Spec = dodajSpec(ball,homePlayer1,homePlayer2,awayPlayer1,awayPlayer2,dodajX,dodajY,dodajInt);
			

			if (mozeDodajHP1Spec)
			{
				homePlayer1.setKickVectorX(dodajX);  //**********
				homePlayer1.setKickVectorY(dodajY);  //**********
				homePlayer1.setKickIntensity(dodajInt);
			}
			else
			{
				bool mozeDodajHP1 = dodaj(ball,homePlayer1,homePlayer2,awayPlayer1,awayPlayer2,dodajX,dodajY,dodajInt);
				if (mozeDodajHP1)
				{//LogFajl << "Dodavanje hp1";
					homePlayer1.setKickVectorX(dodajX);  //**********
					homePlayer1.setKickVectorY(dodajY);  //**********
					homePlayer1.setKickIntensity(dodajInt);
				}
				else
				{
					homePlayer1.setKickVectorX(xkick);  //**********
					homePlayer1.setKickVectorY(ykick);  //**********
					homePlayer1.setKickIntensity(intenzitet); // treba 100 za precisionShotMax
				}
			}

			bool mozeDodajHP2 = dodaj(ball,homePlayer2,homePlayer1,awayPlayer1,awayPlayer2,dodajX,dodajY,dodajInt);

			if (mozeDodajHP2 && (homePlayer2.getXPos() > (g_fieldLength / (3 - dodavanjeRand)) - g_playerDiameter)  && (bliziDoGolmana > g_fieldLength / 4))
			{//LogFajl << "Dodavanje hp2";
				homePlayer2.setKickVectorX(dodajX);  //**********
				homePlayer2.setKickVectorY(dodajY);  //**********
				homePlayer2.setKickIntensity(dodajInt);
			}
			else
			{
				homePlayer2.setKickVectorX(xkick);
				homePlayer2.setKickVectorY(ykick);
				homePlayer2.setKickIntensity(intenzitet);
			}
	  }
  }

 


  if (gameStatus.getReset() == false)
	  stratFlipFlop = true;

  if ((ball.getXPos() > g_fieldLength + g_ballDiameter) && scoreFlipFlop)
  {
	  scoreFlipFlop = false;
	  successCounter[strat]++;
  }
  if ((ball.getXPos() < - g_ballDiameter) && scoreFlipFlop)
  {
	  scoreFlipFlop = false;
	  successCounter[strat]--;
  }

  if ((ball.getXPos() > 0) && (ball.getXPos()<g_fieldLength))
  {
	  scoreFlipFlop = true;
  }

		//end calc

  

// ISPIS U FAJL
  
    /*LogFajl.is_open() != true) 
	  LogFajl.open("Izlaz.txt",ios::app);*/

//double bolXvel = ball.getXVel(), bolYvel = ball.getYVel(), homeXpos = homePlayer1.getXPos(), homeYpos = homePlayer1.getYPos();
//double ka = ball.getYVel() / ball.getXVel() ;

	//LogFajl << koCePrvi << " ||| " << px0 << " " << py0 << endl; //<< " ||| " << presreci01 << " ||| " ; //<< homeXpos << " " << homeYpos << " ||| " << bolXvel << " " << bolYvel << endl ;
    //LogFajl << ball.getXVel() << " " << ball.getYVel() << " " << ka << endl;
	/*LogFajl << " " << koCePrvi << " " << ball.getXVel() << " " << ball.getYVel() << "  igractackapreseka:   " << vectorDistance(homePlayer1.getXPos(),homePlayer1.getYPos(),px0,py0) << "   loptatackapreseka  " << vectorDistance(ball.getXPos(),ball.getYPos(),px0,py0) << "   brzinaigraca  " << vectorLength(homePlayer1.getVelX(),homePlayer1.getVelY()) << "  |||| ";
	LogFajl << "  njihovtackapreseka:   " << vectorDistance(awayPlayer2.getXPos(),awayPlayer2.getYPos(),px3,py3) << "   loptatackapresekanjihov  " << vectorDistance(ball.getXPos(),ball.getYPos(),px3,py3) << "   brzinanjihov  " << vectorLength(awayPlayer2.getVelX(),awayPlayer2.getVelY()) << endl;*/

	//LogFajl << "glavni tajmer:   " << mainMainCounter << "   strategija:   " << strat<< endl;

	//LogFajl <<  vremeGore << " " << vremeDole << " " << vremeDirekt << " " << sut << " "  ;
	//LogFajl <<  ball.getXVel() << " " << ball.getYVel() << endl ;
		
		//sqrt(pow(ball.getXVel(),2)+pow(ball.getYVel(),2)) << endl;               // presreci13 << " " ;     
		
		//sqrt(pow(ball.getXVel(),2)+pow(ball.getYVel(),2)) << " ";

  //LogFajl.close(); 



//Vreme::Primerak()->postaviDrugiTajmer();


		// OUT CONVERSION
		converter.convertOut(homePlayer1,homePlayer2,awayPlayer1,awayPlayer2,ball,gameStatus);


		

		//Vreme::Primerak()->ispisiTrajanjeIzvrsavanjaULog();
        

		//start output
		//170 //180 //190 //200 //210 //220 //230 //240
		homePlayer1.outputDecisions();
		homePlayer2.outputDecisions();
  
		//end output

		
		// Vreme::Primerak()->ispisiTrajanjeIzvrsavanjaULog();
	} // while (true)

	

	return 0;
}
Exemple #12
0
JNIEXPORT void JNICALL Java_net_catchball_CatchBallGLSurface_nativePause
  (JNIEnv *, jclass) {
  ball.stopRotating();
//  LOGI("Pause");
}
Exemple #13
0
JNIEXPORT void JNICALL Java_net_catchball_CatchBallGLSurface_processTouch
  (JNIEnv *, jclass, jfloat x1, jfloat y1, jfloat x2, jfloat y2) {
	ball.rotate(x1,y1,x2,y2);
}
Exemple #14
0
int main( int argc, char* args[] )
{
	if (!initialize())
	{
		return 1;
	}

	if (!createWindow("RF", 800, 600, false)) return false;

	SoundEngine* soundEngine = createSoundEngine();
	SoundSource* music = loadSound(soundEngine, "music.mp3");
	soundEngine->play2D(music);

	SoundSource* effect = loadSound( soundEngine, "effecft.mp3" );
	soundEngine->play2D( effect );
	deleteSound( soundEngine, effect );

	bool play = true;

	loadTexture("logo.png");

	//Font
	//RF_Font font = RF_LoadFont("cour.ttf");
	Font font = loadFont("cour.ttf");
	
	if (font->Error()	)
	{
		return -1;
	}
	font->FaceSize(20);

	//Sound

	float angle = 0;

	Player player;
	Player2 player2;
	Ball ball;

	while (play)
	{
		beginLoop();

		//Events
		if(checkEvent())
		{
			if (eventType == SDL_KEYDOWN && eventKey == SDLK_ESCAPE)
			{
				play = false;
			}

			player.events();
			player2.events();
		}

		//Logic
		player.logic(&ball);
		player2.logic(&ball);
		ball.logic();

		//Render
		clearWindow();

		player.render();
		player2.render();
		ball.render();
		//Fonti TODO 

		drawText( font, "Test test test test", 0, 0 );

		swapBuffer();

		handleFps();
	}

	return 0;
}
// Saves all of the pertinent calibration settings to human-readable file
void saveSettings() {
  // Open file
  std::ofstream of("settings.data");

  if (!of.is_open()) {
    printf("\n\n\nERROR OPENING SETTINGS FILE!\n\n\n");
    return;
  }

  const string h1 = "Home1";
  const string h2 = "Home2";
  const string a1 = "Away1";
  const string a2 = "Away2";
  const string b = "Ball";
  const string f = "Field";
  int tempH, tempS, tempV;

  // Print human-readable header for settings file
  of << "#############################################################" << "\n";
  of << "# This settings file contains the color calibration settings" << "\n";
  of << "# Format: " << "\n";
  of << "# [RobotName] [Hmin] [Smin] [Vmin] [Hmax] [Smax] [Vmax]" << "\n";
  of << "# [Ball] [Hmin] [Smin] [Vmin] [Hmax] [Smax] [Vmax]" << "\n";
  of << "# [Field] [x_center_pos] [y_center_pos] [width] [height]" << "\n";
  of << "#############################################################" << "\n";
  of << "\n\n";

  // Robot Save format:
  // [RobotName] [Hmin] [Smin] [Vmin] [Hmax] [Smax] [Vmax]
  tempH = home1.getHSVmin().val[0];
  tempS = home1.getHSVmin().val[1];
  tempV = home1.getHSVmin().val[2];
  of << h1 << " " <<  tempH << " " <<  tempS << " " <<  tempV;
  tempH = home1.getHSVmax().val[0];
  tempS = home1.getHSVmax().val[1];
  tempV = home1.getHSVmax().val[2];
  of << " " <<  tempH << " " <<  tempS << " " <<  tempV << "\n";

  tempH = home2.getHSVmin().val[0];
  tempS = home2.getHSVmin().val[1];
  tempV = home2.getHSVmin().val[2];
  of << h2 << " " <<  tempH << " " <<  tempS << " " <<  tempV;
  tempH = home2.getHSVmax().val[0];
  tempS = home2.getHSVmax().val[1];
  tempV = home2.getHSVmax().val[2];
  of << " " <<  tempH << " " <<  tempS << " " <<  tempV << "\n";

  tempH = away1.getHSVmin().val[0];
  tempS = away1.getHSVmin().val[1];
  tempV = away1.getHSVmin().val[2];
  of << a1 << " " <<  tempH << " " <<  tempS << " " <<  tempV;
  tempH = away1.getHSVmax().val[0];
  tempS = away1.getHSVmax().val[1];
  tempV = away1.getHSVmax().val[2];
  of << " " <<  tempH << " " <<  tempS << " " <<  tempV << "\n";

  tempH = away2.getHSVmin().val[0];
  tempS = away2.getHSVmin().val[1];
  tempV = away2.getHSVmin().val[2];
  of << a2 << " " <<  tempH << " " <<  tempS << " " <<  tempV;
  tempH = away2.getHSVmax().val[0];
  tempS = away2.getHSVmax().val[1];
  tempV = away2.getHSVmax().val[2];
  of << " " <<  tempH << " " <<  tempS << " " <<  tempV << "\n";


  // Ball Save format:
  // [Ball] [Hmin] [Smin] [Vmin] [Hmax] [Smax] [Vmax]
  tempH = ball.getHSVmin().val[0];
  tempS = ball.getHSVmin().val[1];
  tempV = ball.getHSVmin().val[2];
  of << b << " " <<  tempH << " " << tempS << " " <<  tempV;
  tempH = ball.getHSVmax().val[0];
  tempS = ball.getHSVmax().val[1];
  tempV = ball.getHSVmax().val[2];
  of << " " <<  tempH << " " <<  tempS << " " <<  tempV << "\n";

  // Field Save format:
  // [Field] [x_pos] [y_pos] [width] [height]
  of << f << " " << field_center_x << " " << field_center_y;
  of << " " << field_width << " " <<  field_height << "\n";

  // close file
  of.close();
  printf("Settings Saved!\n");
}