Skip to content
Snippets Groups Projects
battleship.cpp 1.48 KiB
Newer Older
#include <ncurses.h>
#include <iostream>
#include <csignal>
#include <cstdlib>
#include <time.h>

#include "board.h"
#include "networking.h"
#include "util.h"

connection *c;

// Stop the terminal from freaking out when the program is exited
// Even if other stuff isn't cleaned up, the terminal will
// still be useable
void cleanup_screen(int signum) {
  destroy_screen();
  
  delete c;
  
  exit(signum);
}

int main(int argc, char *argv[]) {
  srand(time(NULL));
  
  init_screen();
  
  signal(SIGINT, cleanup_screen);
  signal(SIGTERM, cleanup_screen);
  signal(SIGSEGV, cleanup_screen);
  
  mvprintw(0, 0, "Client or server?");
  mvprintw(1, 0, "1) Server");
  mvprintw(2, 0, "2) Client");
  
  int key = getch();
  while (!(key == '1' || key == '2')) key = getch();
    
  if (key == '1') {
    c = new server_connection;
  } else {
    c = new client_connection;
  }
  
  board player_board(PLAYER);
  std::string opponent_board_desc = c->exchange_message(player_board.get_description());
  board opponent_board(OPPONENT, opponent_board_desc);
  
  clear();
  player_board.draw();
  opponent_board.draw();
  
  while(!player_board.has_lost() && !opponent_board.has_lost()) {
    std::string move = opponent_board.get_move();
    std::string opponent_move = c->exchange_message(move);
    
    player_board.make_move(opponent_move);
    opponent_board.make_move(move);
    
    player_board.draw();
    opponent_board.draw();
    
    usleep(1000000);
  }
  
  getch();
  
  destroy_screen();
  delete c;
}