You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
netpong/main.cpp

91 lines
2.6 KiB
C++

11 months ago
#include <iostream>
#include <raylib-cpp.hpp>
#include "paddle.hpp"
#include "ball.hpp"
int main() {
/* Initialize variables used to instantiate structs*/
const int WIDTH = 600;
const int HEIGHT = 480;
const int RECT_H = HEIGHT / 3;
const int RECT_W = 30;
const int CIRC_RAD = 10;
/* Initialize window */
raylib::Window window = raylib::Window(WIDTH, HEIGHT, "Pong");
SetTraceLogLevel(LOG_INFO);
window.ClearBackground(BLACK);
SetTargetFPS(60);
SetExitKey(KEY_Q);
/* Instantiate Paddle and Ball objects */
Paddle pad1 = Paddle(10, 10, RECT_W, RECT_H);
Paddle pad2 = Paddle(window.GetWidth() - RECT_W - 10, 10, RECT_W, RECT_H);
Ball ball = Ball(window.GetWidth()/2, window.GetHeight()/2, CIRC_RAD, 3, 3);
window.BeginDrawing();
pad1.draw();
pad2.draw();
ball.draw();
/* Main loop */
while (!window.ShouldClose()) {
/* Update paddle velocity */
if (IsKeyPressed(KEY_S)) {
pad1.velocity.y = 5; /* Set positive (downward) velocity, since (0,0) is top-left */
}
if (IsKeyPressed(KEY_W)) {
pad1.velocity.y = -5; /* Set negative (upward) velocity */
}
if (IsKeyReleased(KEY_S) || IsKeyReleased(KEY_W)) {
pad1.velocity.y = 0;
}
if (IsKeyPressed(KEY_UP)) {
pad2.velocity.y = -5;
}
if (IsKeyPressed(KEY_DOWN)) {
pad2.velocity.y = 5;
}
if (IsKeyReleased(KEY_UP) || IsKeyReleased(KEY_DOWN)) {
pad2.velocity.y = 0;
}
/* Update ball velocity based on collision detection */
if (pad1.getRect().CheckCollision(ball.pos, ball.radius)) { /* Collision with paddle 1 */
11 months ago
ball.vel.x = ball.vel.x * (-1);
ball.pos.x = pad1.getRect().x + pad1.getRect().GetWidth() + ball.radius + 1; /* Ensuring that the ball doesn't get stuck inside the paddle */
11 months ago
}
if (pad2.getRect().CheckCollision(ball.pos, ball.radius)) { /* Collision with paddle 2 */
ball.vel.x = ball.vel.x * (-1);
ball.pos.x = pad2.getRect().x - ball.radius - 1;
}
if (ball.pos.x + ball.radius >= window.GetWidth()) { /* Collision with right wall */
11 months ago
pad1.incrementPoints();
ball.pos = raylib::Vector2(window.GetWidth() / 2, window.GetHeight() / 2);
}
if (ball.pos.x - ball.radius <= 0) { /* Collision with left wall */
11 months ago
pad2.incrementPoints();
ball.pos = raylib::Vector2(window.GetWidth() / 2, window.GetHeight() / 2);
}
if (ball.pos.y - ball.radius <= 0 || ball.pos.y + ball.radius >= window.GetHeight()) { /* Collision with top and bottom wals */
11 months ago
ball.vel.y = ball.vel.y * -1;
}
/* Draw objects */
window.BeginDrawing();
window.ClearBackground(BLACK);
pad1.draw();
pad2.draw();
ball.draw();
window.EndDrawing();
}
window.Close();
return 0;
}