//=============================================================================

#include "board.h"
#include "computer_first.h"
#include "computer_random.h"
#include "human.h"
#include "move.h"
#include <array>
#include <iostream>
#include <string>
using std::array;
using std::cin;
using std::cout;
//using std::getline;
using std::string;

//-----------------------------------------------------------------------------
// Globale Spieler sind nur eine Notloesung.
// Eigentlich muessten die Spieler dynamisch auf dem Heap angelegt werden.
// Aber das haben wir in der Vorlesung nicht geschafft.
// Darum diese Notloesung.

array<human, 2> plh{ human{ "Mensch-1", color::white }, human{ "Mensch-2", color::black } };
array<computer_first, 2> plcf{ computer_first{ "FirstField-1", color::white }, computer_first{ "FirstField-2", color::black } };
array<computer_random, 2> plcr{ computer_random{ "Random-1", color::white }, computer_random{ "Random-2", color::black } };

player& define_player(color c)
{
   static_assert(static_cast<int>(color::white) == 0);
   static_assert(static_cast<int>(color::black) == 1);
   int no = static_cast<int>(c);

   cout << "Definieren Sie Spieler " << (no+1) << " fuer " << c << '\n';
   cout << "- m : Mensch\n- e : Erstes Feld\n- z : Zufall\n";

   for (string in;;)
   {
      cout << "> ";
      getline(cin, in);
      if (in.empty()) continue;
      cout << '\n';
      switch (in[0])
      {
      case 'm':
         return plh[no];
      case 'e':
         return plcf[no];
      case 'z':
         return plcr[no];
      }
   }
}

//-----------------------------------------------------------------------------

bool play(board& b, player& pl)
{
   move m = pl.next(b);
   cout << '\n' << pl << " macht Zug: " << m << "\n\n";

   b.set(m);
   cout << b;

   if (b.wins(pl.get_color()))
   {
      cout << '\n' << pl << " hat gewonnen\n";
      return true;
   }
   if (b.full())
   {
      cout << "\nDas Spiel ist remis ausgegangen\n";
      return true;
   }
   return false;
}

//-----------------------------------------------------------------------------

int main()
{
   cout << "Aufg_17_02_Tic_Tac_Toe_3\n\n";

   board b;
   player& pl1 = define_player(color::white);
   player& pl2 = define_player(color::black);

   cout << b;
   for (;;)
   {
      if (play(b, pl1)) break;
      if (play(b, pl2)) break;
   }
}
