void applyMove(node* move,char boardIn[BOARDROWS][BOARDCOLS]){ char tempBoard[BOARDROWS][BOARDCOLS]; copyBoard(boardIn,tempBoard); char movedPiece = tempBoard[move->origin.y][move->origin.x]; if (move->origin.x != move->jumpDest.x){ //if moving piece to the right or left if(move->origin.x < move->jumpDest.x){//moving the piece right for (int i = move->origin.x;i<move->jumpDest.x;i++){ tempBoard[move->origin.y][i] = 'O'; } }else{//moving the piece left for (int i = move->origin.x;i>move->jumpDest.x;i--){ tempBoard[move->origin.y][i] = 'O'; } } }else{//moving the piece up or down if(move->origin.y < move->jumpDest.y){//moving the piece down for (int i = move->origin.y;i<move->jumpDest.y;i++){ tempBoard[i][move->origin.x] = 'O'; } }else{//moving the piece up for (int i = move->origin.y;i>move->jumpDest.y;i--){ tempBoard[i][move->origin.x] = 'O'; } } } tempBoard[move->jumpDest.y][move->jumpDest.x] = movedPiece; copyBoard(tempBoard,boardIn); }
treeNode* myTree(treeNode *head,char inBoard[BOARDROWS][BOARDCOLS],char pColour, char cColour){ char boardHolder[BOARDROWS][BOARDCOLS]; int numChildren; node* ptr; if (head->board[0][0] != 'W' && head->board[0][0] != 'B' && head->board[0][0] != 'O' ){ copyBoard(inBoard,head->board); } if (head->numChildren == 0){ node* moves = getMoves(head->board,cColour,pColour); numChildren = getListSize(moves); head->numChildren = numChildren; //printf("Generated %i moves from the head node.\n", numChildren); head->children = malloc(sizeof(treeNode) * numChildren); for(int i=0;i<numChildren;i++){ // printf("for\n"); copyBoard(head->board,boardHolder); applyMove(moves,boardHolder); //printBoard(boardHolder); head->children[i] = malloc(sizeof(treeNode)); copyBoard(boardHolder,head->children[i]->board); head->children[i]->numChildren = 0; ptr = moves->next; free(moves); moves = ptr; } }else{//this should happen when there are already children in the tree for(int i=0;i<head->numChildren;i++){ head->children[i] = myTree(head->children[i],head->children[i]->board,cColour,pColour); } } return head; }
void updateBoard(int (board)[HEIGHT][WIDTH]) { int next_board[HEIGHT][WIDTH]; copyBoard(next_board, board); for (int x = 0; x < HEIGHT; ++x) { for (int y = 0; y < WIDTH; ++y) { int aliveN = 0; std::vector<int> neighbours = { board[x-1][y+1], board[x][y+1], board[x+1][y+1], board[x+1][y], board[x+1][y-1], board[x][y-1], board[x-1][y-1], board[x-1][y], }; for (auto cell : neighbours) { if (cell) aliveN++; } /* Rules ===== 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by overcrowding. 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. */ if (board[x][y] == 1 && aliveN < 2) { next_board[x][y] = 0; continue; } if (board[x][y] == 1 && (aliveN == 2 || aliveN == 3)) continue; if (board[x][y] == 1 && aliveN > 3) { next_board[x][y] = 0; continue; } if (!board[x][y] == 1 && aliveN == 3) { next_board[x][y] = 1; continue; } } } copyBoard(board, next_board); }
char getBestMove(char subBoard[], char superBoard[], char superBoardSpot, char opPlayer, char levels) { long best = -9999999999; char move; char start, end; char j = 0; char lastSuperBoardState; if (superBoardSpot == -1) { //search all spots on the board start = 0; end = SUB_BOARD_SIZE; } else { start = superBoardSpot * 9; end = start + 9; } threadpool thpool = thpool_init(THREADS); //search within the superboard for (char i = start; i < end; i++) { if (isOpenSpot(subBoard, superBoard, i)) { //Take the winning move is available lastSuperBoardState = superBoard[(i - (i % 9)) / 9]; char newSuperBoardSpot = doMove(subBoard, superBoard, opPlayer, i); if (superBoardWon(superBoard) == opPlayer) { undoMove(subBoard, superBoard, i, lastSuperBoardState); return i; } undoMove(subBoard, superBoard, i, lastSuperBoardState); ThreadData data; data.subBoard = copyBoard(subBoard, SUB_BOARD_SIZE); data.superBoard = copyBoard(superBoard, SUPER_BOARD_SIZE); data.opPlayer = opPlayer; data.levels = levels; data.move = i; tData[j] = data; thpool_add_work(thpool, (void*)threadStarter, j++); } } numThreads = j; thpool_wait(thpool); for (char i = 0; i < numThreads; i++) { if (trData[i].score > best) { best = trData[i].score; move = trData[i].move; } } return move; }
// methods to create a node State* createNode(MyType val){ State *newNode = (State *)malloc(sizeof(State)); int i; copyBoard(newNode->data, val); newNode->next = NULL; return newNode; }//end of createNode
Board moveBoard(Board b, int direction){ // direction = UP, DOWN, LEFT or RIGHT // returns NULL if direction not possible // fatal error if no BLANK on board Board retVal = NULL; int *blankPos = malloc(sizeof(int)*2); if (blankPos == NULL){ printf("Out of memory\n"); exit(1); } if (isValidMove(b, direction) == TRUE){ retVal = copyBoard(b); getBlankPos(b, blankPos); if (direction == UP){ swap(&retVal->array[blankPos[0]-1][blankPos[1]], &retVal->array[blankPos[0]][blankPos[1]]); } else if (direction == DOWN){ swap(&retVal->array[blankPos[0]+1][blankPos[1]], &retVal->array[blankPos[0]][blankPos[1]]); } else if (direction == LEFT){ swap(&retVal->array[blankPos[0]][blankPos[1]-1], &retVal->array[blankPos[0]][blankPos[1]]); } else if (direction == RIGHT){ swap(&retVal->array[blankPos[0]][blankPos[1] + 1], &retVal->array[blankPos[0]][blankPos[1]]); } } else { retVal = NULL; } free(blankPos); return retVal; }
void GameOfLife::specificInit() { int** init = game_board; init[0][0] = DEAD; init[0][1] = DEAD; init[0][2] = DEAD; init[0][3] = ALIVE; init[1][0] = DEAD; init[1][1] = DEAD; init[1][2] = DEAD; init[1][3] = ALIVE; init[2][0] = DEAD; init[2][1] = ALIVE; init[2][2] = DEAD; init[2][3] = DEAD; init[3][0] = ALIVE; init[3][1] = ALIVE; init[3][2] = ALIVE; init[3][3] = DEAD; init[4][0] = DEAD; init[4][1] = ALIVE; init[4][2] = DEAD; init[4][3] = DEAD; init[5][0] = DEAD; init[5][1] = ALIVE; init[5][2] = DEAD; init[5][3] = DEAD; copyBoard(copy_board, game_board); }
// Add one child to current node void addOneChild(Node* root, char move, int player) { Node* newChild = (Node*)malloc(sizeof(Node)); copyBoard(newChild->board, root->board); newChild->move = move; newChild->parent = root; int i; int cont; for (i = 0; i < 6; i++) { newChild->children[i] = NULL; } newChild->curChildIndex = 0; root->children[root->curChildIndex] = newChild; cont = pieceToMove(player, move, newChild->board); if (cont == 1) { findAdditionalMove(newChild, player); Node* best; if (player == 1) { best = findBestInTree(newChild); } else { best = findWorstInTree(newChild); } root->children[root->curChildIndex] = best; best->parent = root; best->move = move; } root->curChildIndex++; return; }
void cleanRows(Board *board, Board *nextBoard) { copyBoard(board, nextBoard); // clear columns for (int i = 0; i < BOARD_SIZE; i++) { int count = 0; for (int j = 0; j < BOARD_SIZE; j++) { if (board->grid[i][j] > 0) count++; } if (count == BOARD_SIZE) { for (int j = 0; j < BOARD_SIZE; j++) { nextBoard->grid[i][j] = 0; } } } // clear rows for (int i = 0; i < BOARD_SIZE; i++) { int count = 0; for (int j = 0; j < BOARD_SIZE; j++) { if (board->grid[j][i] > 0) count++; } if (count == BOARD_SIZE) { for (int j = 0; j < BOARD_SIZE; j++) { nextBoard->grid[j][i] = 0; } } } }
int getPermutations(Board *startBoard, int *pieces, Turn *possibleTurns) { int turnNumber = 0; Board board; Board nextBoard; for (int a = 0; a <=2; a++) { for (int b = 0; b <= 2; b++) { if (a == b) continue; for (int c = 0; c <= 2; c++) { if (c == b || c == a) continue; // initialise board back to start state copyBoard(startBoard, &board); // execute moves, recording moves to the turn getPiecePlacement(&board, pieces[a], &(possibleTurns[turnNumber].moves[0])); executeMove(&board, &nextBoard, &(possibleTurns[turnNumber].moves[0])); getPiecePlacement(&nextBoard, pieces[b], &(possibleTurns[turnNumber].moves[1])); executeMove(&nextBoard, &board, &(possibleTurns[turnNumber].moves[1])); getPiecePlacement(&board, pieces[c], &(possibleTurns[turnNumber].moves[2])); executeMove(&board, &nextBoard, &(possibleTurns[turnNumber].moves[2])); turnNumber++; } } } return turnNumber; }
int main(int argc, char *argv[]) { // Variable declarations int count = 1; int rows,cols,iters,numCoords,x,y,neighbors; FILE *inFile = openFile(argv[1]); struct timeval start, end; char *newBoard = NULL; char *refBoard = NULL; char *temp; // Threading variables // Process command line arguments verifyCmdArgs(argc, argv); // Open test parameter file and read in first 4 lines fscanf(inFile, "%d %d %d %d", &rows, &cols, &iters, &numCoords); // Create game board initialized to starting state newBoard = makeBoard(rows,cols,inFile,numCoords); refBoard = copyBoard(newBoard,rows,cols); print(refBoard,atoi(argv[2]),rows,cols,0); //printf("refBoard2: %s\n", refBoard); // Apply the life and death conditions to the board /*gettimeofday(&start, NULL); while (count < iters+1) { evolve(x,y,rows,cols,newBoard,refBoard,argv,numCoords,count); *temp = *refBoard; *refBoard = *newBoard; // reference board updated to be the newer board *newBoard = *temp;*/ // Very helpful visuals for showing which versions of the board // are being stored in our three char *'s /*printf("temBoard: %s\n", temp); printf("refBoard: %s\n", refBoard); printf("newBoard: %s\n", newBoard);* s/ temp = copyBoard(newBoard,rows,cols); refBoard = temp; // reference board updated to be the newer board //newBoard = temp; ++count; } gettimeofday(&end, NULL); */ // Time calculations long elapsed = (end.tv_sec-start.tv_sec)*1000000 + (end.tv_usec - start.tv_usec); printf("\nElapsed time for %d steps of a %d x %d board is: %f seconds\n", iters, rows, cols, elapsed/1000000.); free(newBoard); free(refBoard); fclose(inFile); refBoard = NULL; newBoard = NULL; temp = NULL; return 0; }
int calcDistance(int xPos1, int yPos1, int xPos2, int yPos2, World* world) { char** tempBoard = copyBoard(world->gameBoard); int distanceToDest = UNREACHABLE_DISTANCE; // unreachable int isNodeValid = 0; // set the cheese square as a wall in the temp board, because the cat can't move through cheese tempBoard[world->cheeseYPos][world->cheeseXPos] = WALL_SQUARE; Node* node = NULL; Node* node1 = (Node*)malloc(sizeof(Node)); if (node1 == NULL) { perror("ERROR: malloc failed\n"); exit(1); } node1->xPos = xPos1; node1->yPos = yPos1; node1->distance = 0; int isFoundDest = 0; ListRef queue = newList(node1); ListRef queueHead = queue; while (queue != NULL && !isEmpty(queue) && !isFoundDest) { node = (Node*)headData(queue); tempBoard[node->yPos][node->xPos] = WALL_SQUARE; Direction direction; for (direction = 0; direction < NUM_DIRECTIONS; direction++) { Node* movedNode = (Node*)malloc(sizeof(Node)); if (movedNode == NULL) { perror("ERROR: malloc failed\n"); exit(1); } movedNode->xPos = node->xPos; movedNode->yPos = node->yPos; movedNode->distance = node->distance; isNodeValid = moveNode(node->xPos, node->yPos, tempBoard, direction, movedNode); if (isNodeValid == 1) { if (isClose(movedNode->xPos,movedNode->yPos, xPos2, yPos2)) { distanceToDest = movedNode->distance; isFoundDest = 1; free(movedNode); break; } tempBoard[movedNode->yPos][movedNode->xPos] = WALL_SQUARE; append(queue, movedNode); } } queue = tail(queue); } freeBoard(tempBoard); destroyList(queueHead, free); return distanceToDest; }
// Initialize the searching Tree void initSearchTree(Hole originalBoard[], Node* root) { copyBoard(root->board, originalBoard); root->move = ' '; root->parent = NULL; int i; for (i = 0; i < 6; i++) { root->children[i] = NULL; } root->curChildIndex = 0; }
//Using linked list to implement undo. void undo(Hole board[], int *gameNum) { if (len(lHead) == 1) { printf("Sorry, you cannot undo past the beginning of the game. Please retry move.\n"); return; } deleteLastNode(&lHead); State* n = getTail(lHead); copyBoard(board, n->data); displayBoard(board); *gameNum -= 1; }
int GameOfLife::randomInit() { srand(time(0)); int alive = 0; for (int i = 0; i < row_size; i++) { for (int j = 0; j < col_size; j++) { game_board[i][j] = rand() % 2; alive += game_board[i][j]; } } copyBoard(copy_board, game_board); return alive; }
// returns 0 if NOT in check after the move // return 1 if in check after the move int simCheck(struct board * b, struct piece * p, struct pos * move, struct piece * k ) { struct piece * inactivePiece = NULL; struct pos * tempLoc; struct board * nBoard = copyBoard(b); struct pos * nMove = makeLoc(move->x, move->y); nMove->type = move->type; if(move->type ==4) { nMove->additionalM1 = move->additionalM1; nMove->additionalM2 = move->additionalM2; nMove->additionalP = getSpace(nBoard, move->x, move->y); } int temp = getOrder(b, p); int temp1; if(move->taken != NULL) { temp1 = getOrder(b,move->taken); nMove->taken = nBoard->pieces[temp1]; } else{ nMove->taken = NULL; } // printAllMoves(nBoard); movePiece(nBoard,nBoard->pieces[temp],nMove); updateAllMovesSim(nBoard); free(nMove); if(move->type == 4) { if(incheckCheck(nBoard,move->additionalP,move->additionalP->loc) == 1) { deleteBoard(nBoard); return 1; } deleteBoard(nBoard); return 0; } if(incheckCheck(nBoard,k,k->loc) == 1) { deleteBoard(nBoard); return 1; } deleteBoard(nBoard); return 0; }
int placePiece(Board *board, Board *nextBoard, int pieceNumber, Point *pos) { copyBoard(board, nextBoard); Piece piece = PIECES[pieceNumber % NUM_PIECES]; for (int x = 0; x < PIECE_SIZE; x++) { for (int y = 0; y < PIECE_SIZE; y++) { int xp = pos->x + x; int yp = pos->y + y; if (xp < BOARD_SIZE && yp < BOARD_SIZE) nextBoard->grid[xp][yp] += piece.grid[x][y]; if (nextBoard->grid[xp][yp] > 1) return -1; } } return 0; }
int right(){ copyBoard(); int i, j, k, x, y; for (i = 0; i < 4; i++){ x = -1; y = -1; for (j = 3; j >=0; j--) if (board[i][j] == 0){ y = j; break; } for (j = y - 1; j >=0; j--) if (board[i][j] != 0){ x = j; break; } for (j = y, k = x; k>=0 && j >=0; k--) if (board[i][k]){ board[i][j] = board[i][k]; board[i][k] = 0; j--; } for (j = 3; j; j--){ if (board[i][j] == board[i][j - 1] && board[i][j] != 0){ board[i][j] *= 2; score += board[i][j]; for (k = j-1; k >0; k--) board[i][k] = board[i][k - 1]; board[i][0] = 0; } } } return checkStateChange(); }
char findBestComputerMove(Hole originalBoard[]) { printFlag = 0; int i, j, k; // make a copy of the originalBoard Hole newBoard[BOARDSIZE]; copyBoard(newBoard, originalBoard); // construct the searching tree Node root; initSearchTree(newBoard, &root); // construct first level. Root is at level 0 int depth = 3; expandTree(&root, depth, 1); Node* bestNode; bestNode = findBest(&root, depth); char computerMove = findBestMove(bestNode, &root); deleteTree(&root, &root); printFlag = 1; return computerMove; }
void findAdditionalMove(Node* root, int player) { int i; char possibleChoice[6] = {'A', 'B', 'C', 'D', 'E', 'F'}; for (i = 0; i < 6; i++) { Node* newChild = (Node*)malloc(sizeof(Node)); copyBoard(newChild->board, root->board); newChild->move = possibleChoice[i]; newChild->parent = root; int j; int cont; for (j = 0; j < 6; j++) { newChild->children[j] = NULL; } newChild->curChildIndex = 0; root->children[root->curChildIndex] = newChild; root->curChildIndex++; cont = pieceToMove(player, possibleChoice[i], newChild->board); if (cont == 1) { findAdditionalMove(newChild, player); } } }
int up(){ copyBoard(); int i, j, k, x, y; for (j = 0; j < 4; j++){ x = 4; y = 4; for (i = 0; i <4; i++) if (board[i][j] == 0){ y = i; break; } for (i = y + 1; i <4; i++) if (board[i][j] != 0){ x = i; break; } for (i = y, k = x; k <4 && i < 4; k++) if (board[k][j]){ board[i][j] = board[k][j]; board[k][j] = 0; i++; } for (i = 0; i<3; i++){ if (board[i][j] == board[i + 1][j] && board[i][j] != 0){ board[i][j] *= 2; score += board[i][j]; for (k = i + 1; k <3; k++) board[k][j] = board[k +1][j]; board[3][j] = 0; } } } return checkStateChange(); }
int left(){ copyBoard(); int i, j, k, x, y; for (i = 0; i < 4; i++){ x = 4; y = 4; for (j = 0; j <4; j++) if (board[i][j] == 0){ y = j; break; } for (j = y + 1; j <4; j++) if (board[i][j] != 0){ x = j; break; } for (j = y, k = x; k <4 && j < 4; k++) if (board[i][k]){ board[i][j] = board[i][k]; board[i][k] = 0; j++; } for (j = 0; j<3; j++){ if (board[i][j] == board[i][j+1] && board[i][j] != 0){ board[i][j] *= 2; score += board[i][j]; for (k = j + 1; k <3; k++) board[i][k] = board[i][k+1]; board[i][3] = 0; } } } return checkStateChange(); }
int down(){ copyBoard(); int i, j,k,x,y; for (j = 0; j < 4; j++){ x = -1; y = -1; for (i = 3; i >= 0; i--) if (board[i][j] == 0){ y = i; break; } for (i = y-1; i >= 0; i--) if (board[i][j] != 0){ x = i; break; } for (i =y,k = x; k >=0&&i>=0; k--) if (board[k][j]){ board[i][j] = board[k][j]; board[k][j]=0; i--; } for (i = 3; i ; i--){ if (board[i][j] == board[i - 1][j] && board[i][j] != 0){ board[i][j] *= 2; score += board[i][j]; for (k = i - 1; k > 0; k--) board[k][j] = board[k - 1][j]; board[0][j] = 0; } } } return checkStateChange(); }
/*this function returns a board score for the given board for the player indicated. well.. actually it just randomly generates a number and returns that right now. You will need to make it better.*/ int Cathy::Eval(int board[][NUMSQUARES],int player, MoveList p1, MoveList p2){ /*int p1score; int p2score; int score;*/ int result = 0; int tempBoard[NUMSQUARES][NUMSQUARES] = {0}; copyBoard(tempBoard, board); int potentialMob = 0; int corner = 0; // First, we begin with taking mobility of a given player into consideration. // It will be a starting point for determining how good the situation is right now. // It is calculated from the difference between a given player and its opponent. // Pottential mobility should be found out. Potential mobility is a number of // empty squares that are adjacent to opponents pieces. if(player == 1){ for(int i = 0;i < NUMSQUARES; i++){ //go through each row for(int j = 0; j < NUMSQUARES; j++){ //go through every column in a row if( tempBoard[i][j] == -1 ){ //if field is occupied by an opponent for(int k = -1; k!= 1; k++){ //loop for local row if( i == 0 ) k = 0; //if row is 0, then don't check the -1 row for(int l = -1; l!= 1; l++){ //loop for local column if( j == 0 ) l = 0; //if column is 0, then don't check for -1 column if(tempBoard[i+k][j+l] == 0){ potentialMob++; tempBoard[i+l][j+l] = 3; } if( j == NUMSQUARES && l == 0) l++; //if column is 8, then don't check for +1 column } if( i == NUMSQUARES && k == 0) k++; // if row is 8, then don't check +1 row } } } } if(p1.isLegal(0,0) != -1 || p1.isLegal(0,NUMSQUARES) != -1 || p1.isLegal(NUMSQUARES,0) != -1 || p1.isLegal(NUMSQUARES,NUMSQUARES) != -1) corner++; result = p1.numMoves() - p2.numMoves() + potentialMob + corner; } else{ for(int i = 0;i < NUMSQUARES; i++){ //go through each row for(int j = 0; j < NUMSQUARES; j++){ //go through every column in a row if( tempBoard[i][j] == -1 ){ //if field is occupied by an opponent for(int k = -1; k!= 1; k++){ //loop for local row if( i == 0 ) k = 0; //if row is 0, then don't check the -1 row for(int l = -1; l!= 1; l++){ //loop for local column if( j == 0 ) l = 0; //if column is 0, then don't check for -1 column if(tempBoard[i+k][j+l] == 0){ potentialMob++; tempBoard[i+l][j+l] = 3; } if( j == NUMSQUARES && l == 0) l++; //if column is 8, then don't check for +1 column } if( i == NUMSQUARES && k == 0) k++; // if row is 8, then don't check +1 row } } } } if(p2.isLegal(0,0) != -1 || p2.isLegal(0,NUMSQUARES) != -1 || p2.isLegal(NUMSQUARES,0) != -1 || p2.isLegal(NUMSQUARES,NUMSQUARES) != -1) corner++; result = p2.numMoves() - p1.numMoves() + potentialMob + corner; } // mobility /*getScores(board,p1score,p2score); if(player==1){ score=p1score-p2score; } else{ score=p2score-p1score; }*/ return result; }
void selectMove() { // First, the two variables we'll use int i; double bestScore; int bestIndex; int bestCount; int *tempBoard; boardEvaluation *tempEval; tempBoard = malloc(boardWidth * boardHeight * sizeof(int)); if (tempBoard == null) { printf("Unable to allocate space for a temporary game board.\n"); exit(1); } // A sanity check if (possibleMovesFound == 0) { printf("Error! No possible moves found!\n"); printBoard(gameBoard); exit(1); } // Now the real work bestScore = -7.0; // Lower than the lowest possible score bestIndex = -1; bestCount = -1; // i = rand() % possibleMovesFound; for (i = 0; i < possibleMovesFound; i++) { // First, get us a temporary copy of the current game board copyBoard(gameBoard, tempBoard); // Now, run the trial move on it runMoveWithStruct(me, possibleMoves[i], tempBoard); // Now, evaluate it tempEval = evaluateBoard(tempBoard, possibleMoves[i]); // Now, score it possibleMoves[i]->score = scoreEvaluation(tempEval); // Now free that evaluation free(tempEval); // Now, see if it is the best one we've found if (possibleMoves[i]->score == 7.0) { // We found a winner, no need to score the rest bestIndex = i; bestCount = 1; break; } else if (possibleMoves[i]->score > bestScore) { bestCount = 1; bestScore = possibleMoves[i]->score; bestIndex = i; } else if (possibleMoves[i]->score == bestScore) { // If the scores are the same... bestCount++; // Make a random choice between them if ((float) rand() / RAND_MAX <= ((double) (1.0 / (double) bestCount))) { bestIndex = i; // Note, this is biased towards the front } } } // Set up the move copyMove(possibleMoves[bestIndex], &finalMove); free(tempBoard); }
State::State(Color const turnIn, Board const & boardIn): turn(turnIn) { copyBoard(boardIn, &board); }
State::State(State const & other): turn(other.turn) { copyBoard(other.board, &board); }