#include #include #include #include #include tile_t *_BOARD; int _ROWS; int _COLLUMS; char _TOKEN1; char _TOKEN2; void setRows(int rows) { _ROWS = rows; } void setCollums(int collums) { _COLLUMS = collums; } void setDimension(int rows, int collums) { setRows(rows); setCollums(collums); } void setTokens(char t1, char t2) { _TOKEN1 = t1; _TOKEN2 = t2; } int getIndex(int i, int j) { return i * _COLLUMS + j; } int checkLine(int pos, int delta) { int count = 1, i; i = pos - delta; while (isValid(i) && _BOARD[pos] == _BOARD[i]) { count++; i -= delta; } i = pos + delta; while (isValid(i) && _BOARD[pos] == _BOARD[i]) { count++; i += delta; } return count >= 4; } // checks _BOARD for a win // returns player id on win, otherwise -1 int checkWin(int pos) { int result = checkLine(pos, ORIZONTAL); if (result) { return _BOARD[pos] - 1; } result = checkLine(pos, VERTICAL); if (result) { return _BOARD[pos] - 1; } result = checkLine(pos, DIAGONAL); if (result) { return _BOARD[pos] - 1; } result = checkLine(pos, DIAGONAL_INV); if (result) { return _BOARD[pos] - 1; } return -1; } int checkWinAll(){ for (int i=0; i <_ROWS *_COLLUMS; i++) { if (checkWin(i) != EMPTY) { return checkWin(i); } } return EMPTY; } void printBoard() { if (CLEAR) { system("clear"); } for (int i=0; i < _ROWS; i++) { printf("|"); for (int j=0; j < _COLLUMS; j++) { printf(" "); printTile(_BOARD[getIndex(i, j)]); printf(" "); } printf("|\n"); } for (int i=0; i<_COLLUMS; i++) { printf("---"); } printf("--\n"); } void printTile(tile_t t) { switch(t) { case EMPTY: printf(" "); break; case PLAYER1: printf("\033[94m%c\033[39m", _TOKEN1); break; case PLAYER2: printf("\033[91m%c\033[39m", _TOKEN2); break; } } // ritorna la posizione in cui il giocatore potra iserire la sua mossa int checkMove(int collums) { if (collums < 0 || collums >= _COLLUMS) { char buf[100]; sprintf(buf, "the collums must be between 1 and %d", _COLLUMS); warningMsg(buf); return -1; } if (_BOARD[collums] != EMPTY) { char buf[100]; sprintf(buf, "the collum %d is full", collums + 1); warningMsg(buf); return -1; } int pos = collums; while (isValid(pos + VERTICAL) && _BOARD[pos + VERTICAL] == EMPTY) { pos += VERTICAL; } return pos; } void insertMove(int pos, int turn) { printf("playing %d in %d\n", (turn == 0) ? PLAYER1 : PLAYER2, pos); _BOARD[pos] = (turn == 0) ? PLAYER1 : PLAYER2; } int isValid(int pos) { return pos >= 0 && pos < _ROWS * _COLLUMS; }