Complete most of networked tick-tac-toe. Finish the questions to ponder!

This commit is contained in:
2026-03-18 13:01:42 +00:00
parent 212119adac
commit 1b07a4e414
6 changed files with 77 additions and 12 deletions

View File

@@ -12,7 +12,7 @@
// A thourough rework is necessary for SFML 3.0.
enum GameMessageType : unsigned char {
JOIN_GAME = 0x01, PLACE_TOKEN = 0x02
JOIN_GAME = 0x01, PLACE_TOKEN = 0x02, START_GAME = 0x03, GAME_OVER = 0x04
};
enum Token : unsigned char {
@@ -24,13 +24,26 @@ public:
GameServer(unsigned short tcp_port) :
m_tcp_port(tcp_port) {}
bool send_start_game_to_clients() {
char buf[1] = { START_GAME };
std::cout << "Starting the game..." << std::endl;
return broadcast_message(buf, nullptr);
}
bool send_game_over_to_clients() {
char buf[1] = { GAME_OVER };
std::cout << "Game Over!" << std::endl;
return broadcast_message(buf, nullptr);
}
// Binds to a port and then loops around. For every client that connects,
// we start a new thread receiving their messages.
void tcp_start()
{
// BINDING
sf::TcpListener listener;
sf::Socket::Status status = listener.listen(m_tcp_port, sf::IpAddress("A.B.C.D"));
sf::Socket::Status status = listener.listen(m_tcp_port, sf::IpAddress("152.105.66.120")); // Make sure to change this!
if (status != sf::Socket::Status::Done)
{
std::cerr << "Error binding listener to port" << std::endl;
@@ -71,6 +84,10 @@ public:
// Slight pause to ensure the all threads have started
// --------------------------------------------------------------
std::this_thread::sleep_for(std::chrono::milliseconds(250));
if(!send_start_game_to_clients()) {
std::cerr << "Could not start game. One or both players did not recieve START_GAME" << std::endl;
}
}
}
}
@@ -79,11 +96,12 @@ public:
// The connection is closed automatically when the listener object is out of scope.
}
private:
unsigned short m_tcp_port;
unsigned short m_player_count { 0 };
unsigned short m_turns_played { 0 };
int board[3][3];
std::vector<sf::TcpSocket*> m_clients;
std::mutex m_clients_mutex;
@@ -144,6 +162,12 @@ private:
debug_message(payload);
broadcast_message(payload, client);
std::this_thread::sleep_for(std::chrono::milliseconds(250));
if(++m_turns_played == 9) {
send_game_over_to_clients();
}
}
}
@@ -194,6 +218,8 @@ private:
switch(messageType) {
case JOIN_GAME: return 2;
case PLACE_TOKEN: return sizeof(int) * 2 + 2;
case START_GAME: return 1;
case GAME_OVER: return 1;
default: return 0;
}
}
@@ -222,7 +248,7 @@ private:
int main()
{
GameServer server(4300);
GameServer server(4331);
server.tcp_start();