#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <cstdio>
#include <cstdlib>
int randInRange(int max) {
double r, x;
r = ((double)rand() / ((double)(RAND_MAX) + (double)(1)));
x = (r * (max + 1));
return (int)x;
}
void printRAM(char* str) {
std::vector<int> ram;
for (int offset = 0; offset < 128; offset++) {
char buffer[16];
buffer[0] = str[offset * 2];
buffer[1] = str[offset * 2 + 1];
buffer[2] = 0;
int value = strtol(buffer, NULL, 16);
ram.push_back(value);
}
const bool printRAM = false;
if (printRAM)
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 16; col++)
fprintf(stdout, "%2x ", ram[col + row * 16]);
fprintf(stdout, "\n");
}
}
bool readData(FILE* alePipe) {
char buffer[65535];
fgets(buffer, sizeof(buffer), alePipe);
char* endRAM = strchr(buffer, ':');
printRAM(buffer);
bool terminal = (endRAM[1] == '1');
int reward = strtol(&endRAM[3], NULL, 10);
if (reward != 0)
std::cout << "Reward: " << reward << std::endl;
return terminal;
}
void agentMain(FILE* alePipe) {
char buffer[1024];
fgets(buffer, sizeof(buffer), alePipe);
std::cout << "ALE says: " << buffer << std::endl;
fputs("0,1,0,1\n", alePipe);
int frameNumber = 0;
while (true) {
bool terminal = readData(alePipe);
frameNumber++;
if (terminal)
break;
fprintf(alePipe, "%d,%d\n", randInRange(17), 18);
}
std::cout << "Episode lasted " << frameNumber << " frames" << std::endl;
}
int main(int argc, char** argv) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " rom_file" << std::endl;
std::cerr
<< "Note: This example must be run from the same directory as the ALE "
"executable ('ale')."
<< std::endl;
return 1;
}
std::string romFile(argv[1]);
std::string aleCmd("./ale -game_controller fifo ");
aleCmd += romFile;
FILE* alePipe = popen(aleCmd.c_str(), "r+");
agentMain(alePipe);
pclose(alePipe);
}