cmpsc330hw5/main.cxx

90 lines
2.3 KiB
C++
Raw Permalink Normal View History

2024-12-06 22:31:01 +00:00
#include <iostream>
#include <fstream>
#include <assert.h>
2024-12-06 22:06:18 +00:00
#include <vector>
2024-12-06 22:31:01 +00:00
#include "common.h"
#include "board.h"
2024-12-06 22:06:18 +00:00
#include "player.h"
using namespace std;
#include <unistd.h> // usleep()
#include <dlfcn.h>
2024-12-06 22:31:01 +00:00
string GameMaster(const vector<string>& libpaths, vector<int>& scores, vector<double>& timespents, double sleep_sec);
2024-12-06 22:06:18 +00:00
void CloseLibs();
2024-12-06 22:31:01 +00:00
int main(int argc, char* argv[])
{
2024-12-06 22:06:18 +00:00
// argv[0] : program name
// argv[1] : 1st player library path
// argv[2] : 2nd player library path
// argv[3] : 3rd player library path
2024-12-06 22:31:01 +00:00
if(argc <= 2)
2024-12-06 22:06:18 +00:00
return 0;
vector<string> libpaths;
2024-12-06 22:31:01 +00:00
vector<int> scores;
2024-12-06 22:06:18 +00:00
vector<double> timespents;
2024-12-06 22:31:01 +00:00
for(int i=1; i<argc; i++)
{
2024-12-06 22:06:18 +00:00
libpaths.push_back(argv[i]);
scores.push_back(0);
timespents.push_back(0);
}
double sleep_sec = 0.00;
string result = GameMaster(libpaths, scores, timespents, sleep_sec);
CloseLibs();
}
2024-12-06 22:31:01 +00:00
void ClearConsole()
{
2024-12-06 22:06:18 +00:00
system("clear");
}
2024-12-06 22:31:01 +00:00
void SleepInSec(double sleep_sec)
{
2024-12-06 22:06:18 +00:00
int sleep_microsecond = sleep_sec * 1000000;
usleep(sleep_microsecond);
}
2024-12-06 22:31:01 +00:00
vector<void*> lst_player_libhandle;
typedef IPlayer* (*CreatePlayerType)();
2024-12-06 22:06:18 +00:00
string LoadPlayer
2024-12-06 22:31:01 +00:00
( IPlayer*& iplayer
, string libpath
, int board_rows // the size of board (including dots, lines, and boxes)
, int board_cols // the size of board (including dots, lines, and boxes)
, char box_type // the character for the player's boxes
, char line_type // the character for the player's lines
)
{
void* player_libhandle = dlopen(libpath.c_str(), RTLD_LAZY);
if(player_libhandle == nullptr)
{
2024-12-06 22:06:18 +00:00
return "cannot load " + libpath;
}
lst_player_libhandle.push_back(player_libhandle);
2024-12-06 22:31:01 +00:00
void* pfunc = dlsym(player_libhandle, "PlayerFactory");
if(pfunc == nullptr)
{
2024-12-06 22:06:18 +00:00
return "cannot find PlayerFactory() function defined as extern C";
}
2024-12-06 22:31:01 +00:00
CreatePlayerType CreatePlayer = (CreatePlayerType)pfunc;
2024-12-06 22:06:18 +00:00
iplayer = CreatePlayer();
iplayer->Init(board_rows, board_cols, box_type, line_type);
2024-12-06 22:31:01 +00:00
if(iplayer == nullptr)
{
2024-12-06 22:06:18 +00:00
return "cannot create player using PlayerFactory() function";
}
return "";
}
2024-12-06 22:31:01 +00:00
void CloseLibs()
{
for(void* player_libhandle : lst_player_libhandle)
2024-12-06 22:06:18 +00:00
dlclose(player_libhandle);
lst_player_libhandle.clear();
}