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

85 lines
2.2 KiB
C++

9 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) || pad2.getRect().CheckCollision(ball.pos, ball.radius)) {
ball.vel.x = ball.vel.x * (-1);
}
if (ball.pos.x + ball.radius >= window.GetWidth()) {
pad1.incrementPoints();
ball.pos = raylib::Vector2(window.GetWidth() / 2, window.GetHeight() / 2);
}
if (ball.pos.x - ball.radius <= 0) {
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()) {
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;
}