# Pong game in C++ SFML

This is my first game, I need to know how I could improve this code:

main.cpp

#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
#include <sstream>
#include <math.h>

int main()
{

const int screenX = 600;
const int screenY = 400;
float ballSpeed = 400.f;
float ballAngle = 75.f;
sf::Vector2f velocity;

sf::RenderWindow window(sf::VideoMode(screenX,screenY), "Pong", sf::Style::Titlebar | sf::Style::Close);

window.setVerticalSyncEnabled(true);

sf::RectangleShape topBorder;
topBorder.setPosition(0, 0);

sf::RectangleShape botBorder;

sf::Font font;

return EXIT_FAILURE;

//bool Sound;

sf::SoundBuffer bufferScore;
sf::Sound soundScore;
soundScore.setBuffer(bufferScore);

sf::SoundBuffer bufferWall;
sf::Sound soundWall;
soundWall.setBuffer(bufferWall);

int intScore1 = 0;
sf::Text textScore1;
std::string strScore1 = std::to_string(intScore1);
textScore1.setString(strScore1);
textScore1.setFont(font);
textScore1.setPosition(sf::Vector2f(screenX/5.f, 0.f));

int intScore2 = 0;
sf::Text textScore2;
std::string strScore2 = std::to_string(intScore2);
textScore2.setString(strScore2);
textScore2.setFont(font);
textScore2.setPosition(sf::Vector2f(365.f, 0.f));

//add sf::VertexArray, dashed line splitting map into 2

sf::Vertex line[] =
{
sf::Vertex(sf::Vector2f(screenX/2+1,0)),
sf::Vertex(sf::Vector2f(screenX/2+1,screenY))
};

ball.setPointCount(10);
ball.setFillColor(sf::Color::White);
ball.setPosition(sf::Vector2f(screenX/2.f, screenY/2.f));

//run prog as long as the window is open
sf::Clock clock;
bool Playing = false;
while (window.isOpen())
{
if (Playing)
{
float deltaTime = clock.restart().asSeconds();
float factor = deltaTime * ballSpeed;
velocity.x = std::cos(ballAngle)*factor;
velocity.y = std::sin(ballAngle)*factor;

ball.move(velocity.x, velocity.y);

{
ball.move(-ball.move);
velocity.x = -(velocity.x);
ballSpeed = -ballSpeed;
ballAngle = -ballAngle;
}

if (ball.getGlobalBounds().intersects(topBorder.getGlobalBounds()) || ball.getGlobalBounds().intersects(botBorder.getGlobalBounds()))
{
velocity.x = -velocity.x;
ballAngle = -ballAngle;
soundWall.play();
}

if ((sf::Keyboard::isKeyPressed(sf::Keyboard::W)) && !(paddle1.getGlobalBounds().intersects(topBorder.getGlobalBounds()))) //only move up if not touching top border

{
intScore1++;
strScore1 = std::to_string(intScore1);
textScore1.setString(strScore1);
ball.setPosition(sf::Vector2f(screenX / 2, screenY / 2));
soundScore.play();
}

{
intScore2++;
strScore2 = std::to_string(intScore2);
textScore2.setString(strScore2);
ball.setPosition(sf::Vector2f(screenX/2, screenY/2));
soundScore.play();
}

window.clear(sf::Color::Black);
window.draw(ball);
window.draw(topBorder);
window.draw(botBorder);
window.draw(line, 2, sf::Lines);
window.draw(textScore1);
window.draw(textScore2);
window.display();
}

if (!Playing)
{
window.clear(sf::Color::Black);
window.display();
}

//check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{

//"close requested" event: we close the window

switch (event.type)
{
case sf::Event::Closed:
window.close();

case sf::Event::KeyPressed:
switch (event.key.code)
case sf::Keyboard::Escape:
Playing = false;
break;

switch (event.key.code)
{
case sf::Keyboard::Up:
case sf::Keyboard::W:
break;
case sf::Keyboard::Down:
case sf::Keyboard::S:
break;

case sf::Keyboard::Return:
{
case 0:
Playing = true;
break;
case 1:
break;
case 2:
window.close();
break;
}
break;
}
break;
}

}

}
return EXIT_SUCCESS;
}


#pragma once
#include <SFML/Graphics.hpp>

#define MAX_NUMBER_ITEMS 3

{
public:

void draw(sf::RenderWindow &window);
void MoveUp();
void MoveDown();
int GetPressedItem() { return selectecItemIndex; }

private:
int selectecItemIndex;
sf::Font font;
};


#include "Menu.h"

{
{  }

selectecItemIndex = 0;
}

{
}

{
for (int i = 0; i < MAX_NUMBER_ITEMS; i++)
{
}
}

{
if (selectecItemIndex - 1 >= 0)
{
selectecItemIndex--;
}
}

{
if (selectecItemIndex + 1 < MAX_NUMBER_ITEMS)
{
selectecItemIndex++;
}
}


Note I'm not quite sure of all the technical details of the menu class as it came from a slightly advanced tutorial, I'll need to go into classes in greater detail.

I just want to say that your code is very readable and understandable!

## Things you could do better:

### Indentation

The function and class definitions are not indented when they should be. I know it means that most of the code would be indented, but it adds to the readability, so please do it.

How this helps you:
It lets you separate functions more easily and lets you be able to tell wether a chunk of code is inside or outside a function.

### Classes (MOST IMPORTANT)

You have too many game objects that are hard-coded in. Make a class for each: (in separate files of course)

• Wall
• Ball

How this helps you:
Classes add code reusability. Say you wanted to reuse your current code to make a four-player pong game (yes that exists). At the moment, you’d need to hard-code every paddle one by one. With classes, you could just add two paddles and that’s about it.

### Vector

C++ programmers tend to prefer using std::vectors over c style arrays.
In the Menu class, use std::vector<sf::Text> menu; instead of sf::text menu[MAX_NUMBER_ITEMS]; so you can push menu items to it instead of putting the index of each one. Make its constructor use an std::vector<sf::Text> so you can customize it within main. Put the settings of the menu items (Font, FillColor, and Position) in a for loop and then set the first item’s special color.

How this helps you:
Say you wanted to make another menu that is used like your first menu. You could copy & paste the original menu to create a new SubMenu1 class, but that’s a big no-no in programming. Instead, you could make menu and subMenus[0] both instances of the Menu class.

### Empty conditional blocks

In your code I’ve seen many statement like:

if (!font.loadFromFile("pong.ttf"))
{  }


They serve no purpose. Just write:

font.loadFromFile("pong.ttf");


(Unless you’re going to do something like throw an error or exit.)

How this helps you:
It literally just removes bloat.

## Things I congratulate you for getting right:

### Constants

There aren’t too many magic numbers (unnamed constants), which really helps people who want to jump in the middle of your code and still be able to understand what it does.

How this helps you:
If you abandon a project for a while (say a month), you forget what some pieces of code do. Using variable names to identify constants helps your mind understand what’s going on.

You game runs at whatever fps the computer is ready to run at.

How this helps you:
People with slow computers will be able to play the game at a normal speed, just at a lower fps.

1. You shouldn't include math.h, but should include cmath instead. math.h is a C header while cmath is a C++ header (with ultimately about the same content). I am somewhat astonished that your current code compiles, as you use std::cos and std::sin while the math.h is only guaranteed to put its definitions into the global namespace (cmath guarantees them in the std:: namespace).
2. As a good practice, you should order your includes alphabetically and group them into sets belonging to each other. Preferably, include the header the current file implements first (i.e A.h in A.cpp), then all headers from the project you're working on, then all headers from other projects, libraries etc. and finally the headers from the standard library. This will facilitate checks of include-correctness.
3. Speaking of headers, you're actually missing an include in main.cpp, the include for EXIT_SUCCESS which is cstdlib. However, in my opinion writing return 0; or omitting the return at the end of main are totally fine, so you could do without the macro and the include.
4. Don't use defines for constants, just declare your constants as variables. Defines are all kinds of bad, so it's better to use them as little as possible.
5. You don't need to declare and define a constructor if it doesn't do anything special.
6. Adding directly to what @BenjaminPhilippe said in his answer, you do not only need more classes, you also need to structure your code more. Currently, your main function is doing way too much. You should introduce more functions and classes to improve your code structure, make testing and debugging easier and increase reusability.
7. Disclaimer: I don't actually know anything at all about SFML. If SFML doesn't provide any callback capabilities, ignore this point.

Polling for key events is usually not sustainable. Even in your little case, key event handling is quite a mess (including nested switch-cases). You should instead register callbacks for each key event that change some state variables somewhere (often, these variables are globals, which isn't exactly great either, but still better than drowning in a switch-case mess) and use those state variables for determining what to do.

8. Why is Playing in main capitalized? All other variables seem to start with a lowercase letter, so you should be consistent and stick with playing.

# Conclusion

Overall, your code is not bad. The thing that bothers me the most is lack of structure, which is the core issue you should attack. I didn't spot anything that would require immediate intervention, such as UB (except for your includes, maybe), which is a great sign that your code is pretty good.