This commit is contained in:
Andrew Haynes
2026-02-24 16:01:56 -05:00
commit 6b17d9c501
8 changed files with 261 additions and 0 deletions
+84
View File
@@ -0,0 +1,84 @@
#include "graphics.hpp"
#include <SFML/Window/Keyboard.hpp>
#include "globals.hpp"
Paddle p1 { { (TILESIZE * 2) - SIZE_X, POS_Y } };
Paddle p2 { { WIDTH - (TILESIZE * 2), POS_Y } };
Ball ball { { (WIDTH / 2) - (3.0f / 2), (HEIGHT / 2) - (3.0f / 2) } };
void
check_and_move()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W))
{
if (p1.rect.getPosition().y - VELOCITY > 0)
{
p1.rect.setPosition(
{ p1.rect.getPosition().x,
p1.rect.getPosition().y - VELOCITY });
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S))
{
if (p1.rect.getPosition().y + VELOCITY + SIZE_Y < HEIGHT)
{
p1.rect.setPosition(
{ p1.rect.getPosition().x,
p1.rect.getPosition().y + VELOCITY });
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up))
{
if (p2.rect.getPosition().y - VELOCITY > 0)
{
p2.rect.setPosition(
{ p2.rect.getPosition().x,
p2.rect.getPosition().y - VELOCITY });
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down))
{
if (p2.rect.getPosition().y + VELOCITY + SIZE_Y < HEIGHT)
{
p2.rect.setPosition(
{ p2.rect.getPosition().x,
p2.rect.getPosition().y + VELOCITY });
}
}
}
void
handle_ball()
{
if (ball.object.getPosition().y <= 0 ||
ball.object.getPosition().y >= HEIGHT - ball.object.getSize().y)
{
ball.velocity.y *= -1;
}
if (ball.object.getPosition().x <= 0)
{
ball.object.setPosition(
{ (WIDTH / 2) - (3.0f / 2), (HEIGHT / 2) - (3.0f / 2) });
p2.points++;
}
if (ball.object.getPosition().x >= WIDTH - ball.object.getSize().x)
{
ball.object.setPosition(
{ (WIDTH / 2) - (3.0f / 2), (HEIGHT / 2) - (3.0f / 2) });
p1.points++;
}
if (ball.object.getGlobalBounds().findIntersection(
p1.rect.getGlobalBounds()) ||
ball.object.getGlobalBounds().findIntersection(
p2.rect.getGlobalBounds()))
{
ball.velocity.x *= -1;
}
ball.object.move({ ball.velocity });
}
+43
View File
@@ -0,0 +1,43 @@
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <format>
#include "globals.hpp"
#include "graphics.hpp"
int
main()
{
sf::RenderWindow window(sf::VideoMode({ (int)WIDTH, (int)HEIGHT }),
"Pong", sf::Style::Default);
window.setFramerateLimit(FPS);
sf::Font font("../assets/pixel.ttf");
sf::Text text(font, "test");
text.setCharacterSize(16);
text.setPosition({ WIDTH / 4 + TILESIZE / 1.5, TILESIZE });
while (window.isOpen())
{
text.setString(std::format("P1: {} : P2: {}", p1.points, p2.points));
window.clear(sf::Color::Black);
while (const std::optional event = window.pollEvent())
{
if (event->is<sf::Event::Closed>())
{
window.close();
}
}
check_and_move();
handle_ball();
window.draw(p1.rect);
window.draw(p2.rect);
window.draw(ball.object);
window.draw(text);
window.display();
}
return 0;
}