From 6ad56fb9effee199d130186c13f5b39f770429ab Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Fri, 23 Feb 2024 11:16:21 -0500 Subject: [PATCH] Started working on client-server communication; so far, I can send the position of client to server, and vice-versa --- main.cpp | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/main.cpp b/main.cpp index 176894d..bef06a8 100644 --- a/main.cpp +++ b/main.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include "includes/raylib-cpp/raylib-cpp.hpp" #include "includes/paddle.hpp" #include "includes/ball.hpp" @@ -191,14 +192,17 @@ int main(int argc, char** argv) { SetTraceLogLevel(LOG_NONE); raylib::Window window = raylib::Window(WIDTH, HEIGHT, "Pong"); window.ClearBackground(BLACK); - SetTargetFPS(60); + SetTargetFPS(5); SetExitKey(KEY_Q); std::string points_str = std::string("0\t\t0"); bool game_started = false; srand(std::time(NULL)); - /* Variable to store the response given by the other player */ + /* Variables to store the response given by the other player */ std::string response; + std::istringstream response_stream; + /* Vector to store peer paddle position */ + raylib::Vector2 peer_pos; /* Instantiate Paddle and Ball objects */ Paddle pad1 = Paddle(10, (HEIGHT / 2) - (RECT_H / 2), RECT_W, RECT_H); @@ -233,15 +237,26 @@ int main(int argc, char** argv) { } if (game_started) { - /* Receive response from the other machine, if the game is in multiplayer mode */ - response = ""; - if (type.mode != M_SINGLE) { - #ifdef DEBUG - response = ""; - #else - std::string response = type.netsock->recvAll(); - #endif + + /* Make the players send their position to the other player (The server provides authoritative information on the position of the ball. + The 'P' here indicates that this line provides paddle information. */ + if (type.mode == M_SERVER) { + type.netsock->sendAll("P" + std::to_string(pad1.getRect().x) + " " + std::to_string(pad1.getRect().y)); + } + if (type.mode == M_CLIENT) { + type.netsock->sendAll("P" + std::to_string(pad2.getRect().x) + " " + std::to_string(pad2.getRect().y)); + } + + /* Create a stream from the response of the server, and use that to create the vector of peer position */ + response = type.netsock->recvAll(); + if (response[0] == 'P') { + /* Create a stream, excluding the first character */ + response_stream = std::istringstream(response.substr(1)); + response_stream >> peer_pos.x >> peer_pos.y; + std::cout << "X position of peer is: " << peer_pos.x << " Y position is: " << peer_pos.y << std::endl; } + + /* When updating the paddle positions, update the peer paddle's positions based on the vector set earlier */ std::string to_send = ""; /* Update paddle velocity */