Beispiel #1
0
// 静止探索で呼ばれる。
MovePicker::MovePicker(const Position& pos, Move ttm, const Depth depth, const History& history, const Square sq)
	: pos_(pos), history_(history), currMove_(firstMove()), lastMove_(firstMove())
{
	assert(depth <= Depth0);
	legalMoves_[0].score = INT_MAX; // 番兵のセット

	if (pos.inCheck()) {
		phase_ = QEvasionSearch;
	}
	// todo: ここで Stockfish は qcheck がある。
	else if (DepthQRecaptures < depth) {
		phase_ = QSearch;
		if (!ttm.isNone() && !ttm.isCaptureOrPawnPromotion()) {
			ttm = Move::moveNone();
		}
	}
	else {
		phase_ = QRecapture;
		recaptureSquare_ = sq;
		ttm = Move::moveNone();
	}

	ttMove_ = (!ttm.isNone() && pos.moveIsPseudoLegal(ttm) ? ttm : Move::moveNone());
	lastMove_ += !ttMove_.isNone();
}
Beispiel #2
0
PositionStatus AbstractGame::getPositionStatus() {
  if(!POSITION_DEFINED()) {
    if(m_bricksOnBoard <= 1) {
      DEFINE_POSITION(m_bricksOnBoard == 0, m_bricksOnBoard);
    } else {

      bool winnerMoveFound = false;
      int  pliesToWin      = 30;
      int  pliesToLoose    = 0;
      for(Move m = firstMove(); m && !winnerMoveFound; m = nextMove(m)) {
        doMove(m);
        const PositionStatus status = getPositionStatus();
        if(IS_LOOSERSTATUS(status)) {
          winnerMoveFound = true;
          if(PLIESTOEND(status) < pliesToWin) {
            pliesToWin = PLIESTOEND(status);
          }
        } else if(!winnerMoveFound) {
          if(PLIESTOEND(status) > pliesToLoose) {
            pliesToLoose = PLIESTOEND(status);
          }
        }
        undoMove(m);
      }
      if(winnerMoveFound) {
        DEFINE_POSITION(true , pliesToWin   + 1);
      } else {
        DEFINE_POSITION(false, pliesToLoose + 1);
      }
    }
  }
  return m_statusTable[m_board];
}
Beispiel #3
0
Outcome minimax( int player, Game game, vector<int> alphaBeta,int currLevel ) // notice that this is a call by value, so array gets copied!!!!
{

	//char c = 13;
	//if ( ! (minimaxCalls % 1000000 ) )
	//	cout << "minimax Calls = " << minimaxCalls/1000000 << " 000000" << c;
//	minimaxCalls++;

	int index = 1 - ((player*2)+2)/4;

	Move move = firstMove( game,player );
	Outcome Best( tryMove( player, move, game, alphaBeta,currLevel ), move ); // get a starting value on the first branch

	for ( move = nextMove( game, move ,player); move != noMovesLeft; move=nextMove( game, move ,player) )	{ 
//		If I am a max, being simulated by a min, who can already get
//      a score of beta, and the outcome from above is worse (for my parent), I might as well quit at this point.
//		Why? The grandparent will be totally uninterested in anything this node has to offer because it can pick
//		the previous node.
		
		alphaBeta[index] = player*__max( player*alphaBeta[index], player*Best.first );
		if ( alphaBeta[0] > alphaBeta[1] )  
		{
			Best.first = alphaBeta[index];
			break;
		}

		//add a check but ensure that we track the levels 
		int currentScore = tryMove( player, move, game, alphaBeta ,currLevel+1);
		if ( currentScore * player > Best.first * player ) 
		{ 
			Best = Outcome(currentScore, move);
		}
	}
	return Best;
}
Beispiel #4
0
MovePicker::MovePicker(const Position& pos, const Move ttm, const Depth depth,
					   const History& history, SearchStack* searchStack, const Score beta)
	: pos_(pos), history_(history), depth_(depth)
{
	assert(Depth0 < depth);

	legalMoves_[0].score = INT_MAX; // 番兵のセット
	currMove_ = lastMove_ = firstMove();
	captureThreshold_ = 0;
	endBadCaptures_ = legalMoves_ + MaxLegalMoves - 1;
	ss_ = searchStack;

	if (pos.inCheck()) {
		phase_ = EvasionSearch;
	}
	else {
		phase_ = MainSearch;

		killerMoves_[0].move = searchStack->killers[0];
		killerMoves_[1].move = searchStack->killers[1];

		if (ss_ != nullptr && ss_->staticEval < beta - CapturePawnScore && depth < 3 * OnePly) {
			captureThreshold_ = -CapturePawnScore;
		}
		else if (ss_ != nullptr && beta < ss_->staticEval) {
			captureThreshold_ = beta - ss_->staticEval;
		}
	}

	ttMove_ = (!ttm.isNone() && pos.moveIsPseudoLegal(ttm) ? ttm : Move::moveNone());
	lastMove_ += (!ttMove_.isNone());
}
Beispiel #5
0
Move AbstractGame::findMove(PositionSet markedPositions) const {
  for(Move m = firstMove(); m; m = nextMove(m)) {
    if(*m == markedPositions) {
      return m;
    }
  }
  return NULL;
}
Beispiel #6
0
MovePicker::MovePicker(const Position& pos, const Move ttm, const History& history, const PieceType pt)
	: pos_(pos), history_(history), currMove_(firstMove()), lastMove_(firstMove())
{
	assert(!pos.inCheck());

	legalMoves_[0].score = INT_MAX; // 番兵のセット
	phase_ = ProbCut;

	captureThreshold_ = pos.capturePieceScore(pt);
	ttMove_ = ((!ttm.isNone() && pos.moveIsPseudoLegal(ttm)) ? ttm : Move::moveNone());

	if (!ttMove_.isNone() && (!ttMove_.isCapture() || pos.see(ttMove_) <= captureThreshold_)) {
		ttMove_ = Move::moveNone();
	}

	lastMove_ += !ttMove_.isNone();
}
Beispiel #7
0
Move AbstractGame::findBestMove(MoveResultArray &moveArray, PlayLevel level) {
  moveArray.clear();
  for(Move m = firstMove(); m; m = nextMove(m)) {
    doMove(m);
    const PositionStatus status = getPositionStatus();
    moveArray.add(MoveWithResult(m, MAKE_STATUS(IS_LOOSERSTATUS(status),PLIESTOEND(status)+1)));
    undoMove(m);
  }
  moveArray.sort();
  return moveArray.selectBestMove(level, m_bricksOnBoard);
}
task main()
{
	initializeRobot();
	waitForStart();
	raiseArm(ArmUpRotations);
	intializeClaw();

  int _dirAC = 0;

  wait1Msec(200);

  int sensorDirection = HTIRS2readDCDir(irSeeker);

  if(sensorDirection < 5){
  	raiseArm(LeftArmUpRotations);
  	leftTurn(leftTurnRotations);
  	attackRack(leftFinalInches);
	}
	else{
		firstMove(middleStartInches);

		wait1Msec(300);
		sensorDirection = HTIRS2readDCDir(irSeeker);
		if(sensorDirection < 7){
			leftTurn(middleTurnRotations);
			attackRack(middleFinalInches);
		}
		else{
			raiseArm(RightArmUpRotations);
			firstMove(rightStartInches - middleStartInches);
			leftTurn(middleTurnRotations);
			attackRack(rightFinalInches);
		}
	}
	retreat();
}
Beispiel #9
0
/*This function plays a computer turns by going through a series of functions 
 * in order of priority and plays if that functions find that type of move.
 * The last function in the order will always play a move until the game is over
 * and this function is made to only make one move per turn.
 */
void computerTurn(int n, char board[21][21], bool humanPlayer) {
    int x, y;
    char humanPlayerC, compPlayerC;
    if (humanPlayer) {
        humanPlayerC = 'W';
        compPlayerC = 'B';
    } else if (!humanPlayer) {
        humanPlayerC = 'B';
        compPlayerC = 'W';
    }
    struct rusage usage; // a structure to hold "resource usage" (including time)
    struct timeval start, end; // will hold the start and end times
    getrusage(RUSAGE_SELF, &usage);
    start = usage.ru_utime;
    double time_start = start.tv_sec + start.tv_usec / 1000000.0; // in seconds
    /* PLACE THE CODE YOU WISH TO TIME HERE */
    if (firstMove(n, board, compPlayerC))
        largestFreeLoop(n, board, humanPlayer, humanPlayerC, compPlayerC);
    else if (connect6(n, board, humanPlayer, compPlayerC));
    else if (block6(n, board, humanPlayer, compPlayerC));
    else if (connect5(n, board, humanPlayer, humanPlayerC, compPlayerC));
    else if (block5(n, board, humanPlayer, humanPlayerC, compPlayerC));
    else if (connectTrap(n, board, humanPlayer, humanPlayerC, compPlayerC));
    else if (blockException(n, board, humanPlayer, humanPlayerC, compPlayerC));
    //Detect Enemy Traps takes up a lot of time and may not be worth using since
    //enemies may not have such complex traps
    else if (detectEnemyTraps(n, board, humanPlayer, humanPlayerC, compPlayerC));  
    else if (traps(n, board, humanPlayer, humanPlayerC, compPlayerC));
    else largestFreeLoop(n, board, humanPlayer, humanPlayerC, compPlayerC);


    /* PLACE THE CODE YOU WISH TO TIME HERE */
    getrusage(RUSAGE_SELF, &usage);
    end = usage.ru_utime;
    double time_end = end.tv_sec + end.tv_usec / 1000000.0; // in seconds
    double total_time = time_end - time_start; // total_time now holds the time
    printf("Total Time: %lf\n", total_time);

}
Beispiel #10
0
    void testMoveBBox() {
        FTBBox  boundingBox;
        FTPoint firstMove( 3.5f, 1.0f, -2.5f);
        FTPoint secondMove( -3.5f, -1.0f, 2.5f);

        boundingBox.Move( firstMove);

        CPPUNIT_ASSERT( boundingBox.lowerX ==  3.5f);
        CPPUNIT_ASSERT( boundingBox.lowerY ==  1.0f);
        CPPUNIT_ASSERT( boundingBox.lowerZ == -2.5f);
        CPPUNIT_ASSERT( boundingBox.upperX ==  3.5f);
        CPPUNIT_ASSERT( boundingBox.upperY ==  1.0f);
        CPPUNIT_ASSERT( boundingBox.upperZ == -2.5f);

        boundingBox.Move( secondMove);

        CPPUNIT_ASSERT( boundingBox.lowerX == 0.0f);
        CPPUNIT_ASSERT( boundingBox.lowerY == 0.0f);
        CPPUNIT_ASSERT( boundingBox.lowerZ == 0.0f);
        CPPUNIT_ASSERT( boundingBox.upperX == 0.0f);
        CPPUNIT_ASSERT( boundingBox.upperY == 0.0f);
        CPPUNIT_ASSERT( boundingBox.upperZ == 0.0f);
    }
void Solver::solve(vector<Move>& _solution) {
    lowerBound = initBoard->getLowerBound(targetTower);
    bestSolutionDepth = maxDepth;

    if (myRank != MASTER_RANK) {
        //cekam az mi prijde prace
        //prvni rozdeleni se udela automaticky bez zadani
        //cekam dokud message neprijde melo by prijit prvni deleni prace
        //momentalne to prvni spocte takzee prijde pesek
        MPI_Status s;
        MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &s);

        processMessages();

    } else {
        // Hotovo, koncim.
        if (initBoard->isTowerComplete(targetTower)) {
            broadcast(MESSAGE_FINISHED);
            return;
        }
        Move firstMove(0, 0, 0);
        SpaceItem* firstSpaceItem = new SpaceItem(*initBoard, firstMove);
        space.push_back(firstSpaceItem);
        expandTop();
        actualDepth = 1;
        firstWorkDistribution = true;
        space.erase(space.begin());
    }
    int counter = 0;

    while (!finished) {
        if (!space.empty()) {
            proccessTop(_solution, actualDepth);
        } else {

            requestData();
            sendToken();
        }

        if (counter == 150) {//natipovat idealni honotu
            if ((myRank == MASTER_RANK) && firstWorkDistribution) {
                firstDistribution();
                counter = 0;
            } else {
                counter = 0;
                processMessages();

                if (finished) {
                    char buffer[BUFFER_SIZE];
                    int position = 0;

                    serializeSolution(buffer, position, _solution);

                    char result[BUFFER_SIZE];

                    MPI_Op op;
                    MPI_Op_create((MPI_User_function*) compare, 0, &op);
                  //  cout<<_solution.size()<<endl;
                    MPI_Reduce(&buffer, &result, BUFFER_SIZE, MPI_PACKED, op, 0, MPI_COMM_WORLD);
                    int workRequestsRes;
                    MPI_Reduce (&workRequestsInt, &workRequestsRes, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
                    int failedWorkRequestsRes;
                    MPI_Reduce (&failedWorkRequests, &failedWorkRequestsRes, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
                    if (myRank == MASTER_RANK) {
                        vector<Move> solution;
                        int position = 0;
                        deserializeSolution(result, position, solution);

                        cout << "MASTER - ZACATEK RESENI" << endl;
                        for (vector<Move>::const_iterator it = solution.begin(); it < solution.end(); ++it) {
                            cout << *it << endl;
                        }
                        cout << "Solution depth: " << solution.size() << endl;
                        cout<< "Work Requests: "<<workRequestsRes<<endl;
                        cout<<"Denied Work Requests: "<<failedWorkRequestsRes<<endl;
                        
                        cout << "MASTER - KONEC RESENI" << endl;
                    }
                }
            }
        }
        counter++;
    }

    //   cout << "PushCount process " << myRank << ": " << pushCount << endl;
    //   cout << "Solution: " << _solution.size() << " - process " << myRank << endl;
    //   cout << "mam jeste: " << space.size() << " stavu" << endl;
}
Beispiel #12
0
void DBConverter::commitDBSet(const DBSet& set)
{
	// Adding statistics for move
	switch( set.MoveNumber ) {
		case 0: 
			data->AddPassoutMove1(set.Utilized, set.Hand, set.Move1);
			break;
		case 1:
			data->AddPassoutMove2(set.Utilized, set.Hand, set.Move1, set.Move2);
			break;
		case 2:
			data->AddPassoutMove3(set.Utilized, set.Hand, set.Move1, set.Move2, set.Move3);
			break;
		default:
			PrefAssert( false );
	}
	// Adding first move to set
	if( set.MoveNumber == 0 ) {
		vector<int> firstMove(1);
		firstMove[0] = -1;
		for( SuitForwardIterator itSuit; itSuit.HasNext(); itSuit.Next() ) { 
			RanksSet ranks = GetCardsOfSuit(set.Hand, itSuit.GetObject());
			if( ranks == EmptyRanksSet ) {
				continue;
			}
			firstMove.push_back( GetRanksSetIndex(ranks, GetCardsOfSuit(set.Utilized, itSuit.GetObject())) );
			if( itSuit.GetObject() == GetCardSuit(set.Move1) ) {
				firstMove[0] = firstMove.back();
			}
		}
		assert( firstMove[0] >= 0 );
		passoutFirstMoveData->AddSet(firstMove);
	}
	// Determining move suit and player suit...
	Suit moveSuit = GetCardSuit(set.Move1);
	Suit playerSuit = moveSuit;
	Card move = set.Move1;
	if( set.MoveNumber == 1 ) {
		playerSuit = GetCardSuit(set.Move2);
		move = set.Move2;
	} else if( set.MoveNumber == 2 ) {
		playerSuit = GetCardSuit(set.Move3);
		move = set.Move3;
	}
	if( moveSuit != playerSuit ) {
		GetLog() << "Move suit != player suit" << endl;
		// Adding learning set data about passout drop if required
		vector<int> sample(1);
		sample[0] = -1;
		for( SuitForwardIterator itSuit; itSuit.HasNext(); itSuit.Next() ) { 
			RanksSet ranksSet = GetCardsOfSuit(set.Hand, itSuit.GetObject());
			if( ranksSet == EmptyRanksSet ) {
				continue;
			}
			sample.push_back( GetRanksSetIndex(ranksSet, GetCardsOfSuit(set.Utilized, itSuit.GetObject())) ); 
			if( itSuit.GetObject() == playerSuit ) {
				sample[0] = sample.back();
			}
		}
		PrefAssert( sample[0] >= 0 );
		GetLog() << "Adding passout learning set: ";
		// dumping learning data
		for( int i = 0; i < sample.size(); i++ ) {
			GetLog() << sample[i] << " ";
		}
		GetLog() << endl;
		passoutDropData->AddSet(sample);
	}
}
Beispiel #13
0
void MovePicker::goNextPhase() {
	currMove_ = firstMove(); // legalMoves_[0] は番兵
	++phase_;

	switch (phase()) {
	case PH_TacticalMoves0: case PH_TacticalMoves1:
		lastMove_ = generateMoves<CapturePlusPro>(currMove(), pos());
		scoreCaptures();
		return;

	case PH_Killers:
		currMove_ = killerMoves_;
		lastMove_ = currMove() + 2;
		return;

	case PH_NonTacticalMoves0:
		lastMove_ = generateMoves<NonCaptureMinusPro>(currMove(), pos());
		scoreNonCapturesMinusPro<false>();
		currMove_ = lastMove();
		lastNonCapture_ = lastMove_ = generateMoves<Drop>(currMove(), pos());
		scoreNonCapturesMinusPro<true>();
		currMove_ = firstMove();
		lastMove_ = std::partition(currMove(), lastNonCapture(), HasPositiveScore());
		// 要素数は10個くらいまでであることが多い。要素数が少ないので、insertionSort() を使用する。
		insertionSort<MoveStack*, true>(currMove(), lastMove());
		return;

	case PH_NonTacticalMoves1:
		currMove_ = lastMove();
		lastMove_ = lastNonCapture();
		if (static_cast<Depth>(3 * OnePly) <= depth_) {
			std::sort(currMove(), lastMove(), std::greater<MoveStack>());
		}
		return;

	case PH_BadCaptures:
		currMove_ = legalMoves_ + MaxLegalMoves - 1;
		lastMove_ = endBadCaptures_;
		return;

	case PH_Evasions:
	case PH_QEvasions:
		lastMove_ = generateMoves<Evasion>(currMove(), pos());
		if (currMove() + 1 < lastMove()) {
			scoreEvasions();
		}
		return;

	case PH_QCaptures0:
		lastMove_ = generateMoves<CapturePlusPro>(firstMove(), pos());
		scoreCaptures();
		return;

	case PH_QCaptures1:
		lastMove_ = generateMoves<Recapture>(firstMove(), pos(), recaptureSquare_);
		scoreCaptures();
		return;

	case EvasionSearch: case QSearch: case QEvasionSearch: case QRecapture: case ProbCut:
		// これが無いと、MainSearch の後に EvasionSearch が始まったりしてしまう。
		phase_ = PH_Stop;

	case PH_Stop:
		lastMove_ = currMove() + 1;
		return;

	default: UNREACHABLE;
	}
}