4conq/Compete/main.cpp
szdytom 02eadae4ca
Add framework
Signed-off-by: szdytom <szdytom@qq.com>
2024-01-30 20:46:18 +08:00

98 lines
2.1 KiB
C++

#include <cstdio>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Game.h"
using namespace std;
const int BOARD_SZ = 7;
int sockfd;
void close_active_socket() {
close(sockfd);
}
int main(int argc, char **argv) {
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd == -1) {
perror("socket()");
return -1;
}
atexit(close_active_socket);
sockaddr_in addr;
memset(&addr, 0, sizeof(sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(3030);
if (bind(sockfd, (sockaddr*)&addr, sizeof(addr)) == -1) {
perror("bind()");
return -1;
}
if (listen(sockfd, 2) == -1) {
perror("listen()");
return -1;
}
FILE *logf = fopen("log.txt", "w");
setvbuf(logf, nullptr, _IONBF, 0);
GameState st(BOARD_SZ);
st.randomBoard();
fprintf(stderr, "Waiting for participants...\n");
FILE *fplayerw[2], *fplayerr[2];
for (int i = 0; i < 2; ++i) {
int playerfd = accept(sockfd, nullptr, nullptr);
if (playerfd == -1) {
perror("accept()");
return -1;
}
fplayerr[i] = fdopen(playerfd, "r");
fplayerw[i] = fdopen(dup(playerfd), "w");
fprintf(stderr, "Connected player %d.\n", i);
}
fprintf(stderr, "Starting game...\n");
auto b_str = st.boardString();
fprintf(logf, "%s\n", b_str.c_str());
for (int i = 0; i < 2; ++i) {
fprintf(fplayerw[i], "init %d\n%s", st.n, b_str.c_str());
fflush(fplayerw[i]);
}
fprintf(stderr, "Initial board sent\n");
int lstX = -1, lstY = -1;
while (st.win == -1) {
if (fprintf(fplayerw[st.cp], "getMove %d %d\n", lstX, lstY) == -1) {
perror("fprintf(getMove)");
fprintf(stderr, "Lost: %d(RPC Fail)\n", st.cp);
return -1;
}
fflush(fplayerw[st.cp]);
if (fscanf(fplayerr[st.cp], "%d %d", &lstX, &lstY) == -1) {
perror("recv(getMove)");
printf("Lost: %d(RPC Fail)\n", st.cp);
close(sockfd);
return -1;
}
fprintf(logf, "Move(%d): %d %d\n", st.cp, lstX, lstY);
if (!st.move(lstX, lstY)) {
fprintf(stderr, "Lost: %d(Invalid Move)\n", st.cp);
fclose(logf);
return -1;
}
}
fprintf(stderr, "Win: %d\n", st.win);
fclose(logf);
return 0;
}