Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Pong.exe keeps crashing, C::B issue or C++ issue?  (Read 1846 times)

0 Members and 1 Guest are viewing this topic.

BrainInaJar1245

  • Newbie
  • *
  • Posts: 21
    • View Profile
Pong.exe keeps crashing, C::B issue or C++ issue?
« on: May 17, 2012, 04:52:22 pm »
So whenever I run the following code, get a message from windows saying that pong.exe has stopped working. Is this because of bad coding, or is this because of Code::Blocks?

// Program: Pong
// Created By: CW Stoneman
// Studio: Jumping Lemmings Studios
// Date Created: 2-28-12
// Version: 0.0
// Last Updated: 4-25-12
// Version Notes:

// Description: A pong clone to figure out how to use SFML.

// To do list:
// Figure out why it won't display anything

// Headers to include
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <cmath>

using namespace std;

// Global constants
const float PI = 3.14159f;                           // Pi
const int RESETSCORE = 10;               // The score at which the game is over
const int STARTINGX1 = 40;                  // The starting x position for
                                                                            // paddle 1
const int TEXTY1 = 20;                              // The y coordinate for the
                                                                            // player names
const int TEXTY2 = 50;                              // The y coordinate for the
                                                                            // scores
const int TEXTX1 = 100;                            // The x coordinate for the
                                                                            // First score
const int TEXTX2 = 540;                            // The x coordinate for the
                                                                            // second score
const double PADDLESPEED = 2.5; // The speed at which the paddles move
const double AICHANGE = 0.75;         // The adjustment for the AI. AI's speed =
                                                                            // (other player's score/2)* AICHANGE
const int PADDLEHEIGHT = 75;           // Height of the paddles
const int PADDLEWIDTH = 20;             // Width of the paddles
const int BALLSIZE = 25;                         // Size of the ball

// Function Prototypes
int main();

// Class Prototypes
class Ball;
class Paddle;
class Game;

class Ball
// The class for the ball
{
    // Declare the variables
    public:
        sf::Shape circle;          // The paddle's sprite
        double speed;          // The speed of the ball
        double ballAngle;    // Points one of four directions for the
                                                 // ball
        bool colliding;            // If the ball is colliding or not

    // Function prototypes
    public:
        void loadResources(sf::RenderWindow&);
        void changePosition(sf::RenderWindow&);
        void reset();
        void update();
        int checkCollision(double, double, double, double, double, double,
                           sf::RenderWindow&);
        void bounce(int,double,double,bool);
};

void Ball::loadResources(sf::RenderWindow& App)
// Loads the ball's resources
{
    circle = sf::Shape::Circle(App.GetView().GetRect().GetWidth() /2,
                               App.GetView().GetRect().GetHeight() /2, 12.5,
                               sf::Color(125,234,19));
}

void Ball::changePosition(sf::RenderWindow& App)
// Moves the ball
{
    float Factor = speed * App.GetFrameTime();
    circle.Move(cos(ballAngle) * Factor, sin(ballAngle) * Factor);
}

void Ball::reset()
// Resets the ball
{
    do
    {
       // Make sure the ball initial angle is not too much vertical
        ballAngle = sf::Randomizer::Random(0.f, 2 * PI);
    } while (abs(cos(ballAngle)) < 0.7f);
    speed = 400.f;
}

int Ball::checkCollision(double xPosition1, double yMin1, double yMax1,
                           double xPosition2, double yMin2,double yMax2,
                           sf::RenderWindow& App)
// Checks if the ball needs to bounce, and returns true if the player has \
// scored.
{
    int scored;
    if (circle.GetPosition().x < 0)

    {
        scored = 1;
    }
    else if (circle.GetPosition().x > App.GetView().GetRect().GetWidth() )
    {
        scored = 2;
    }
    if (circle.GetPosition().y < 0.f)
         {
            ballAngle = -ballAngle;
            circle.SetY(0.1f);
         }
    else if ((circle.GetPosition().x == xPosition1) &&
             (circle.GetPosition().y > yMin1) &&
              (circle.GetPosition().y < yMax1))
    {
        bounce(90,xPosition1,PADDLEWIDTH, TRUE);
    }
    else if ((circle.GetPosition().x == xPosition2) &&
             (circle.GetPosition().y > yMin2) &&
              (circle.GetPosition().y < yMax2))
    {
        bounce(-90,xPosition2,PADDLEWIDTH, TRUE);
    }
    return scored;
}

void Ball::bounce(int angle, double paddlePositionx, double paddleSize,
                  bool paddle)
// Check the collisions between the ball and the paddles
{
    if (paddle)
        {
            angle = PI - angle;
            circle.SetX(paddlePositionx + paddleSize + 0.1f);
        }
        else
        {
            angle = PI - angle;
            circle.SetX(paddlePositionx - paddleSize - 0.1f);
        }
    }

class Paddle
// Class for the paddles
{
    //. Declare the variables
    public:
        sf::Shape rectangle; // The sprite for the paddle
        float paddleSpeed; // The paddle's speed

    // Function Prototypes
    public:
        void loadResources(float,sf::RenderWindow&);
        void changePosition(sf::RenderWindow&, sf::Clock&);
        void reset(float,sf::RenderWindow&);
        void update();
        void move(Ball, int, sf::RenderWindow&);
        void move(sf::RenderWindow&, bool);
};

void Paddle::move(Ball theBall, int otherScore, sf::RenderWindow& App)
// Moves the AI Paddle
{
    paddleSpeed = ((otherScore/2)/AICHANGE) + 1;
    if (theBall.circle.GetPosition().x > 0)
    {
        rectangle.Move(0,paddleSpeed*App.GetFrameTime());
    }
    else
    {
        rectangle.Move(0,-paddleSpeed*App.GetFrameTime());
    }
}

void Paddle::loadResources(float xcoordinate, sf::RenderWindow& App)
// Loads the resources for the paddle
{
     rectangle = sf::Shape::Rectangle((xcoordinate)-12.5, (App.GetView().GetRect().GetHeight() /2)-37.5,
                                      (xcoordinate)+12.5,(App.GetView().GetRect().GetHeight() /2)+37.5,
                                      sf::Color(255, 21, 13));
}

void Paddle::move(sf::RenderWindow& App, bool direction)
// Moves the player's paddle
{
    if (direction == TRUE)
    // Move it up
    {
        rectangle.Move(0.f, paddleSpeed * App.GetFrameTime());
    }
    else if (direction == FALSE)
    // Move down
    {
        rectangle.Move(0.f, -paddleSpeed * App.GetFrameTime());
    }
}

void Paddle::reset(float startingx,sf::RenderWindow& App)
// Resets the paddle
{
    rectangle.SetPosition(startingx, App.GetView().GetRect().GetHeight() /2);
    paddleSpeed = 350;
}

class Game
// The main class with the game and all its variables
{
    // Declare the variables
    public:
        Ball theBall;                      // The ball
        Paddle paddle1;            // The first paddle
        Paddle paddle2;            // The second paddle
        int score1;                        // The first score
        int score2;                        // The second score
        sf::Font mechaBold;      // The font used for displaying the scores
        sf::String score1Text;    // The text for the first score
        sf::String score2Text;    // The text for the second score
        sf::String player1Text;   // The text for the first player
        sf::String player2Text;   // The text for the second player
        sf::String status;               // The game's status

    // Function Prototypes
    public:
        void loadResources(sf::RenderWindow&);
        void reset(sf::RenderWindow&);
        void update(sf::RenderWindow&, bool);
        void score(int, sf::RenderWindow&);
        void newRound(sf::RenderWindow&);
};

void Game::update(sf::RenderWindow& App, bool direction)
{
    int scored;
    double Factor = theBall.speed * App.GetFrameTime();
    theBall.circle.Move(cos(theBall.ballAngle)* Factor,
                        sin(theBall.ballAngle)*Factor);

    // Convert the scores into strings.
    // This is a huge pain in the butt.
    string Result;
    ostringstream convert;
    convert << score1;
    Result = convert.str();
    score1Text.SetText(Result);
    convert << score2;
    Result = convert.str();
    score2Text.SetText(Result);

    paddle2.move(theBall,score1,App);

    //  Check the ball for collisions
    scored = theBall.checkCollision(
                           paddle1.rectangle.GetPosition().x+12.5,
                           paddle1.rectangle.GetPosition().y-37.5,
                           paddle1.rectangle.GetPosition().y+37.5,
                           paddle2.rectangle.GetPosition().x-12.5,
                           paddle2.rectangle.GetPosition().y-37.5,
                           paddle2.rectangle.GetPosition().y+37.5, App);
    if (scored > 0)
    {
        score(scored, App);
    }
}

void Game::score(int scored,sf::RenderWindow& App)
// Scores for the players
{
    if (scored == 1)
    {
        score1++;
        newRound(App);
        status.SetText("Player 1 just scored!");
    }
    else if (scored == 2)
    {
        score2++;
        newRound(App);
        status.SetText("Player 2 just scored!");
    }
}

void Game::newRound(sf::RenderWindow& App)
// Starts another round
{
    theBall.reset();
    paddle1.reset(STARTINGX1,App);
    paddle2.reset(App.GetView().GetRect().GetWidth()-40, App);
}

void Game::loadResources(sf::RenderWindow& App)
// Loads the game's resources, and  all the subclassse's resources
{
    // Load from a font file on disk
    if (!mechaBold.LoadFromFile("Mecha_Bold.ttf"))
    {
        App.Close();
        cout << "Font didn't load";
    }
    paddle1.loadResources(STARTINGX1, App);
    paddle2.loadResources(App.GetView().GetRect().GetWidth()-40, App);
    theBall.loadResources(App);
}

void Game::reset(sf::RenderWindow& App)
// Starts a new game
{
    score1 = 0;
    score2 = 0;

    player1Text.SetText("Player 1");
    player1Text.SetFont(mechaBold);
    player1Text.SetSize(18);
    player1Text.SetPosition(TEXTX1,TEXTY1);
    player2Text.SetText("Player 2");
    player2Text.SetFont(mechaBold);
    player2Text.SetSize(18);
    player2Text.SetPosition(TEXTX2,TEXTY1);
    score1Text.SetFont(mechaBold);
    score1Text.SetSize(50);
    score1Text.SetPosition(TEXTX1,TEXTY2);
    score2Text.SetFont(mechaBold);
    score2Text.SetSize(50);
    score2Text.SetPosition(TEXTX2,TEXTY2);

    status.SetPosition(App.GetView().GetRect().GetHeight()/2,App.GetView().GetRect().GetHeight() -100);
    status.SetSize(18);
    status.SetFont(mechaBold);
    status.SetText("Game reset.");

    // Convert the scores into strings.
    // This is a huge pain in the butt.
    string Result;
    ostringstream convert;
    convert << score1;
    Result = convert.str();
    score1Text.SetText(Result);
    convert << score2;
    Result = convert.str();
    score2Text.SetText(Result);

    theBall.reset();
    paddle1.reset(STARTINGX1, App);
    paddle2.reset(App.GetView().GetRect().GetWidth()-40, App);
    loadResources(App);

}

int main()
{
    // Declare the variables
    sf::Clock Clock;       // The clock
    Game theGame;    // The game with everything in it
    sf::Event Event;       // The events for the game to get
    bool direction;        // The direction of the player's paddle. True for up,
                                          // false for down.

    // Create the main rendering window
    sf::RenderWindow App(sf::VideoMode(App.GetView().GetRect().GetWidth()  , App.GetView().GetRect().GetHeight() , 32),
                         "Pong by CW");

    // Function prototypes
    void draw(sf::RenderWindow&, Game);

    theGame.reset(App);

    // Set the framerate so that it doesn't go too fast
    App.SetFramerateLimit(40);

    // Start game loop
    while (App.IsOpened())
    {
        // Process events
        while (App.GetEvent(Event))
        {
            // Close window : exit
            if (Event.Type == sf::Event::Closed)
            {
                App.Close();
            }
            else if ((Event.Key.Code == sf::Key::Up) &&
            (theGame.paddle1.rectangle.GetPosition().y > -App.GetView().GetRect().GetHeight() /2))
            {
                theGame.paddle1.rectangle.Move(0.f,
                                               -theGame.paddle1.paddleSpeed *
                                               App.GetFrameTime());
                                               cout << theGame.paddle1.rectangle.GetPosition().y << endl;
            }
            else if ((Event.Key.Code == sf::Key::Down) &&
            (theGame.paddle1.rectangle.GetPosition().y < App.GetView().GetRect().GetHeight() /2))
            {
                theGame.paddle1.rectangle.Move(0.f, theGame.paddle1.paddleSpeed*
                                               App.GetFrameTime());
            }
            else if (Event.Key.Code == sf::Key::R)
            {
                theGame.reset(App);
            }
            else if (Event.Key.Code == sf::Key::F1)
            {
                sf::Image Screen = App.Capture();
                Screen.SaveToFile("screenshot.jpg");
                theGame.status.SetText("Screenshot captured.");
            }
        }
        // Update the game
        theGame.update(App, direction);
        draw(App, theGame);
    }
    return EXIT_SUCCESS;
}

void draw(sf::RenderWindow& App, Game theGame)
// Draws all the stuff
{
    // Draw everything
    App.Clear(sf::Color(0,0,35));
    App.Draw(theGame.theBall.circle);
    App.Draw(theGame.paddle1.rectangle);
    App.Draw(theGame.paddle2.rectangle);
    App.Draw(theGame.player1Text);
    App.Draw(theGame.player2Text);
    App.Draw(theGame.score1Text);
    App.Draw(theGame.score2Text);
    App.Draw(theGame.status);
    App.Display();
}


As always, any help is greatly appreciated.
Bass gets you through in times of treble.

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Re: Pong.exe keeps crashing, C::B issue or C++ issue?
« Reply #1 on: May 17, 2012, 05:18:01 pm »
Use [code=cpp] tags please (right-upper dropdown field).

Find out with the debugger where the program crashes and see if the surrounding variables have correct values. Or use console outputs. Or minimize the code until the error becomes apparent.

But don't post such a huge code with the expectation "there's an error, find it".
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

BrainInaJar1245

  • Newbie
  • *
  • Posts: 21
    • View Profile
Re: Pong.exe keeps crashing, C::B issue or C++ issue?
« Reply #2 on: May 17, 2012, 05:49:16 pm »
Yeah, the debugger fixed it. Didn't even think of that... Oops.
Bass gets you through in times of treble.

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: Pong.exe keeps crashing, C::B issue or C++ issue?
« Reply #3 on: May 17, 2012, 05:53:52 pm »
And can you please edit your post and put the [code=cpp] tag around your code to make it more readable? :)
Laurent Gomila - SFML developer

Silvah

  • Guest
Re: Pong.exe keeps crashing, C::B issue or C++ issue?
« Reply #4 on: May 18, 2012, 02:07:24 pm »
Use [cod[i][/i]e=cpp] tags please
Use [nobbc] tags, please. It's the solution, not a workaround.
« Last Edit: May 18, 2012, 02:11:40 pm by Advocatus Diaboli »