Character::Character(SDL_Renderer* renderer) { moves["estatico"]=getMove(renderer,"estatico",1); moves["idle"]=getMove(renderer,"idle",4); moves["kick"]=getMove(renderer,"kick",6); moves["punch"]=getMove(renderer,"punch",3); moves["walk"]=getMove(renderer,"walk",5); this->current_move = "idle"; this->current_sprite = 0; this->current_sprite_frame = 0; }
Character::Character(SDL_Renderer* renderer, int x, int y) { this->x=x; this->y=y; moves["bola"]=getMove(renderer,"bola",6); moves["vuelta"]=getMove(renderer,"vuelta",10); this->current_move = "bola"; this->current_sprite = 0; this->current_sprite_frame = 0; }
Direction _201445681_A::step(Direction prevStep_) { // AfterMove because we can't be sure it moved (in cases of undisciplined robot) updateAfterMove(prevStep_); Direction next = getMove(prevStep_, _myOrder); // BeforeMove because we can't be sure it moved (in cases of undisciplined robot) updateBeforeMove(next); #ifdef _DEBUG_ // if (deleteThis++ % 5 == 0) //// { // boost::detail::Sleep(50); // system("cls"); // printHouse(_robot.location); // cout << "A" << endl; // cout << _robot.location << endl; // cout << (int)prevStep_ << endl; //// } #endif return next; }
void AntiVisibleTower::shoot(float dt) { //电力足够的话 且没有移动 if (getMove() == false && isPowerEnough) { //检测隐形敌人 for (int i = 0; i < instance->enemyVector.size(); i++) { auto enemy = instance->enemyVector.at(i); auto enemyPos = enemy->getPosition(); auto enemyType = enemy->getType(); //只对第二种敌人(隐形敌人有效),否则所有敌人都要隐形 if (enemyType == 2) { if (isEnemyInAnyAntiTowerRange(enemy)) //如果敌人在反隐塔vector中任意一个的射程内的话就显形,否则隐形 { enemy->getEnemySprite()->setVisible(true); //图像上显形 enemy->setIsVisible(true);//功能上显形 } else { enemy->getEnemySprite()->setVisible(false);//隐形 enemy->setIsVisible(false); } } } } }
Character::Character(SDL_Renderer* renderer, int x, int y, bool flipped, string input_manager_file) { this->x=x; this->y=y; this->flipped=flipped; moves["idle"]=getMove(renderer,"idle",4); moves["kick"]=getMove(renderer,"kick",6); moves["punch"]=getMove(renderer,"punch",3); moves["walk_forward"]=getMove(renderer,"walk_forward",5); moves["walk_backward"]=getMove(renderer,"walk_backward",5); this->current_move = "idle"; this->current_sprite = 0; this->current_sprite_frame = 0; this->input_manager=new InputManager(input_manager_file); }
void RandomMoveComponent::update(sf::RenderTarget& container, float dt) { if(move_time <= 0.f) { move_time = getDuration(); current_move = getMove(); } move_time -= dt; MoveEvent e; e.move_vector = current_move; e.run = false; m_pOwner->triggerEvent(e); }
void multiPlayer() { do { system("CLS"); gameName(); draw(); setMove(getMove()); checkWin(); checkBoard(); }while(gameFinished!=true); printBoard(); system("PAUSE"); resetBoard(); }
string AIEngine::alphaMove() { // Create a copy of the original board string content = board->getContent(); Board preBoard(content); // Get best move board->score = 0; Board postBoard = alphaBeta(preBoard, pieceType, 4, true, pair<int, int>(0,0), INT_MIN, INT_MAX); // Set original board to resulting board for(int i = 0; i < BOARD_SIZE; i++) { for(int j = 0; j < BOARD_SIZE; j++) board->setIndex(i, j, postBoard.getIndex(i, j)); } // Get the selected move return getMove(preBoard, postBoard); }
bool pgn::Parser::getMoveList(std::string::const_iterator &itr1, const std::string::const_iterator &itr2, pgn::MoveList &out) { std::string::const_iterator local_itr = itr1; pgn::MoveList ml; skipBlanks(local_itr, itr2); pgn::Move *move; while (move = getMove(local_itr, itr2)) { itr1 = local_itr; ml.insert(*move); delete move; } itr1 = local_itr; out = ml; return true; }
/* choose the best next move for the computer, according to minimax */ int get_computer_move(int * game_matrix,int depth,linked_list (*create_children)(int *gameMatrix, int player,int *error)) { int cMove = 0,error=0; vertex root = build_tree(game_matrix, -1,create_children); if (root == NULL){ printf("make root failed\n"); return -1; } alphaBeta(root,INT_MIN,INT_MAX,-1,0,depth,create_children,&error); if(error==-1){ printf("alphaBeta failed\n"); remove_tree(root, 1,1); return -1; } cMove = getMove(root); remove_tree(root, 1,0); return cMove; }
void singlePlayer() { do { system("CLS"); gameName(); draw(); if(player==1) {setRmove(getRmove());} else {setMove(getMove());} checkWin(); checkBoard(); }while(gameFinished!=true); printBoard(); system("PAUSE"); resetBoard(); }
void getPlayerTwo(char board[ROW][COL], int *row, int *col){ int oldRow = *row, oldCol = *col; while(1){ printf("Player 2:\n"); printf("r:%d c:%d\n", *row, *col); getLocationForPlayers(board, row, col); printf("r:%d c:%d\n", *row, *col); if(!correctMoveForThePlayer(oldRow, oldCol, row, col)){ printf("\nWRONG ENTRY. TRY AGAIN.\n"); } else if(*row < ROW && *col < COL){ board[*row][*col] = 'B'; getMove(board, *row, *col); break; } else { printf("\nWRONG ENTRY. TRY AGAIN.\n"); } } }
void* networking::createGame(void *arg){ struct gameData gd = *((struct gameData*)arg); game Game; pthread_detach(pthread_self()); notifyPlayers(gd); while(!gameOverCheck(gd, Game)) { while(!winConditionCheck(gd, Game)) { sendGameState(gd, Game.serialize()); getMove(gd, Game); Game.changePlayer(); } Game.incrementScore(); Game.resetBoard(); sendGameState(gd, Game.serialize()); } close(gd.player1); close(gd.player2); return NULL; }
void MultiTower::shoot(float dt) //真正发射子弹 { if (nearestEnemy != nullptr && getMove() == false && isPowerEnough && nearestEnemy->getCurrHp() > 0 && nearestEnemy->getIsVisible() && !isSilenced) //当该塔不在移动状态时才能攻击 { int dirTotal = 10; for (int i = 0; i < dirTotal; i++) { auto multiBullet = MultiTowerBullet::create(); instance->bulletVector.pushBack(multiBullet->getBulletSprite()); //这里注意 : 子弹vector是sprite类型的,不是bullet类型的 instance->map->addChild(multiBullet, 40); multiBullet->setPosition(this->getPosition() + Point(0, 40)); auto moveDuration = 3; Point shootVector; shootVector.x = 1; shootVector.y = tan(i * 2 * M_PI / dirTotal); Point normalizedShootVector; if (i >= dirTotal / 2) { normalizedShootVector = shootVector.getNormalized(); } else{ normalizedShootVector = -shootVector.getNormalized(); } float farthestDistance = 300; Point overshotVector = normalizedShootVector * farthestDistance; Point offscreenPoint = (multiBullet->getPosition() - overshotVector); multiBullet->runAction(Sequence::create(MoveTo::create(moveDuration, offscreenPoint), CallFunc::create([=](){ instance->bulletVector.eraseObject(multiBullet); multiBullet->removeFromParent(); }),NULL)); } } }
/* we use this to get the first move when AI plays first */ int get_suggested_move(int * game_matrix, int depth,linked_list (*create_children)(int *gameMatrix, int player,int *error)) { int cMove = 0,error=0; /* build tree */ vertex root = build_tree(game_matrix, 1,create_children); if (root == NULL){ printf("make root failed\n"); return -1; } /* update scores in the tree */ alphaBeta(root,INT_MIN,INT_MAX,1,0,depth,create_children,&error); if(error==-1){ printf("alphaBeta failed\n"); remove_tree(root, 1,1); return -1; } /* find best move */ cMove = getMove(root); /* destroy tree */ remove_tree(root, 1,0); return cMove; }
void KMovingConfig::save( void ) { int v; KConfigGroup cg(config, "Windows"); v = getMove(); if (v == TRANSPARENT) cg.writeEntry(KWIN_MOVE,"Transparent"); else cg.writeEntry(KWIN_MOVE,"Opaque"); cg.writeEntry(KWIN_GEOMETRY, getGeometryTip()); v = getResizeOpaque(); if (v == RESIZE_OPAQUE) cg.writeEntry(KWIN_RESIZE_OPAQUE, "Opaque"); else cg.writeEntry(KWIN_RESIZE_OPAQUE, "Transparent"); cg.writeEntry(KWIN_MOVE_RESIZE_MAXIMIZED, moveResizeMaximized->isChecked()); cg.writeEntry(KWM_BRDR_SNAP_ZONE,getBorderSnapZone()); cg.writeEntry(KWM_WNDW_SNAP_ZONE,getWindowSnapZone()); cg.writeEntry(KWM_CNTR_SNAP_ZONE,getCenterSnapZone()); cg.writeEntry("SnapOnlyWhenOverlapping",OverlapSnap->isChecked()); if (standAlone) { config->sync(); // Send signal to all kwin instances QDBusMessage message = QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); QDBusConnection::sessionBus().send(message); } emit KCModule::changed(false); }
/*Main function of interactif window*/ void runInteractif() { interactif_win = newwin(HEIGHT_INT, WIDTH_WIN, 1, 1); init_pair(1, COLOR_BLACK, COLOR_WHITE); bgchange(interactif_win, COLOR_BLACK, COLOR_WHITE, 99); /*Load board from array from the file or from somewhere else*/ loadMap("menu"); /*Print bottom info*/ wattron(stdscr, COLOR_PAIR(1)); printFrom(stdscr, HEIGHT-1, 1, "Use"); wattroff(stdscr, COLOR_PAIR(1)); init_pair(4, COLOR_RED, COLOR_WHITE); wattron(stdscr, COLOR_PAIR(4)); printFrom(stdscr, HEIGHT-1, 5, "ARROW KEYS"); wattroff(stdscr, COLOR_PAIR(4)); wattron(stdscr, COLOR_PAIR(1)); printFrom(stdscr, HEIGHT-1, 16, "to move your character. Use"); wattroff(stdscr, COLOR_PAIR(1)); wattron(stdscr, COLOR_PAIR(4)); printFrom(stdscr, HEIGHT-1, 44, "ENTER"); wattroff(stdscr, COLOR_PAIR(4)); wattron(stdscr, COLOR_PAIR(1)); printFrom(stdscr, HEIGHT-1, 50, "to 'use' objects"); wattroff(stdscr, COLOR_PAIR(1)); flushinp(); int input; while (1 == 1) { /*Receive input*/ flushinp(); input = getch(); getMove(input); } }
double needlemanWunsch(const char* acA, const char* acB, int nLenA, int nLenB, int nM) { double **aadFMatrix = NULL; int **aanMoves = NULL; int **aanHA = NULL; int **aanHB = NULL; int anHA[nLenA + nLenB]; int anHB[nLenA + nLenB]; char *acAlignA = NULL, *acAlignB = NULL; int nCount = 0, nLen = 0, nComp = 0; int i = 0, j = 0; double dDist = 0.0; aadFMatrix = (double **) malloc((nLenA + 1)*sizeof(double *)); aanMoves = (int **) malloc((nLenA + 1)*sizeof(int *)); aanHA = (int **) malloc((nLenA + 1)*sizeof(int *)); aanHB = (int **) malloc((nLenA + 1)*sizeof(int *)); if(!aadFMatrix || !aanMoves) goto memoryError; for(i = 0; i < nLenA + 1; i++){ aadFMatrix[i] = (double *) malloc((nLenB + 1)*sizeof(double)); aanMoves[i] = (int *) malloc((nLenB + 1)*sizeof(int)); aanHA[i] = (int *) malloc((nLenB + 1)*sizeof(int)); aanHB[i] = (int *) malloc((nLenB + 1)*sizeof(int)); if(!aadFMatrix[i] || !aanMoves[i]) goto memoryError; for(j = 0; j < nLenB + 1; j++){ aadFMatrix[i][j] = 0.0; aanMoves[i][j] = -1; aanHA[i][j] = -1; aanHB[i][j] = -1; } } for(i = 0; i <= nLenA; i++){ aadFMatrix[i][0] = GAP_PENALTY*i; aanMoves[i][0] = UP; aanHA[i][0] = 0; aanHB[i][0] = 0; } for(j = 0; j <= nLenB; j++){ aadFMatrix[0][j] = GAP_PENALTY*j; aanMoves[0][j] = LEFT; aanHA[0][j] = 0; aanHB[0][j] = 0; } for(i = 1; i <= nLenA; i++){ for(j = 1; j <= nLenB; j++){ double dChoice1, dChoice2, dChoice3; dChoice1 = aadFMatrix[i-1][j-1] + dist(acA[i - 1], acB[j - 1]); if(i == nLenA){ dChoice2 = aadFMatrix[i][j-1]; } else{ double dGap = 0.0; int nCurrH = aanHA[i][j - 1]; int nNewH = returnHomopolymerA(LEFT, aanHA, aanMoves, i, j, acA, acB); /*Left gap in A*/ if(nNewH == 0){ dGap = GAP_PENALTY; } else{ dGap = HOMOPOLYMER_PENALTY; } dChoice2 = aadFMatrix[i][j-1] + dGap; } if(j == nLenB){ dChoice3 = aadFMatrix[i-1][j]; } else{ double dGap = 0.0; int nCurrH = aanHA[i][j - 1]; int nNewH = returnHomopolymerA(LEFT, aanHA, aanMoves, i, j, acA, acB); /*Left gap in A*/ if(nNewH == 0){ dGap = GAP_PENALTY; } else{ dGap = HOMOPOLYMER_PENALTY; } /*Up gap in B*/ dChoice3 = aadFMatrix[i-1][j] + dGap; } aanMoves[i][j] = getMove(dChoice1, dChoice2, dChoice3); aadFMatrix[i][j] = dmin3(dChoice1, dChoice2, dChoice3); updateHomopolymers(aanHA, aanHB, aanMoves, i, j, acA, acB); } } dDist = aadFMatrix[nLenA][nLenB]; acAlignA = (char *) malloc((nLenA + nLenB)*sizeof(char)); if(!acAlignA) goto memoryError; acAlignB = (char *) malloc((nLenA + nLenB)*sizeof(char)); if(!acAlignB) goto memoryError; for(i = 0; i < nLenA + nLenB; i++){ acAlignA[i] = GAP; acAlignB[i] = GAP; } nCount = 0; i = nLenA; j = nLenB; while(i > 0 && j > 0){ anHA[nCount] = aanHA[i][j]; anHB[nCount] = aanHB[i][j]; switch(aanMoves[i][j]){ case DIAG: acAlignA[nCount] = acA[i - 1]; acAlignB[nCount] = acB[j - 1]; i--; j--; break; case UP: acAlignA[nCount] = acA[i - 1]; if(j == nLenB){ acAlignB[nCount] = T_GAP; } else{ acAlignB[nCount] = GAP; } i--; break; case LEFT: if(i == nLenA){ acAlignA[nCount] = T_GAP; } else{ acAlignA[nCount] = GAP; } acAlignB[nCount] = acB[j - 1]; j--; break; } nCount++; } while(i > 0){ acAlignA[nCount] = acA[i - 1]; acAlignB[nCount] = GAP; anHA[nCount] = aanHA[i][j]; anHB[nCount] = aanHB[i][j]; i--; nCount++; } while(j > 0){ acAlignA[nCount] = GAP; acAlignB[nCount] = acB[j - 1]; anHA[nCount] = aanHA[i][j]; anHB[nCount] = aanHB[i][j]; j--; nCount++; } nLen = nCount; i = 0; while(acAlignA[i] == T_GAP || acAlignB[i] == T_GAP){ i++; } nComp = nLen - i; dDist = aadFMatrix[nLenA][nLenB]/((double) nComp); //normalise by M * true length not with terminal gaps free(acAlignA); free(acAlignB); for(i = 0; i <= nLenA; i++){ free(aadFMatrix[i]); free(aanMoves[i]); free(aanHA[i]); free(aanHB[i]); } free(aadFMatrix); free(aanMoves); free(aanHA); free(aanHB); return dDist; memoryError: fprintf(stderr, "Failed to allocate memory in needlemanWunsch\n"); fflush(stderr); exit(EXIT_FAILURE); }
int main (void) { int player = 0; int winner = 0; int choice = 0; int row = 0; int column = 0; int line = 0; char board [3][3] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'} }; void renderBoard(char** bd){ /*todo add somelogic*/ } void getMove(char&& bd){ /*to do add some logic*/ } for (int i = 0; i<9 && winner==0; i++) { renderBoard(board); player = i%2 + 1; getMove(board); do { printf("\nPlayer %d, please enter the number of the square " "where you want to place your %c: ", player,(player==1)?'X':'O'); scanf("%d", &choice); row = --choice/3; column = choice%3; }while(choice<0 || choice>9 || board [row][column]>'9'); board[row][column] = (player == 1) ? 'X' : 'O'; if((board[0][0]==board[1][1] && board[0][0]==board[2][2]) || (board[0][2]==board[1][1] && board[0][2]==board[2][0])) winner = player; else for(line = 0; line <=2; line++) if((board[line][0]==board[line][1] && board[line][0]==board[line][2])|| (board[0][line]==board[1][line] && board[0][line]==board[2][line])) winner = player; } renderBoard(board); if(winner==0) printf("The game is a draw\n"); else printf("Player %d has won\n", winner); return 0; }
void Snake::move(Map &m) { Map::e_caseType c; SnakeIA::e_Direction d; Cdn<int> head(m_snake.back()); bool moved(false); d = getMove(m, head); while (moved == false) { if (d == UP) { if ((c = m.getCase(head.getX(), head.getY() - 1)) == Map::EMPTY || c == Map::FOOD) { if (c == Map::FOOD) m.deleteFood(head.getX(), head.getY() - 1); m_snake.push_back(Cdn<int>(head.getX(), head.getY() - 1)); moved = true; } } if (d == DOWN) { if ((c = m.getCase(head.getX(), head.getY() + 1)) == Map::EMPTY || c == Map::FOOD) { if (c == Map::FOOD) m.deleteFood(head.getX(), head.getY() + 1); m_snake.push_back(Cdn<int>(head.getX(), head.getY() + 1)); moved = true; } } if (d == LEFT) { if ((c = m.getCase(head.getX() - 1, head.getY())) == Map::EMPTY || c == Map::FOOD) { if (c == Map::FOOD) m.deleteFood(head.getX() - 1, head.getY()); m_snake.push_back(Cdn<int>(head.getX() - 1, head.getY())); moved = true; } } if (d == RIGHT) { if ((c = m.getCase(head.getX() + 1, head.getY())) == Map::EMPTY || c == Map::FOOD) { if (c == Map::FOOD) { m.deleteFood(head.getX() + 1, head.getY()); m_eated++; } m_snake.push_back(Cdn<int>(head.getX() + 1, head.getY())); moved = true; } } d = getRandomMove(); } if (c == Map::FOOD) m_toGrow++; if (m_toGrow == 0) m_snake.erase(m_snake.begin()); else { std::cout << "I'm Growing, my size is " << m_snake.size() << std::endl; m_toGrow--; } }
void pid_Wallfollow_process(void) { if (ControlFlag) { static int i; pid_Runtimeout(&pid_process_callback, ui32_msLoop); ControlFlag = false; leftError=(float)IR_get_calib_value(IR_CALIB_BASE_LEFT) - (float)IR_GetIrDetectorValue(1); rightError=(float)IR_get_calib_value(IR_CALIB_BASE_RIGHT) - (float)IR_GetIrDetectorValue(2); isWallLeft = IR_GetIrDetectorValue(1)<IR_get_calib_value(IR_CALIB_MAX_LEFT); isWallRight = IR_GetIrDetectorValue(2)<IR_get_calib_value(IR_CALIB_MAX_RIGHT); isWallFrontLeft = IR_GetIrDetectorValue(0)<IR_get_calib_value(IR_CALIB_MAX_FRONT_LEFT); isWallFrontRight = IR_GetIrDetectorValue(3)<IR_get_calib_value(IR_CALIB_MAX_FRONT_RIGHT); switch(eMove) { case FORWARD: switch (moveStage) { case 1: if (Forward()) moveStage++; if (isWallFrontLeft| isWallFrontRight) { preMove=eMove; eMove=getMove(isWallLeft,isWallFrontLeft|isWallFrontRight,isWallRight); } break; case 2: posLeftTmp=qei_getPosLeft(); moveStage++; i=1; avrSpeedTmp=avrSpeed; case 3://slow down forwardUpdate(); if (!isWallLeft) { rqTurnLeft=true; } if (!isWallRight) { rqTurnRight=true; } if ((abs(qei_getPosLeft()-posLeftTmp)<5000) && (!isWallFrontLeft) && (!isWallFrontRight)) { if ((abs(qei_getPosLeft()-posLeftTmp)>i*500) && (avrSpeed>AVG_SPEED_FWD-40)) { avrSpeed -= 10; i++; } if (isWallLeft|isWallRight) pid_wallfollow(leftError,rightError, avrSpeed,WALL_FOLLOW_AUTO); else { pid_reset(&pid_wall_left); pid_reset(&pid_wall_right); speed_set(MOTOR_RIGHT, avrSpeed); speed_set(MOTOR_LEFT, avrSpeed); } } else { #ifdef TEST_FORWARD_MOVE speed_Enable_Hbridge(false); #endif preMove=eMove; eMove=getMove(!rqTurnLeft,isWallFrontLeft|isWallFrontRight,!rqTurnRight); if (eMove==FORWARD) avrSpeed=AVG_SPEED_FWD; rqTurnLeft=false; rqTurnRight=false; moveStage=1; } break; } break; case TURN_LEFT: switch (moveStage) { case 1: if (preMove!=FORWARD)//after turning left or right //test // ____ // | | // | | | fwdPulse=6000; else if ((preMove==FORWARD) && (avrSpeed<AVG_SPEED_FWD_FAST)) //after turning back //test // ___ // |__ | // |__| fwdPulse=5500; else//after moving forward //test // ___ // ___ | // | | // |_| fwdPulse=4500; moveStage++; case 2: if (TurnLeft(fwdPulse,60,240,7800,1700+CELL_ENC)) { moveStage++; } break; case 3: posLeftTmp=qei_getPosLeft(); moveStage++; case 4: //go straight a little bit to check wall forwardUpdate(); if (abs(qei_getPosLeft()-posLeftTmp)<2000) { if (abs(qei_getPosLeft()-posLeftTmp)>1500) { if (!isWallRight) rqTurnRight=1; if (!isWallLeft) rqTurnLeft=1; } avrSpeed=AVG_SPEED_FWD_SLOW; if (isWallLeft|isWallRight) pid_wallfollow(leftError,rightError, avrSpeed,WALL_FOLLOW_AUTO); else { pid_reset(&pid_wall_left); pid_reset(&pid_wall_right); speed_set(MOTOR_RIGHT, avrSpeed);//left motor is faster speed_set(MOTOR_LEFT, avrSpeed); } } else { #ifdef TEST_TURNLEFT_MOVE3 speed_Enable_Hbridge(false); #endif //time to check front wall preMove=eMove; eMove=getMove(!rqTurnLeft,isWallFrontLeft|isWallFrontRight,!rqTurnRight); rqTurnLeft=false; rqTurnRight=false; moveStage=1; pid_reset(&pid_wall_left); pid_reset(&pid_wall_right); } } break; case TURN_RIGHT: switch (moveStage) { case 1: if (preMove!=FORWARD)//after turning left or right //test // ____ // | | // | | | fwdPulse=6000; else if ((preMove==FORWARD) && (avrSpeed<AVG_SPEED_FWD_FAST)) //after turning back //test // ____ // | ____ // |__| fwdPulse=5500; else//after moving forward //test // _____ // | _____ // | | // |_| fwdPulse=4500; moveStage++; case 2: if (TurnRight(fwdPulse,200,40,8000,1700+CELL_ENC)) { moveStage++; } break; case 3: posLeftTmp=qei_getPosLeft(); moveStage++; case 4: forwardUpdate(); if (abs(qei_getPosLeft()-posLeftTmp)<1000) { if (abs(qei_getPosLeft()-posLeftTmp)>500) { if (!isWallRight) rqTurnRight=1; if (!isWallLeft) rqTurnLeft=1; } avrSpeed=AVG_SPEED_FWD_SLOW; if (isWallLeft|isWallRight) pid_wallfollow(leftError,rightError, avrSpeed,WALL_FOLLOW_AUTO); else { pid_reset(&pid_wall_left); pid_reset(&pid_wall_right); speed_set(MOTOR_RIGHT, avrSpeed); speed_set(MOTOR_LEFT, avrSpeed); } } else { #ifdef TEST_TURNRIGHT_MOVE3 speed_Enable_Hbridge(false); #endif preMove=eMove; eMove=getMove(!rqTurnLeft,isWallFrontLeft|isWallFrontRight,!rqTurnRight); rqTurnLeft=false; rqTurnRight=false; moveStage=1; pid_reset(&pid_wall_left); pid_reset(&pid_wall_right); } } break; case TURN_BACK: switch (moveStage) { case 1: if (preMove==FORWARD) fwdPulse=8000; else fwdPulse=9000; moveStage++; case 2: if (TurnBack(fwdPulse,-140,60,8000,13000)) { //rotate more if we still detect front wall: do it yourself ;D moveStage++; } break; case 3: if (move(-9000,-9000,AVG_SPEED_BWD,AVG_SPEED_BWD)) { #ifdef TEST_TURNBACK_BACKWARD speed_Enable_Hbridge(false); #endif forwardUpdate(); avrSpeed = AVG_SPEED_FWD_SLOW; preMove=eMove; eMove=FORWARD; moveStage = 1; } } break; } } }
void GamePlayer::compete(int argc, char* args[], int dumpLevel) { std::string host = tournamentParams().stringValue("HOST"); int port = (argc == 1) ? tournamentParams().intValue("PORT") : std::atoi(args[1]); if (!client.create(host, port)) { std::perror(std::string("Error connecting to " + host + ":" + std::to_string(port)).c_str()); std::cout << nickname << " tournament over" << std::endl; return; } std::cout << "Connected to server, now waiting to play" << std::endl; init(); client.sendMsg(nickname); while (true) { //std::this_thread::sleep_for(std::chrono::microseconds(200)); std::string cmd = client.receiveMsg(); if (cmd == "DONE") { if (dumpLevel > 0) std::cout << nickname << " is done playing" << std::endl; done(); break; } else if (cmd == "START") { side = GameState::str2who(client.receiveMsg()); std::string opp = client.receiveMsg(); if (dumpLevel > 0) std::cout << nickname << " new game as " << st->who2str (st->getWho()) << " against " << opp << std::endl; std::string msgForOpp = messageForOpponent(opp); if (dumpLevel > 0) std::cout << "Message for opponent: " << msgForOpp << std::endl; client.sendMsg(msgForOpp); std::string msgFromOpp = client.receiveMsg(); messageFromOpponent(msgFromOpp); if (dumpLevel > 0) std::cout << "Message from opponent: " << msgFromOpp << std::endl; startGame(opp); } else if (cmd == "OVER") { std::string winner = client.receiveMsg(); client.sendMsg("OVER"); if (winner == "DRAW") { if (dumpLevel > 0) std::cout << "I (" << nickname << " had a draw"; endGame(0); } else if (st->str2who(winner) == side) { if (dumpLevel > 0) std::cout << "I (" << nickname << ") won" << std::endl; endGame(+1); } else { if (dumpLevel > 0) std::cout << "I (" << nickname << ") lost" << std::endl; endGame(-1); } } else if (cmd == "MOVE") { std::string lastMove = client.receiveMsg(); std::string boardStr = client.receiveMsg(); st->parseMsg(boardStr); if (dumpLevel > 1) { std::cout << "Turn " << nickname << " " << GameState::who2str(side) << std::endl << "Last move: " << lastMove << std::endl << "Current state\n" << st->toDisplayStr(); } GameMove *mv = getMove(*st, lastMove); std::string mvStr = mv->toString(); if (dumpLevel > 1) std::cout << "Send my move: " << mvStr <<std::endl; client.sendMsg(mvStr); delete mv; std::string timeStr = client.receiveMsg(); // should be "TIME" if (timeStr != "TIME") std::perror(std::string("time message:" + timeStr).c_str()); double time = std::stod(client.receiveMsg()); if (dumpLevel > 1) std::cout << time << " seconds" << std::endl; timeOfLastMove(time); } else { std::perror(std::string("bad command from server: " + cmd).c_str()); std::exit(EXIT_FAILURE); } } }
int main(int argc, char * argv[]){ int disciplines[] = DEFAULT_DISCIPLINES; int dice[] = DEFAULT_DICE; int turnOver = FALSE; int winner = NO_ONE; int diceValue; action move; int whoseTurn = NO_ONE; srand(time(NULL)); //initialises a seed Game g = newGame(disciplines,dice); while (winner == NO_ONE) { diceValue = rollDice(2,6); throwDice(g,diceValue); printf("[Turn %d] The turn now belongs to University %d!\n", getTurnNumber(g), getWhoseTurn(g)); printf("The dice casted a %d!\n", diceValue); whoseTurn = getWhoseTurn(g); //loop until player action is PASS turnOver = FALSE; while (!turnOver) { move = getMove(g); //print info about move printf("Move %d \n",move.actionCode); assert(isLegalAction(g, move)); if (move.actionCode == START_SPINOFF) { //decide if outcome is patent or publication if (rand() % 3 <= 1) { move.actionCode = OBTAIN_PUBLICATION; } else { move.actionCode = OBTAIN_IP_PATENT; } } if(move.actionCode == PASS){ turnOver = TRUE; printf("Pass\n"); } makeAction(g, move); if(getKPIpoints(g, whoseTurn) >= WINNING_KPI){ winner = whoseTurn; turnOver = TRUE; printf("Winner %d\n",whoseTurn); } } } // TODO print statistics // TODO free memory return EXIT_SUCCESS; }
void needlemanWunsch(double *adFookUp, double* adF1, double* adF2, t_Align *ptAlign, int* anA, int* anB, int nLenA, int nLenB) { double **aadFMatrix = NULL; int **aanMoves = NULL; int *anPath = NULL; int nCount = 0; int i = 0, j = 0, k = 0; aadFMatrix = (double **) malloc((nLenA + 1)*sizeof(double *)); aanMoves = (int **) malloc((nLenA + 1)*sizeof(int *)); if(!aadFMatrix || !aanMoves) goto memoryError; anPath = (int *) malloc(sizeof(int)*(nLenA + nLenB)); if(!anPath) goto memoryError; for(i = 0; i < nLenA + 1; i++){ aadFMatrix[i] = (double *) malloc((nLenB + 1)*sizeof(double)); aanMoves[i] = (int *) malloc((nLenB + 1)*sizeof(int)); if(!aadFMatrix[i] || !aanMoves[i]) goto memoryError; for(j = 0; j < nLenB + 1; j++){ aadFMatrix[i][j] = 0.0; aanMoves[i][j] = -1; } } for(i = 0; i <= nLenA; i++){ aadFMatrix[i][0] = GAP_PENALTY*i; aanMoves[i][0] = UP; } for(j = 0; j <= nLenB; j++){ aadFMatrix[0][j] = GAP_PENALTY*j; aanMoves[0][j] = LEFT; } //printf("allocated memory %d %d\n",nLenA,nLenB); fflush(stdout); for(i = 1; i <= nLenA; i++){ for(j = 1; j <= nLenB; j++){ double dChoice1, dChoice2, dChoice3; dChoice1 = aadFMatrix[i-1][j-1] + adFookUp[anA[i - 1]*BINS + anB[j - 1]] - adF1[i - 1] - adF2[j - 1]; if(j >= 4){ if(i == nLenA){ dChoice2 = aadFMatrix[i][j-4]; } else{ dChoice2 = aadFMatrix[i][j-4] + 4.0*GAP_PENALTY; } } else{ dChoice2 = MAX_DBL; } if(i >= 4){ if(j == nLenB){ dChoice3 = aadFMatrix[i-4][j]; } else{ dChoice3 = aadFMatrix[i-4][j] + 4.0*GAP_PENALTY; } } else{ dChoice3 = MAX_DBL; } aanMoves[i][j] = getMove(dChoice1, dChoice2, dChoice3); aadFMatrix[i][j] = dmin3(dChoice1, dChoice2, dChoice3); } } ptAlign->dDist = aadFMatrix[nLenA][nLenB]; i = nLenA; j = nLenB; while(i > 0 && j > 0){ anPath[nCount] = aanMoves[i][j]; switch(aanMoves[i][j]){ case DIAG: i--; j--; nCount++; break; case UP: i--; nCount++; k = 1; while(k < 4 && i >= 0){ anPath[nCount] = UP; i--; k++; nCount++; } break; case LEFT: j--; nCount++; while(k < 4 && j >= 0){ anPath[nCount] = LEFT; j--; k++; nCount++; } break; } } while(i > 0){ anPath[nCount] = aanMoves[i][j]; i--; nCount++; } while(j > 0){ anPath[nCount] = aanMoves[i][j]; j--; nCount++; } ptAlign->nLen = nCount; ptAlign->nComp = nCount; if(anPath[0] != DIAG){ int nStart = anPath[0]; i = 0; while(anPath[i] == nStart && i < nCount){ ptAlign->nComp--; i++; } } //printf("free memory %d %d\n",nLenA,nLenB); fflush(stdout); /*free up memory*/ free(anPath); for(i = 0; i <= nLenA; i++){ free(aadFMatrix[i]); free(aanMoves[i]); } free(aadFMatrix); free(aanMoves); return; memoryError: fprintf(stderr, "Failed to allocate memory in needlemanWunsch\n"); fflush(stderr); exit(EXIT_FAILURE); }
void playFreedomGame(){ char board[ROW][COL] = { {'W', 'B', 'W', 'W', 'B', 'B', 'W', 'W', 'W', 'B'}, {'B', 'B', 'B', 'B', 'W', 'W', 'B', 'B', 'B', 'B'}, {'W', 'W', 'B', 'W', 'W', 'B', 'W', 'W', 'W', 'W'}, {'W', 'W', 'B', 'W', 'W', 'B', 'B', 'W', 'B', 'B'}, {'B', 'B', 'W', 'B', 'B', 'W', 'W', 'B', 'B', 'W'}, {'W', 'W', 'B', 'W', 'W', 'W', 'B', 'B', 'W', 'B'}, {'B', 'B', 'W', 'B', 'B', 'W', 'B', 'W', 'W', 'W'}, {'W', 'W', 'B', 'W', 'B', 'W', 'B', 'W', 'B', 'B'}, {'B', 'W', 'B', 'B', 'W', 'W', 'B', 'B', 'B', 'W'}, {'B', 'W', 'B', 'W', 'B', 'B', 'W', 'W', 'B', 'W'} }; // char board[ROW][COL] = // { // {'B', 'B', 'B', 'B', 'B'}, // {'W', 'W', 'B', 'W', 'B'}, // {'W', 'B', 'W', 'B', 'B'}, // {'B', 'W', 'B', 'W', 'B'}, // {'W', 'B', 'W', 'W', 'W'} // }; // char board[ROW][COL] = {' '}; // fillArr(board, ' '); printBoard(board); int row = 0, col = 0, i = 0; while(howManyEmptyLeft(board) != 0){ printf("Player 1:\n"); getLocationForPlayers(board, &row, &col); board[row][col] = 'W'; getMove(board, row, col); getPlayerTwo(board, &row, &col); while(howManyEmptyLeft(board) != 0){ getPlayerOne(board, &row, &col); if(!isThereMove(board, row, col)){ break; } getPlayerTwo(board, &row, &col); if(!isThereMove(board, row, col)){ break; } printf("%d\n", howManyEmptyLeft(board)); i++; } } printScore(board, 'W'); printScore(board, 'B'); }
int main (int argc, char *argv[]) { player_t turn; GameState game; move_t themove; int opt; while ((opt = getopt (argc, argv, "cD:ehl:sVv:20")) != -1) { switch (opt) { case 'l': printf ("Level option (-l) is not yet implemented!\n"); printf (" -- you requested level %s.\n", optarg); break; case 'e': printf ("Expert option (-e) is not yet implemented!\n"); break; case 's': printf ("Smiley option (-s) is not yet implemented!\n"); break; case 'v': printf ("Verbose option (-v) is not yet implemented!\n"); printf (" -- you requested verbosity level %s.\n", optarg); break; case '2': printf ("2 player option (-2) is not yet implemented!\n"); break; case '0': printf ("Computer vs Computer option (-0) is not yet implemented!\n"); break; case 'D': printf ("Debug option (-D) is not yet implemented!\n"); printf (" -- you requested Debug level %s.\n", optarg); break; case 'V': printf ("Quad Version 0.8a By Jeremy Madea [email protected]\n"); printf (" Please Play me!\n"); exit (0); break; case 'h': printf ("Usage: quad [-v]\n"); exit (0); break; case '?': printf ("Invocation error... exiting\n"); exit (1); break; } } do { turn = whoGoesFirst (); initGameState (&game, turn); displayTheBoard (&game); while (!gameOver (&game)) { themove = getMove (turn, &game); playTheMove (turn, themove, &game); turn = other (turn); displayTheBoard (&game); } displayGameResult (&game); } while (doYouWantToPlayAgain ()); exit (0); }
EdgeSetIF* TabuSearchUtils::getEdgeSet( NeighborSolution const & spanningTreeNeighborWithCost) { return getEdgeSet(getMove(spanningTreeNeighborWithCost)); }
int main(int argc, char *argv[]) { VERBOSE = 0; GRAPHICS = 0; validate(argc, argv); int avatarID = atoi(argv[1]); FILE *logFile; logFile = fopen(argv[6], "a+"); char *IP = (char*)calloc(strlen(argv[4]) + 1, sizeof(char)); MALLOC_CHECK(stderr, IP); strncpy(IP, argv[4], strlen(argv[4])); myAvatar *avatar; int slobAvatar = 0; // the one who doesn't move in maze solver int mazePort = atoi(argv[5]); int width = atoi(argv[7]); int height = atoi(argv[8]); int shmID = atoi(argv[9]); char *maze = (char*) shmat(shmID, 0, 0); if (maze == (void *)-1 && errno == EACCES) { fprintf(stderr, "shmat failed EACCES\n"); exit(1); } if (maze == (void *)-1 && errno == EINVAL) { fprintf(stderr, "shmat failed EINVAL\n"); exit(1); } if (maze == (void *)-1 && errno == ENOMEM) { fprintf(stderr, "shmat failed ENOMEM\n"); exit(1); } // Server connection stuff int sockfd; struct sockaddr_in servaddr; // Create and check status of server sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { free(IP); fprintf(stderr, "Could not create socket.\n"); return 0; // false } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr(IP); servaddr.sin_port = htons(mazePort); // Connect to server if (connect(sockfd, (struct sockaddr*) &servaddr, \ sizeof(servaddr)) < 0) { fprintf(stderr, "Unable to connect to server. Exiting.\n"); free(IP); return 0; // false } // Fire off initial AM_AVATAR_READY AM_Message *sendmsg = (AM_Message*)calloc(1, sizeof(AM_Message)); MALLOC_CHECK(stderr, sendmsg); sendmsg->type = htonl(AM_AVATAR_READY); sendmsg->avatar_ready.AvatarId = htonl(avatarID); // pack information // Send ready message to server containing avatar ID send(sockfd, sendmsg, sizeof(AM_Message), 0); // Make a message to get back from server AM_Message *receivemsg = (AM_Message*)calloc(1, sizeof(AM_Message)); MALLOC_CHECK(stderr, receivemsg); int firstMove = 1; int turn = -1; // Start while loop that checks all server messages and updates // the avatar's position until either error message or AM_SOLVED received for ( ;; ) { // Zero out the message pointers so they can be re-used memset(receivemsg, 0, sizeof(AM_Message)); memset(sendmsg, 0, sizeof(AM_Message)); // Receive the message and make sure it's not empty if (recv(sockfd, receivemsg, sizeof(AM_Message), 0) == 0) { fprintf(stderr, "Server terminated early.\n"); OUTPUT(logFile, "Empty message type. Exiting...\n"); break; } // Check for server error if (IS_AM_ERROR(receivemsg->type)) { fprintf(stderr, "Error mask detected error.\n"); } // Following if statements will check for all possible server errors // In all cases, print to stderr, log the error to output file // and break to free resources and return if (ntohl(receivemsg->type) == AM_UNKNOWN_MSG_TYPE) { fprintf(stderr, "AM_UNKNOWN_MSG_TYPE\n"); OUTPUT(logFile, "Unknown message type. Exiting...\n"); break; } if (ntohl(receivemsg->type) == AM_NO_SUCH_AVATAR) { fprintf(stderr, "AM_NO_SUCH_AVATAR\n"); OUTPUT(logFile, "No such avatar error. Exiting...\n"); break; } if (ntohl(receivemsg->type) == AM_UNEXPECTED_MSG_TYPE) { fprintf(stderr, "AM_UNEXPECTED_MSG_TYPE\n"); OUTPUT(logFile, "Unexpected message type. Exiting...\n"); break; } if (ntohl(receivemsg->type) == AM_AVATAR_OUT_OF_TURN) { fprintf(stderr, "AM_AVATAR_OUT_OF_TURN\n"); OUTPUT(logFile, "Avatar out of turns message type. Exiting...\n"); break; } if (ntohl(receivemsg->type) == AM_TOO_MANY_MOVES) { fprintf(stderr, "AM_AVATAR_TOO_MANY_MOVES\n"); OUTPUT(logFile, "Avatar too many moves message type. Exiting...\n"); break; } if (ntohl(receivemsg->type) == AM_SERVER_TIMEOUT) { fprintf(stderr, "AM_SERVER_TIMEOUT\n"); OUTPUT(logFile, "Server timeout message type. Exiting...\n"); break; } if (ntohl(receivemsg->type) == AM_SERVER_DISK_QUOTA) { fprintf(stderr, "AM_SERVER_DISK_QUOTA\n"); OUTPUT(logFile, "Server disk quota message type. Exiting...\n"); break; } if (ntohl(receivemsg->type) == AM_SERVER_OUT_OF_MEM) { fprintf(stderr, "AM_SERVER_OUT_OF_MEM\n"); OUTPUT(logFile, "Server out of mem message type. Exiting...\n"); break; } // Huzzah! Output success to log file. if (ntohl(receivemsg->type) == AM_MAZE_SOLVED) { // Only output this stuff once. if (avatarID == slobAvatar) { fprintf(stdout, "SOLVED!!!\n"); fprintf(logFile, "Maze solved with %d avatars on %d" " difficulty in %d moves. The Hash key is: %d.\n", ntohl(receivemsg->maze_solved.nAvatars),\ ntohl(receivemsg->maze_solved.Difficulty), ntohl(receivemsg->maze_solved.\ nMoves), ntohl(receivemsg->maze_solved.Hash)); } break; } if (ntohl(receivemsg->type) == AM_AVATAR_TURN) { // Only look at messages from the relevant reply messages if (ntohl(receivemsg->avatar_turn.TurnId) == avatarID) { if (firstMove) { // Initialize the avatar. avatar = (myAvatar*)calloc(1, sizeof(myAvatar)); MALLOC_CHECK(stderr, avatar); avatar->fd = avatarID; avatar->lastMoveDir = M_NORTH; // everyone goes north initially // Initially, avatar's previous position and current position // are the same. Retrieve these from server. avatar->pos.x = ntohl(receivemsg->avatar_turn.Pos[avatarID].x); avatar->pos.y = ntohl(receivemsg->avatar_turn.Pos[avatarID].y); // No previous initially. // Send the avatar north. sendmsg->type = htonl(AM_AVATAR_MOVE); sendmsg->avatar_move.AvatarId = htonl(avatarID); sendmsg->avatar_move.Direction = htonl(M_NORTH); if (VERBOSE) { fprintf(stdout, "Avatar %d: Initial pos (%d, %d) moved NORTH\n", avatarID,\ avatar->pos.x, avatar->pos.y); } // Send ready message to server containing avatar ID send(sockfd, sendmsg, sizeof(AM_Message), 0); turn = 1; firstMove = 0; if (GRAPHICS) { //initialize graphics AddAvatar(maze,avatar,width); PrintMaze(maze, width, height); } continue; } else { // not first move // If it's the avatar standing still, arbitrarily picked as // avatar with ID = 0, then always stand still. if (avatarID == slobAvatar) { sendmsg->type = htonl(AM_AVATAR_MOVE); sendmsg->avatar_move.AvatarId = htonl(avatarID); // should be 0 sendmsg->avatar_move.Direction = htonl(M_NULL_MOVE); send(sockfd, sendmsg, sizeof(AM_Message), 0); turn++; continue; } // Make the previous the current position avatar->prev.x = avatar->pos.x; avatar->prev.y = avatar->pos.y; turn++; // Make current position the new one from the server int newX = ntohl(receivemsg->avatar_turn.Pos[avatarID].x); int newY = ntohl(receivemsg->avatar_turn.Pos[avatarID].y); avatar->pos.x = newX; avatar->pos.y = newY; // See if the slob and the current avatar are on the same spot. int deltaX = avatar->pos.x - ntohl(receivemsg->avatar_turn.Pos[slobAvatar].x); int deltaY = avatar->pos.y - ntohl(receivemsg->avatar_turn.Pos[slobAvatar].y); int checkSameCell = 0; if ((deltaY == 0) && (deltaX == 0)) { checkSameCell = 1; } // If avatar is on same spot as slob, slob has been found. // Don't move the other avatar. if (checkSameCell) { sendmsg->type = htonl(AM_AVATAR_MOVE); sendmsg->avatar_move.AvatarId = htonl(avatarID); sendmsg->avatar_move.Direction = htonl(M_NULL_MOVE); send(sockfd, sendmsg, sizeof(AM_Message), 0); turn++; continue; } // Avatar is not slob and has not yet met slob. else { // See if the last move was productive int lastMove = checkLastMove(avatar); avatar->lastMoveSuccess = lastMove; //update graphics based on last move if(!lastMove){ AddWall(maze,avatar,width); } else{ //DelAvatar(maze,avatar,width);//comment out to see history if(!AddMark(maze,avatar,width))//blocks square if test passes AddAvatar(maze,avatar,width); } if (GRAPHICS) { PrintMaze(maze,width,height); } //prep next move int nextMove = getMove(avatar); avatar->lastMoveDir = nextMove; while(isKnown(maze, avatar, width)){ avatar->lastMoveSuccess = false; nextMove = getMove(avatar); avatar->lastMoveDir = nextMove; } turn++; sendmsg->type = htonl(AM_AVATAR_MOVE); sendmsg->avatar_move.AvatarId = htonl(avatarID); sendmsg->avatar_move.Direction = htonl(nextMove); if (VERBOSE) { fprintf(stdout, "======== Turn %d ========\n", turn); if (nextMove == M_NORTH) { fprintf(stdout, "Avatar %d: Moved NORTH from (%d, %d).\n", avatarID,\ avatar->pos.x, avatar->pos.y); } if (nextMove == M_SOUTH) { fprintf(stdout, "Avatar %d: Moved SOUTH from (%d, %d).\n", avatarID,\ avatar->pos.x, avatar->pos.y); } if (nextMove == M_WEST) { fprintf(stdout, "Avatar %d: Moved WEST from (%d, %d).\n", avatarID,\ avatar->pos.x, avatar->pos.y); } if (nextMove == M_EAST) { fprintf(stdout, "Avatar %d: Moved EAST from (%d, %d).\n", avatarID,\ avatar->pos.x, avatar->pos.y); } fprintf(stdout, "\n"); } send(sockfd, sendmsg, sizeof(AM_Message), 0); } } } } } shmctl(shmID, IPC_RMID, NULL); free(sendmsg); free(receivemsg); free(IP); free(avatar); fclose(logFile); close(sockfd); return 1; }
void needlemanWunsch(t_Align *ptAlign, const char* acA, const char* acB, int nLenA, int nLenB) { double **aadFMatrix = NULL; int **aanMoves = NULL; char *acAlignA = NULL, *acAlignB = NULL; int nCount = 0; int i = 0, j = 0, nD = 0, nR = 0; aadFMatrix = (double **) malloc((nLenA + 1)*sizeof(double *)); aanMoves = (int **) malloc((nLenA + 1)*sizeof(int *)); if(!aadFMatrix || !aanMoves) goto memoryError; for(i = 0; i < nLenA + 1; i++){ aadFMatrix[i] = (double *) malloc((nLenB + 1)*sizeof(double)); aanMoves[i] = (int *) malloc((nLenB + 1)*sizeof(int)); if(!aadFMatrix[i] || !aanMoves[i]) goto memoryError; for(j = 0; j < nLenB + 1; j++){ aadFMatrix[i][j] = 0.0; aanMoves[i][j] = -1; } } for(i = 0; i <= nLenA; i++){ aadFMatrix[i][0] = GAP_PENALTY*i; aanMoves[i][0] = UP; } for(j = 0; j <= nLenB; j++){ aadFMatrix[0][j] = GAP_PENALTY*j; aanMoves[0][j] = LEFT; } for(i = 1; i <= nLenA; i++){ for(j = 1; j <= nLenB; j++){ double dChoice1, dChoice2, dChoice3; dChoice1 = aadFMatrix[i-1][j-1] + dist(acA[i - 1], acB[j - 1]); if(i == nLenA){ dChoice2 = aadFMatrix[i][j-1]; } else{ dChoice2 = aadFMatrix[i][j-1] + GAP_PENALTY; } if(j == nLenB){ dChoice3 = aadFMatrix[i-1][j]; } else{ dChoice3 = aadFMatrix[i-1][j] + GAP_PENALTY; } aanMoves[i][j] = getMove(dChoice1, dChoice2, dChoice3); aadFMatrix[i][j] = dmin3(dChoice1, dChoice2, dChoice3); } } ptAlign->dDist = aadFMatrix[nLenA][nLenB]; acAlignA = (char *) malloc((nLenA + nLenB)*sizeof(char)); if(!acAlignA) goto memoryError; acAlignB = (char *) malloc((nLenA + nLenB)*sizeof(char)); if(!acAlignB) goto memoryError; for(i = 0; i < nLenA + nLenB; i++){ acAlignA[i] = GAP; acAlignB[i] = GAP; } nCount = 0; i = nLenA; j = nLenB; while(i > 0 && j > 0){ switch(aanMoves[i][j]){ case DIAG: acAlignA[nCount] = acA[i - 1]; acAlignB[nCount] = acB[j - 1]; i--; j--; break; case UP: acAlignA[nCount] = acA[i - 1]; if(j == nLenB){ acAlignB[nCount] = T_GAP; } else{ acAlignB[nCount] = GAP; } i--; break; case LEFT: if(i == nLenA){ acAlignA[nCount] = T_GAP; } else{ acAlignA[nCount] = GAP; } acAlignB[nCount] = acB[j - 1]; j--; break; } nCount++; } while(i > 0){ acAlignA[nCount] = acA[i - 1]; acAlignB[nCount] = GAP; i--; nCount++; } while(j > 0){ acAlignA[nCount] = GAP; acAlignB[nCount] = acB[j - 1]; j--; nCount++; } ptAlign->nLen = nCount; ptAlign->acA = (char *) malloc(ptAlign->nLen*sizeof(char)); if(!ptAlign->acA) goto memoryError; ptAlign->acB = (char *) malloc(ptAlign->nLen*sizeof(char)); if(!ptAlign->acB) goto memoryError; for(i = 0; i < ptAlign->nLen; i++){ ptAlign->acA[ptAlign->nLen - 1 -i] = acAlignA[i]; ptAlign->acB[ptAlign->nLen - 1 -i] = acAlignB[i]; } ptAlign->dDist = calcDistance(acAlignA, acAlignB, ptAlign->nLen); ptAlign->nComp = ptAlign->nLen; while(ptAlign->nComp > 0 && ptAlign->acA[ptAlign->nComp - 1] == T_GAP || ptAlign->acB[ptAlign->nComp - 1] == T_GAP){ ptAlign->nComp--; } ptAlign->anD = (int *) malloc(nLenA*sizeof(int)); if(!ptAlign->anD) goto memoryError; ptAlign->anR = (int *) malloc(nLenA*sizeof(int)); if(!ptAlign->anR) goto memoryError; ptAlign->anMapD = (int *) malloc(nLenA*sizeof(int)); if(!ptAlign->anMapD) goto memoryError; ptAlign->anMapR = (int *) malloc(nLenA*sizeof(int)); if(!ptAlign->anMapR) goto memoryError; nCount = 0; nD = 0; for(i = 0; i < ptAlign->nLen; i++){ if(ptAlign->acA[i] == GAP){ nD++; } else if(ptAlign->acA[i] == T_GAP){ } else{ if(ptAlign->acB[i] == GAP){ nD++; } else if(ptAlign->acB[i] == T_GAP){ } else if(ptAlign->acA[i] != ptAlign->acB[i]){ nD++; } ptAlign->anD[nCount] = nD; ptAlign->anMapD[nCount] = i; nCount++; } } ptAlign->nDiff = nD; nCount = 0; nR = 0; for(i = ptAlign->nLen - 1; i >= 0; i--){ if(ptAlign->acA[i] == GAP){ nR++; } else if(ptAlign->acA[i] == T_GAP){ } else{ if(ptAlign->acB[i] == GAP){ nR++; } else if(ptAlign->acB[i] == T_GAP){ nR++; } else if(ptAlign->acB[i] != ptAlign->acA[i]){ nR++; } ptAlign->anR[nCount] = nR; ptAlign->anMapR[nCount] = i; nCount++; } } for(i = 0; i <= nLenA; i++){ free(aadFMatrix[i]); free(aanMoves[i]); } free(aadFMatrix); free(aanMoves); free(acAlignA); free(acAlignB); return; memoryError: fprintf(stderr, "Failed to allocate memory in needlemanWunsch\n"); fflush(stderr); exit(EXIT_FAILURE); }