Skip to content
Snippets Groups Projects
server_main.cpp 2.38 KiB
Newer Older
#include "game.hpp"
#include "player.hpp"
#include "server.hpp"
#include <arpa/inet.h>
#include <iostream>
#include <map>
#include <netinet/ip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wordle-de.pb.h>

std::map<std::string, Player *> players;

void connected(uint16_t fd) { std::cout << "Connected" << std::endl; }
void disconnected(uint16_t fd) { std::cout << "Disconnected" << std::endl; }
void received(uint16_t fd, char *buffer) {

  wordle_de::Message msg;
  msg.ParseFromString(buffer);

  switch (msg.msg_case()) {
  case wordle_de::Message::kLogin: {
    auto login = msg.mutable_login();
    std::cout << "Received Login" << std::endl;
    std::string username = login->username();
    std::string password = login->password();
    std::cout << "Username: " << username << ", Password: " << password
              << std::endl;
    // check if player is registered
    if (players.contains(username)) {
      std::cout << "player known" << std::endl;
      auto player = players.at(username);
      // authenticate player
      if (player->authenticate(password)) {
        std::cout << "Player '" << username << "' authenticated" << std::endl;
      } else {
        std::cout << "wrong password" << std::endl;
      }
    }
    auto player = new Player(username, password);
    players[username] = player;
    break;
  }
  case wordle_de::Message::kGuess: {
    if (!msg.has_guess()) {
      throw "malformed message";
    }
    auto guess = msg.guess();
    std::cout << "Received Guess: " << guess.guess() << std::endl;
    break;
  }
  case wordle_de::Message::kGameState:
    break;
  case wordle_de::Message::MSG_NOT_SET:
    break;
  }
}

int main(void) {
  GOOGLE_PROTOBUF_VERIFY_VERSION;
  auto srv = Server();
  srv.onConnect(connected);
  srv.onDisconnect(disconnected);
  srv.onInput(received);
  std::cout << "Run..." << std::endl;
  srv.init();
  while (true) {
    srv.run();
  }
  std::string word = "Hello";
  std::string guess = "hello";
  auto s = GameState();
  s.setWord(word);
  auto res = s.guess(guess);
  printf("Word: %s\n", word.c_str());
  printf("Guess: %s\n", guess.c_str());
  for (const auto &r : res) {
    switch (r) {
    case GameState::NO_MATCH:
      printf("X");
      break;
    case GameState::MATCH:
      printf("m");
      break;
    case GameState::EXACT_MATCH:
      printf("M");
      break;
    }
  }
  printf("\n");
  return 0;
}