Exemplo n.º 1
0
Score SEEMap(Board &board, Square sq)
{
	board.ResetSee();

	return -StaticExchangeEvaluationSq(board, sq, true);
}
Exemplo n.º 2
0
void Cycle::testForMove(Board b) {

	srand(static_cast<unsigned int>(time(0)));
	int ran = rand() % 10;
	int r = row;
	int c = column;

	///   Locate cell in front of Cycle.
	if (direction == N)
		r = row - 1;
	if (direction == S)
		r = row + 1;
	if (direction == W)
		c = column - 1;
	if (direction == E)
		c = column + 1;
	
	///   Cycle has chance to turn before crash. May turn any direction but current.
	if (b.getBoardPos(r, c) != ' ') {
		if (ran < DIFFICULTY_1) {
			do {
				ran = rand() % 4;				
			} while (direction == (Direction)ran);
			direction = (Direction)ran;
		}
	}
	///   Cycle may make ninety degree turn. Chance of turn increases in zones near border.
	///   Zone 1
	else if (((row == 2 || row == 3) && direction == N) || ((row == 33 || row == 34) && direction == S)){
		if (ran < DIFFICULTY_2) {
			ran = ran % 2;
			if (ran == 0)
				direction = E;
			else
				direction = W;
		}
	}
	else if (((column == 2 || column == 3) && direction == W) || ((column == 75 || column == 76) && direction == E)){
		if (ran < DIFFICULTY_2) {
			ran = ran % 2;
			if (ran == 0)
				direction = N;
			else
				direction = S;
		}
	}
	///   Zone 2
	else if (((row >= 4 && row <= 6) && direction == N) || ((row >= 30 && row <= 32) && direction == S)){
		if (ran < DIFFICULTY_3) {
			ran = ran % 2;
			if (ran == 0)
				direction = E;
			else
				direction = W;
		}
	}
	else if (((column >= 4 && column <= 6) && direction == W) || ((column >= 72 && column <= 74) && direction == E)){
		if (ran < DIFFICULTY_3) {
			ran = ran % 2;
			if (ran == 0)
				direction = N;
			else
				direction = S;
		}
	}
	///   Zone 3
	else if (ran < DIFFICULTY_4){		
			ran = ran % 2;
			if (direction == N || direction == S) {
				if (ran == 0)
					direction = E;
				else
					direction = W;
			}
			else if (direction == E || direction == W) {
				if (ran == 0)
					direction = N;
				else
					direction = S;
			}			
	}
}
Exemplo n.º 3
0
float BoardDetector::detect(const vector< Marker > &detectedMarkers, const BoardConfiguration &BConf, Board &Bdetected, Mat camMatrix, Mat distCoeff,
                            float markerSizeMeters) throw(cv::Exception) {
    if (BConf.size() == 0)
        throw cv::Exception(8881, "BoardDetector::detect", "Invalid BoardConfig that is empty", __FILE__, __LINE__);
    if (BConf[0].size() < 2)
        throw cv::Exception(8881, "BoardDetector::detect", "Invalid BoardConfig that is empty 2", __FILE__, __LINE__);
    // compute the size of the markers in meters, which is used for some routines(mostly drawing)
    float ssize;
    if (BConf.mInfoType == BoardConfiguration::PIX && markerSizeMeters > 0)
        ssize = markerSizeMeters;
    else if (BConf.mInfoType == BoardConfiguration::METERS) {
        ssize = cv::norm(BConf[0][0] - BConf[0][1]);
    }

    // cout<<"markerSizeMeters="<<markerSizeMeters<<endl;
    Bdetected.clear();
    /// find among detected markers these that belong to the board configuration
    for (unsigned int i = 0; i < detectedMarkers.size(); i++) {
        int idx = BConf.getIndexOfMarkerId(detectedMarkers[i].id);
        if (idx != -1) {
            Bdetected.push_back(detectedMarkers[i]);
            Bdetected.back().ssize = ssize;
        }
    }
    // copy configuration
    Bdetected.conf = BConf;
    //

    bool hasEnoughInfoForRTvecCalculation = false;
    if (Bdetected.size() >= 1) {
        if (camMatrix.rows != 0) {
            if (markerSizeMeters > 0 && BConf.mInfoType == BoardConfiguration::PIX)
                hasEnoughInfoForRTvecCalculation = true;
            else if (BConf.mInfoType == BoardConfiguration::METERS)
                hasEnoughInfoForRTvecCalculation = true;
        }
    }

    // calculate extrinsic if there is information for that
    if (hasEnoughInfoForRTvecCalculation) {

        // calculate the size of the markers in meters if expressed in pixels
        double marker_meter_per_pix = 0;
        if (BConf.mInfoType == BoardConfiguration::PIX)
            marker_meter_per_pix = markerSizeMeters / cv::norm(BConf[0][0] - BConf[0][1]);
        else
            marker_meter_per_pix = 1; // to avoind interferring the process below

        // now, create the matrices for finding the extrinsics
        vector< cv::Point3f > objPoints;
        vector< cv::Point2f > imagePoints;
        for (size_t i = 0; i < Bdetected.size(); i++) {
            int idx = Bdetected.conf.getIndexOfMarkerId(Bdetected[i].id);
            assert(idx != -1);
            for (int p = 0; p < 4; p++) {
                imagePoints.push_back(Bdetected[i][p]);
                const aruco::MarkerInfo &Minfo = Bdetected.conf.getMarkerInfo(Bdetected[i].id);
                objPoints.push_back(Minfo[p] * marker_meter_per_pix);
                //  		cout<<objPoints.back()<<endl;
            }
        }
        if (distCoeff.total() == 0)
            distCoeff = cv::Mat::zeros(1, 4, CV_32FC1);

        // 	    for(size_t i=0;i< imagePoints.size();i++){
        // 		cout<<objPoints[i]<<" "<<imagePoints[i]<<endl;
        // 	    }
        // 	    cout<<"cam="<<camMatrix<<" "<<distCoeff<<endl;
        cv::Mat rvec, tvec;
        cv::solvePnP(objPoints, imagePoints, camMatrix, distCoeff, rvec, tvec);
        rvec.convertTo(Bdetected.Rvec, CV_32FC1);
        tvec.convertTo(Bdetected.Tvec, CV_32FC1);
        //             cout<<rvec<< " "<<tvec<<" _setYPerpendicular="<<_setYPerpendicular<<endl;

        {
            vector< cv::Point2f > reprojected;
            cv::projectPoints(objPoints, rvec, tvec, camMatrix, distCoeff, reprojected);
            double errSum = 0;
            // check now the reprojection error and
            for (size_t i = 0; i < reprojected.size(); i++) {
                errSum += cv::norm(reprojected[i] - imagePoints[i]);
            }
            //                  cout<<"AAA RE="<<errSum/double ( reprojected.size() ) <<endl;
        }
        // now, do a refinement and remove points whose reprojection error is above a threshold, then repeat calculation with the rest
        if (repj_err_thres > 0) {
            vector< cv::Point2f > reprojected;
            cv::projectPoints(objPoints, rvec, tvec, camMatrix, distCoeff, reprojected);

            vector< int > pointsThatPassTest; // indices
            // check now the reprojection error and
            for (size_t i = 0; i < reprojected.size(); i++) {
                float err = cv::norm(reprojected[i] - imagePoints[i]);
                if (err < repj_err_thres)
                    pointsThatPassTest.push_back(i);
            }
            // cerr<<"Number of points after reprjection test "<<pointsThatPassTest.size() <<"/"<<objPoints.size() <<endl;
            // copy these data to another vectors and repeat
            vector< cv::Point3f > objPoints_filtered;
            vector< cv::Point2f > imagePoints_filtered;
            for (size_t i = 0; i < pointsThatPassTest.size(); i++) {
                objPoints_filtered.push_back(objPoints[pointsThatPassTest[i]]);
                imagePoints_filtered.push_back(imagePoints[pointsThatPassTest[i]]);
            }

            cv::solvePnP(objPoints_filtered, imagePoints_filtered, camMatrix, distCoeff, rvec, tvec);
            rvec.convertTo(Bdetected.Rvec, CV_32FC1);
            tvec.convertTo(Bdetected.Tvec, CV_32FC1);
        }


        // now, rotate 90 deg in X so that Y axis points up
        if (_setYPerpendicular)
            rotateXAxis(Bdetected.Rvec);
        //         cout<<Bdetected.Rvec.at<float>(0,0)<<" "<<Bdetected.Rvec.at<float>(1,0)<<" "<<Bdetected.Rvec.at<float>(2,0)<<endl;
        //         cout<<Bdetected.Tvec.at<float>(0,0)<<" "<<Bdetected.Tvec.at<float>(1,0)<<" "<<Bdetected.Tvec.at<float>(2,0)<<endl;
    }

    float prob = float(Bdetected.size()) / double(Bdetected.conf.size());
    return prob;
}
Exemplo n.º 4
0
int main(int argc, char **argv) {
    Board board;
    int value;
    Board::socket_t move;
    bool tuzdek;

    char answer;
    cout << "Do you want to begin (Y/N)? ";
    cin >> answer;
    bool firstComp = (answer != 'Y');

    while (true) {
        if (firstComp) {
            busy();
            minimax(board, D, 0, move, tuzdek);
            board.pli(move, tuzdek, 0);
            unbusy();
            firstComp = false;
        }

        int playerMove;
        cout << board.rotate();

        if (board.kaznas[1] > K * N) {
            cout << "You win." << endl;
            break;
        } else if (board.kaznas[0] > K * N) {
            cout << "You lose." << endl;
            break;
        }

        cout << "Your move: ";
        cin >> playerMove;
        //playerMove = std::rand() % 9 + 1;
        Board::socket_t pMove = playerMove + K - 1;
        if (board.sockets[pMove] == 0) {
            cout << "Cannot play at " << playerMove << endl;
            continue;
        }

        auto target = board.playSocket(pMove);
        if (board.tuzdekPossible(target, 1)) {
            cout << "Create tuzdek at opponent's " << (static_cast<int> (target) + 1) << " (Y/N) ";
            cin >> answer;
            if (answer == 'Y') {
                board.tuzdeks[1] = target;
            }
        }
        board.accountSocket(target, 1);

        busy();
        auto value = minimax(board, D, 0, move, tuzdek);
        if (move == -1) {
            cout << "Game ended." << endl;
            // TODO determine winner from kaznas
            break;
        }
        board.pli(move, tuzdek, 0);
        cout << "Opponent's move: " << (static_cast<int> (move) + 1) << " (worst outcome: " << value << ")" << endl;
        unbusy();
    }
Exemplo n.º 5
0
void loop(void)
{
    static bool     accCalibrated;
    static uint16_t calibratingA;
    static uint32_t currentTime;
    static uint32_t disarmTime;

    if (rcTask.checkAndUpdate(currentTime)) {

        // update RC channels
        rc.update();

        // when landed, reset integral component of PID
        if (rc.throttleIsDown()) 
            stab.resetIntegral();

        if (rc.changed()) {

            if (armed) {      // actions during armed

                // Disarm on throttle down + yaw
                if (rc.sticks == THR_LO + YAW_LO + PIT_CE + ROL_CE) {
                    if (armed) {
                        armed = false;
                        // Reset disarm time so that it works next time we arm the board.
                        if (disarmTime != 0)
                            disarmTime = 0;
                    }
                }
            } else {         // actions during not armed

                // gyro calibration
                if (rc.sticks == THR_LO + YAW_LO + PIT_LO + ROL_CE) 
                    calibratingG = calibratingGyroCycles;

                // Arm via throttle-low / yaw-right
                if (rc.sticks == THR_LO + YAW_HI + PIT_CE + ROL_CE)
                    if (calibratingG == 0 && accCalibrated) 
                        if (!rc.auxState()) // aux switch must be in zero position
                            if (!armed)          
                                armed = true;

                // accel calibration
                if (rc.sticks == THR_HI + YAW_LO + PIT_LO + ROL_CE)
                    calibratingA = calibratingAccCycles;

            } // not armed

        } // rc.changed()

        // Switch to alt-hold when switch moves to position 1 or 2
        nav.checkSwitch();

    } else {                    // not in rc loop

        static int taskOrder;   // never call all functions in the same loop, to avoid high delay spikes

        switch (taskOrder) {
            case 0:
                if (baro.available())
                    baro.update();
                taskOrder++;
                break;
            case 1:
                if (baro.available() && altitudeEstimationTask.checkAndUpdate(currentTime)) {
                    nav.updateAltitudePid(armed);
                }
                taskOrder++;
                break;
            case 2:
                taskOrder++;
                break;
            case 3:
                taskOrder++;
                break;
            case 4:
                taskOrder = 0;
                break;
        }
    }

    currentTime = board.getMicros();

    if (imuTask.checkAndUpdate(currentTime)) {

        imu.update(currentTime, armed, calibratingA, calibratingG);

        haveSmallAngle = abs(imu.angle[0]) < CONFIG_SMALL_ANGLE && abs(imu.angle[1]) < CONFIG_SMALL_ANGLE;

        // measure loop rate just afer reading the sensors
        currentTime = board.getMicros();

        // compute exponential RC commands
        rc.computeExpo();

        // use LEDs to indicate calibration status
        if (calibratingA > 0 || calibratingG > 0) 
            board.ledGreenOn();
        else {
            if (accCalibrated)
                board.ledGreenOff();
            if (armed)
                board.ledRedOn();
            else
                board.ledRedOff();
        }

        // periodically update accelerometer calibration status
        if (accelCalibrationTask.check(currentTime)) {
            if (!haveSmallAngle) {
                accCalibrated = false; 
                board.ledGreenToggle();
                accelCalibrationTask.update(currentTime);
            } else {
                accCalibrated = true;
            }
        }

        // handle serial communications
        msp.update(armed);

        // perform navigation tasks (alt-hold etc.)
        nav.perform();

        // update stability PID controller 
        stab.update();

        // update mixer
        mixer.update(armed);

    } // IMU update

} // loop()
Exemplo n.º 6
0
	void Entity::goDown(Board& board, Environnement& env) 
	{
		if (moveToThisLocation(board, board.getValidValue(_loc + Coord::DOWN), env)) {
			_lastAction = MOVE_DOWN;
		}
	}
Exemplo n.º 7
0
bool Player::MakeTurn(Board& board, COORDS c) {

	return board.Hit(c) != NO_BOOM;
}
Exemplo n.º 8
0
 void update(const Board& board, Disc disc, eval_t error, int beta, int n_sample) {
   Board next = board;
   next.move(search_next(board, disc), disc);
   evaluator_.update(next, (Disc)-disc, error, beta, n_sample);
 }
Exemplo n.º 9
0
Vector3d getRayColor(Vector3d p0, Vector3d ray, int rec) {

  ray.normalize();

  if (rec == 0) {
    return Vector3d(0,0,0);
  }

  // 最小のt
  double tmin = -1;
  Vector3d P, N, color;

  // レイを飛ばして球と交差するか求める
  for(int i = 0; i < sphere_n; i++) {
    double t_sphere = sphere[i].getIntersec(p0, ray);

    if( (t_sphere > 0) && (t_sphere < tmin || tmin == -1) ) { // 球との交点がある
      tmin = t_sphere;
      // ★前回の課題を参考に、球体の表面の色を計算で求め、colorVecに設定する

      double Is = 0; // 鏡面反射光
      double Id = 0; // 拡散反射光

      //
      // 拡散反射光を計算する
      //

      // 球と視点ベクトルの交点座標 P
      P = p0 + ray * t_sphere;
      // 球の中心座標 C
      Vector3d C = sphere[i].center;
      // 法線ベクトル  N = P - C
      N = P - C;
      // Nを正規化する
      N.normalize();
      // Lambertの反射(拡散反射光)
      Id = -Iin * Kd * getCos(N, lightDirection);
      Id = Id > 0 ? Id : 0;

      //
      // 鏡面反射光を計算する
      //

      // 反射光 R=2(L・N)N-L
      Vector3d R = reflect(-lightDirection, N);
      // Phongの反射(鏡面反射光)
      Is = Iin * Ks * pow2(getCos(R, ray), Ns);
      Is = Is > 0 ? Is : 0;

      double I = Id + Is + Ia;
      double r = I * sphere[i].cR;
      double g = I * sphere[i].cG;
      double b = I * sphere[i].cB;
      color.set(r,g,b);
    } 
  }

  // レイを飛ばして床と交差するか求める
  double t_board = board.getIntersec(p0, ray);

  if( (t_board > 0) && (t_board < tmin || tmin == -1) ) { // 床との交点がある
    tmin = t_board;
    // ★床の表面の色を設定する
    P = p0 + ray * t_board;
    color =  board.getColorVec(P.x, P.z);
    // ★球の影になる場合は、RGBの値をそれぞれ0.5倍する
    Vector3d ray2 = -lightDirection;
    for(int i = 0; i < sphere_n; i++) {
      double t = sphere[i].getIntersec(P, ray2);
      if(t>0) {
        color = color * 0.5;
      }
    }
    N.set(0,1,0);
  }

  if (tmin != -1) {
    return color + getRayColor(P, reflect(ray,N), rec-1) * 0.5;
  } else {
    // 何とも交差しない
    return Vector3d(0,0,0);
  }
}
Exemplo n.º 10
0
int main(int argc, const char* argv[]){
	ifstream infile;
	infile.open("C-small-attempt2.in");
    ofstream outfile;
	outfile.open("C-small222.out");
	
    int T;
    infile >> T;
  for(int i=0; i<T; i++) {
    int r, c, m;
	infile >> r >> c >> m;
	Board a(r,c,m);
	Board *b = &a;
	
	outfile <<"Case #" <<i+1<<":"<<endl;

	if(m>=0&&(m+1)==(r*c)){
	    b->ConfigMine1();
		b->findc2();  //
		outfile<< b->toPrint();
	}
	else if((r*c-m)==4&&m>=0){
		b->ConfigMine6();
        b->setvalues();
	    if(b->checkpossible()){
	      b->findc();
	      outfile << b->toPrint();
	    }else{
			outfile<<"Impossible"<<endl;
		}
	}
	else{
	  b->ConfigMine1();
      b->setvalues();
	  if(b->checkpossible()){
	    b->findc();
	    outfile << b->toPrint() ;
	  }else{
		b->ConfigMine2();
		b->setvalues();
        if(b->checkpossible()){
	        b->findc();
	        outfile << b->toPrint() ;
	    }else{
		    b->ConfigMine3();
		    b->setvalues();
            if(b->checkpossible()){
	            b->findc();
	            outfile << b->toPrint() ;
	        }else{
		        b->ConfigMine4();
		        b->setvalues();
                if(b->checkpossible()){
	               b->findc();
	               outfile << b->toPrint() ;
	            }else{
		            b->ConfigMine5();
		            b->setvalues();
                    if(b->checkpossible()){
	                    b->findc();
	                    outfile << b->toPrint() ;
	                 }else{
                        outfile << "Impossible" <<endl;
					}
				}
			}
		}
	  }
	}
	}
	
  /*
  while(true){
	
	int r, c, m;
	cin>> r >> c >> m;
	Board a(r,c,m);
	Board *b = &a;

	cout<<b->toPrint();
	cout<<"Solution:"<<endl;
	

	cout<<fixed;
	//cout<<"Case #" <<i+1<<":"<<endl;
	if(m>=0&&(m+1)==(r*c)){
	    b->ConfigMine1();
		b->findc2();  //
		cout<< b->toPrint();
	}
	else if((r*c-m)==4&&m>=0){
		b->ConfigMine6();
        b->setvalues();
	    if(b->checkpossible()){
	      b->findc();
	      cout << b->toPrint();
	    }else{
			cout<<"Impossible"<<endl;
		}
	}
	else{
	  b->ConfigMine1();
      b->setvalues();
	  if(b->checkpossible()){
	    b->findc();
	    cout << b->toPrint() ;
	  }else{
		b->ConfigMine2();
		b->setvalues();
        if(b->checkpossible()){
	        b->findc();
	        cout << b->toPrint() ;
	    }else{
		    b->ConfigMine3();
		    b->setvalues();
            if(b->checkpossible()){
	            b->findc();
	            cout << b->toPrint() ;
	        }else{
		        b->ConfigMine4();
		        b->setvalues();
                if(b->checkpossible()){
	               b->findc();
	               cout << b->toPrint() ;
	            }else{
		            b->ConfigMine5();
		            b->setvalues();
                    if(b->checkpossible()){
	                    b->findc();
	                    cout << b->toPrint() ;
	                 }else{
                        cout << "Impossible" <<endl;
					}
				}
			}
		}
	  }
	}
  }
  */
	return 0;	
}
Exemplo n.º 11
0
pos_t CompoundAIPlayer::play(Board& board) {
	if (board.empty_cnt() <= 10) {
		return lookn.play(board);
	}
	return look2.play(board);
}
Exemplo n.º 12
0
bool Mate::isProtected_(const Board& board, Bitboard& bb, const Bitboard& occ, const Bitboard& occNoAttacker) {
  const auto& king = black ? board.getBKingSquare() : board.getWKingSquare();
  bool hasHand = black
    ? (board.getBlackHand(Piece::Pawn) != 0 ||
       board.getBlackHand(Piece::Lance) != 0 ||
       board.getBlackHand(Piece::Knight) != 0 ||
       board.getBlackHand(Piece::Silver) != 0 ||
       board.getBlackHand(Piece::Gold) != 0 ||
       board.getBlackHand(Piece::Bishop) != 0 ||
       board.getBlackHand(Piece::Rook) != 0)
    : (board.getWhiteHand(Piece::Pawn) != 0 ||
       board.getWhiteHand(Piece::Lance) != 0 ||
       board.getWhiteHand(Piece::Knight) != 0 ||
       board.getWhiteHand(Piece::Silver) != 0 ||
       board.getWhiteHand(Piece::Gold) != 0 ||
       board.getWhiteHand(Piece::Bishop) != 0 ||
       board.getWhiteHand(Piece::Rook) != 0);

  if (hasHand) {
    BB_EACH_OPE(to, bb, {
        if (isProtected_<black>(board, to, occ, occNoAttacker, king)) { return true; }
    });
  } else {
Exemplo n.º 13
0
bool Mate::isProtected_(const Board& board, const Square to, const Bitboard& occ, const Bitboard& occNoAttacker, const Square king) {
  // pawn
  Bitboard bb = (black ? board.getBPawn() : board.getWPawn()) & occNoAttacker;
  if (bb.check(black ? to.safetyDown() : to.safetyUp())) {
    return true;
  }

  // lance
  bb = (black ? board.getBLance() : board.getWLance()) & occNoAttacker;
  bb &= black ? MoveTables::wlance(to, occ) : MoveTables::blance(to, occ);
  if (bb) { return true; }

  // knight
  bb = (black ? board.getBKnight() : board.getWKnight()) & occNoAttacker;
  bb &= black ? MoveTables::wknight(to) : MoveTables::bknight(to);
  if (bb) { return true; }

  // silver
  bb = (black ? board.getBSilver() : board.getWSilver()) & occNoAttacker;
  bb &= black ? MoveTables::wsilver(to) : MoveTables::bsilver(to);
  if (bb) { return true; }

  // gold
  bb = (black ? board.getBGold() : board.getWGold()) & occNoAttacker;
  bb &= black ? MoveTables::wgold(to) : MoveTables::bgold(to);
  if (bb) { return true; }

  // bishop
  bb = (black ? board.getBBishop() : board.getWBishop()) & occNoAttacker;
  bb &= MoveTables::bishop(to, occ);
  if (bb) { return true; }

  // rook
  bb = (black ? board.getBRook() : board.getWRook()) & occNoAttacker;
  bb &= MoveTables::rook(to, occ);
  if (bb) { return true; }

  // tokin
  bb = (black ? board.getBTokin() : board.getWTokin()) & occNoAttacker;
  bb &= black ? MoveTables::wgold(to) : MoveTables::bgold(to);
  if (bb) { return true; }

  // promoted lance
  bb = (black ? board.getBProLance() : board.getWProLance()) & occNoAttacker;
  bb &= black ? MoveTables::wgold(to) : MoveTables::bgold(to);
  if (bb) { return true; }

  // promoted knight
  bb = (black ? board.getBProKnight() : board.getWProKnight()) & occNoAttacker;
  bb &= black ? MoveTables::wgold(to) : MoveTables::bgold(to);
  if (bb) { return true; }

  // promoted silver
  bb = (black ? board.getBProSilver() : board.getWProSilver()) & occNoAttacker;
  bb &= black ? MoveTables::wgold(to) : MoveTables::bgold(to);
  if (bb) { return true; }

  // horse
  bb = (black ? board.getBHorse() : board.getWHorse()) & occNoAttacker;
  bb &= MoveTables::horse(to, occ);
  if (bb) { return true; }

  // dragon
  bb = (black ? board.getBDragon() : board.getWDragon()) & occNoAttacker;
  bb &= MoveTables::dragon(to, occ);
  if (bb) { return true; }

  // king
  if (king.isValid()) {
    if (MoveTables::king(king).check(to) &&
        (!recursive || !isProtected_<!black>(board, to, occ, occNoAttacker, Square::Invalid))) {
      return true;
    }
  }

  return false;
}
Exemplo n.º 14
0
#include <tuple>
using std::tuple;
using std::make_tuple;
// For _1, used with std::bind




// ***** Test Cases *****


TEST_CASE("2 param  Constructor", "[Board]")
{
	const int SIZE = 10;
	const int CELLS = SIZE*SIZE;
	Board primary(SIZE,true);

	REQUIRE(primary.getSize() == SIZE);
	REQUIRE(primary.isPrimary() == true);

	Board target(SIZE,false); //Testing Target board construction
	REQUIRE(target.getSize() == SIZE);
	REQUIRE(target.isPrimary() == false);

}

TEST_CASE(" Testing manipulating cells from board","[BOARD]")
{
	const int SIZE = 10;
	const int CELLS = SIZE*SIZE;
	Board cellTest(SIZE,true);
Exemplo n.º 15
0
void MyDomain::received(char* str)
{

    if (strncmp(str, "quit", 4)==0) {
	l.exit();
	return;
    }

    if (strncmp(str, "pos ", 4)!=0) return;

    b.setState(str+4);
    if (verbose) {
	printf("\n\n==========================================\n");
	printf(str+4);
    }

    int state = b.validState();
    if ((state != Board::valid1) && 
	(state != Board::valid2)) {
	printf("%s\n", Board::stateDescription(state));
	switch(state) {
	    case Board::timeout1:
	    case Board::timeout2:
	    case Board::win1:
	    case Board::win2:
		l.exit();
	    default:
		break;
	}
	return;
    }

    if (b.actColor() & myColor) {
	struct timeval t1, t2;

	gettimeofday(&t1,0);
	Move m = b.bestMove();
	gettimeofday(&t2,0);

	int msecsPassed =
	    (1000* t2.tv_sec + t2.tv_usec / 1000) -
	    (1000* t1.tv_sec + t1.tv_usec / 1000);

	printf("%s ", (myColor == Board::color1) ? "O":"X");
	if (m.type == Move::none) {
	    printf(" can not draw any move ?! Sorry.\n");
	    return;
	}
	printf("draws '%s' (after %d.%03d secs)...\n",
	       m.name(), msecsPassed/1000, msecsPassed%1000);

	b.playMove(m, msecsPassed);
	sendBoard();

	if (changeEval)
	    ev.changeEvaluation();

	/* stop player at win position */
	int state = b.validState();
	if ((state != Board::valid1) && 
	    (state != Board::valid2)) {
	    printf("%s\n", Board::stateDescription(state));
	    switch(state) {
		case Board::timeout1:
		case Board::timeout2:
		case Board::win1:
		case Board::win2:
		    l.exit();
		default:
		    break;
	    }
	}

	maxMoves--;
	if (maxMoves == 0) {
	    printf("Terminating because given number of moves drawn.\n");
	    broadcast("quit\n");
	    l.exit();
	}
    }    
}
Exemplo n.º 16
0
//This function gets the conditions to end the game
void win(Board& game) {
	if ((game.get_bc() + game.get_wc() == 64) || (game.get_bc() == 0) || (game.get_wc() == 0))
	{
		cout << "Game Over!" << endl;
		cout << "BLACK VS WHITE: \n";
		cout << game.get_bc() << " : " << game.get_wc() << endl;

		if (game.get_bc() == 0){
			cout << "White Wins!" << endl;
		}
		if (game.get_wc() == 0){
			cout << "Black Wins!" << endl;
		}
		if ((game.get_bc() + game.get_wc() == 64) && game.get_bc() > game.get_wc())
		{
			cout << "Black Wins!" << endl;
		}
		if ((game.get_bc() + game.get_wc() == 64) && game.get_wc() > game.get_bc())
		{
			cout << "White Wins!" << endl;
		}
		if ((game.get_bc() + game.get_wc() == 64) && game.get_wc() == game.get_bc()){
			cout << "DRAW!" << endl;
		}
		exit(0);
	}
}
Exemplo n.º 17
0
	void Entity::goRight(Board& board, Environnement& env) 
	{
		if (moveToThisLocation(board, board.getValidValue(_loc + Coord::RIGHT), env)) {
			_lastAction = MOVE_RIGHT;
		}
	}
Exemplo n.º 18
0
int main(int argc, char const *argv[])
{
  // cout << "Hello world";
  Board* board;

  cout << "Sample test: " << endl;
  board = new Board(3);
  board->SetCell(0, 0, 0, 'x');
  board->SetCell(0, 0, 1, 'o');
  board->SetCell(0, 0, 2, 'x');
  board->SetCell(0, 1, 0, 'o');
  board->SetCell(0, 1, 1, 'x');
  board->SetCell(0, 1, 2, '.');
  board->SetCell(0, 2, 0, 'o');
  board->SetCell(0, 2, 1, 'x');
  board->SetCell(0, 2, 2, 'o');
  board->Print(0);
  board->Print(1);
  cout << "changing board cell [0][2] to 'M' from player 0's perspective would result in the board: " << endl;
  board->SetCell(0, 0, 2, 'M');
  board->Print(0);
  cout << "while changing board cell [0][2] to 'M' from player 1's perspective would result in the board" << endl;
  board->Print(1);

  cout << "test with size 5" << endl;
  board = new Board(5);
  board->SetCell(1, 0, 0, 'c');
  board->SetCell(0, 0, 4, 'x');
  board->SetCell(1, 3, 2, 'l');
  board->SetCell(0, 0, 0, 'p');
  board->Print(0);
  board->Print(1);

  board = new Board(5);
  board->SetCell(0, 0, 0, 'x');
  board->SetCell(0, 1, 1, 'y');
  board->SetCell(1, 0, 0, 'g');
  board->SetCell(1, 0, 0, 'x');
  board->SetCell(0, 0, 0, 'f');
  board->SetCell(0, 3, 3, 'p');
  board->SetCell(0, 3, 0, 't');
  board->SetCell(1, 0, 3, 'l');
  board->Print(0);
  board->Print(1);

  cout << "test with size 19" << endl;
  board = new Board(19);
  board->SetCell(1, 0, 0, 'c');
  board->SetCell(0, 0, 4, 'x');
  board->SetCell(1, 3, 2, 'l');
  board->SetCell(0, 0, 0, 'p');
  board->Print(0);
  board->Print(1);
  
  board = new Board(19);
  board->SetCell(0, 0, 0, 'x');
  board->SetCell(0, 1, 1, 'y');
  board->SetCell(1, 0, 0, 'g');
  board->SetCell(1, 0, 0, 'x');
  board->SetCell(0, 0, 0, 'f');
  board->SetCell(0, 3, 3, 'p');
  board->SetCell(0, 3, 0, 't');
  board->SetCell(1, 0, 3, 'l');
  board->Print(0);
  board->Print(1);

  return 0;
}
Exemplo n.º 19
0
int main(int argc, char *argv[], char* envp[])
{
	// If this were a larger project, I'd set up a separate GTest project for this, but that's a lot of work to get a handful of unit tests implemented
	// and as such is a pretty excessive solution to my problem.

	writeLogLine("Starting boggle solver");

	char path_to_dictionary[kArbitraryMaxPath];
	char path_to_puzzle[kArbitraryMaxPath];
	char path_to_results[kArbitraryMaxPath];

	if (argc != 4)
	{
		writeLogLine("Boggle Solver Command Line Arguments:");
		writeLogLine("BoggleSolver.exe {PATH_TO_DICTIONARY} {PATH_TO_PUZZLE} {RESULTS_FILE}");
		pauseForClose();
		return 1;
	}

	strcpy_s(path_to_dictionary, argv[1]);
	writeLogLineFormatted("Path to dictionary: %s", path_to_dictionary);

	strcpy_s(path_to_puzzle, argv[2]);
	writeLogLineFormatted("Path to puzzle: %s", path_to_puzzle);
	
	strcpy_s(path_to_results, argv[3]);
	writeLogLineFormatted("Path to results file %s", path_to_results);

	CharIndexMap* theMap = new CharIndexMap();

	writeLogLine("Loading dictionary");
	DictionaryTrie theDictionary(theMap);
	bool dictLoaded = theDictionary.LoadFromFile(path_to_dictionary);

	if(!dictLoaded)
	{
		writeLogLine("Dictionary Load Failed");
		pauseForClose();
		return -1;
	}

	writeLogLine("Loading board");
	Board theBoard;
	bool boardLoaded = theBoard.LoadFromFile(path_to_puzzle);

	if(!boardLoaded)
	{
		writeLogLine("Failed board loading");
		pauseForClose();
		return -1;
	}

	ThreadsafeStack<char*> foundWords;
	ThreadsafeStack<std::pair<int, int>> taskStack;
	int columns = theBoard.ColumnCount();
	int rows = theBoard.RowCount();

	for (int thisRow = 0; thisRow < rows; thisRow++)
	{
		for (int thisColumn = 0; thisColumn < columns; thisColumn++)
		{
			taskStack.push(std::pair<int, int>(thisColumn, thisRow));
		}
	}

	clock_t timer;
	timer = clock();

	std::vector<std::thread> threadPool;
	for (int i = 0; i < kThreadPoolSize; i++)
	{
		threadPool.push_back(std::thread(threadBaseLevel, &theBoard, &theDictionary, &taskStack, &foundWords));
	}
	
	for (int i = 0; i < kThreadPoolSize; i++)
	{
		threadPool[i].join();
	}

	timer = clock() - timer;
	float timeSpent = static_cast<float>(timer) / CLOCKS_PER_SEC;

	writeLogLineFormatted("Took %f to solve", timeSpent);
	writeLogLineFormatted("Found %i words", foundWords.size());

	std::vector<char*> words;

	//We can sort a vector - we can't sort a threadsafestack - we don't care about speed at this point, so let's just make it a vector and go from there.
	while (!foundWords.empty())
	{
		char* word = foundWords.pop();
		words.push_back(word);
	}

	std::sort(words.begin(), words.end(), CompareStringsNoCase);

	std::ofstream outfp(path_to_results);
	if(outfp.is_open())
	{
		for(char* word : words)
		{
			outfp.write(word, strlen(word));
			outfp.write("\n", 1);
		}
	}

	
	//writeLogLine("All words:");
	//for(char* word : foundWords)
	//{
	//	writeLogLineFormatted("%s", word);
	//}

	pauseForClose();

	delete theMap;
	return 0;
}
Exemplo n.º 20
0
 unsigned operator()(const Board& key) const {
   return key.hash();
 }
Exemplo n.º 21
0
void AI::performMove(Board& board) {
	AIMove bestMove = getBestMove(board, _aiPlayer);
	board.setVal(bestMove.x, bestMove.y, _aiPlayer);
}
Exemplo n.º 22
0
 void reset()
 {
     const auto size = board.size();
     this->~Game();
     new (this) Game(size);
 }
Exemplo n.º 23
0
void Mixer::cutMotors(void)
{
    for (uint8_t i = 0; i < 4; i++) {
        board->writeMotor(i, 0);
    }
}
Exemplo n.º 24
0
		void draw(Pos p, int o) {
			for (int b = 0; b < 4; b++) {
				board->drawBlock(p + layouts[type][o][b], type);
			}
		}
Exemplo n.º 25
0
// Displays Cycle bike skin at current position.
void Cycle::showCycle(Board b){

	b.gotoXY(row, column);
	cout << bike;
}
Exemplo n.º 26
0
		void crystalise() {
			for (int b = 0; b < 4; b++) {
				board->setPos(pos + layouts[type][orient][b], type);
			}
		}
Exemplo n.º 27
0
int _tmain(int argc, _TCHAR* argv[]){
	
	// resize console window
	HWND console = GetConsoleWindow();
	RECT r;
	GetWindowRect(console, &r); //stores the console's current dimensions
	MoveWindow(console, r.left, r.top, 800, 500, TRUE); // 800 width, 500 height
	
	//////////////////////
	//  Main Game Loop  //
	//////////////////////

	const int GAME_SPEED = 100;
	const int LEVEL_UP_SCORE = 1000;
	const int SCORE_MULTIPLIER = 10;
	int clockMultiplier = 0, playerPoints = 0, points = 0;
	bool replay = false;
	int keyPressed;
	bool gameOver = false;	
	
	do {
		//setup game board
		Board b;
		Cycle player;
		Cycle comp(true);

		b.clear();
		b.drawBoard();
		player.showCycle(b);
		comp.showCycle(b);
		b.welcomeScreen();

		//wait for player to begin
		bool ready = false;
		while (!ready){
			if (_kbhit()){
				ready = true;
			}
		}
		
		///////////////////////
		//  Inner Game Loop  //
		///////////////////////

		b.clear();
		b.drawBoard();
		player.showCycle(b);
		comp.showCycle(b);	

		while (!gameOver) {
			Sleep(GAME_SPEED - clockMultiplier);

			//test for player input
			if (_kbhit()){

				keyPressed = _getch();

				// key is only assigned a valid value.
				try {
					player.changeDirection(keyPressed);
				}
				catch (const char* msg){
					cerr << msg << endl;
				}
			}

			//player move
			char p = player.markTrail();
			int row = player.getRow();
			int col = player.getColumn();
			b.setBoard(row, col, p);
			player.moveCycle();
			gameOver = player.collisionTest(b);
			player.showCycle(b);

			//computer move
			if (gameOver == false){
				comp.testForMove(b);
				char c = comp.markTrail();
				row = comp.getRow();
				col = comp.getColumn();
				b.setBoard(row, col, c);
				comp.moveCycle();
				gameOver = comp.collisionTest(b);
				comp.showCycle(b);
			}			
		} //end inner game loop

		if (player.testAlive() == false) {
			b.gotoXY(18, 34);
			cout << "Game Over!";
			clockMultiplier -= 10;
		}
		else {
			b.gotoXY(18, 36);
			cout << "You Win!";
			points = LEVEL_UP_SCORE + (clockMultiplier * SCORE_MULTIPLIER);
			playerPoints += points;
			clockMultiplier += 10;
		}

		b.gotoXY(22, 27);
		cout << "Your score this round: " << points;
		b.gotoXY(24, 30);
		cout << "Your total score: " << playerPoints;
		b.gotoXY(28, 20);
		cout << "Would you like to play again? (y,n) ";
		char n;
		cin >> n;
		if (n == 'y' || n == 'Y'){
			replay = true;
			gameOver = false;
		}
	} while (replay == true); 
	//end main game loop
	return 0;
}
Exemplo n.º 28
0
int main(int argc, char* argv[])
{

	MPI_Init(&argc, &argv);

	MPI_Comm_size(MPI_COMM_WORLD, &num_threads);
	MPI_Comm_rank(MPI_COMM_WORLD, &thread_rank);

	parseArgs(argc, argv);
#if 0
        if(thread_rank < 4)
                myColor = Board::color1;
        else {
                myColor = Board::color2;
                thread_rank = thread_rank - 4;
	}
#endif
	SearchStrategy* ss = SearchStrategy::create(strategyNo);
	if (verbose)
		printf("Using strategy '%s' ...\n", ss->name());
	ss->setMaxDepth(maxDepth);

	b.setSearchStrategy( ss );
	ss->setEvaluator(&ev);
	ss->registerCallbacks(new SearchCallbacks(verbose));

	if(thread_rank == 0) {

		MyDomain d(lport);
		if (host) d.addConnection(host, rport);

		l.install(&d);
		l.run();
	}
	else
	{
		while (1)
		{
			MPI_Status mpi_st;
			Slave_Input slave_input;
			Slave_Output slave_output;
			MPI_Recv (&slave_input, sizeof(Slave_Input), MPI_BYTE, 0, 10, MPI_COMM_WORLD, &mpi_st);
			// depth= -1 is a signal for the slave to quit
			if (slave_input.depth == -1)
				break;

			ss->_board = &b;
			ss->_board->setState(slave_input.boardstate);
			ss->_board->playMove(slave_input.move);
			((ABIDStrategy*)ss)->_currentMaxDepth = slave_input.currentMaxDepth;
			ss->_sc->_leavesVisited = 0;
			ss->_sc->_nodesVisited = 0;
			/* check for a win position first */
			if (!ss->_board->isValid())
			{
				slave_output.eval = (14999-(slave_input.depth-1));
			}
			else
			{
				if ((slave_input.depth == slave_input.currentMaxDepth) && (slave_input.move.type > Move::maxPushType ))
					slave_output.eval = ss->evaluate();
				else
					slave_output.eval = -((ABIDStrategy*)ss)->alphabeta(slave_input.depth, slave_input.alpha, slave_input.beta);
			}
			((ABIDStrategy*)ss)->_pv.update(slave_input.depth-1, slave_input.move);

			slave_output.pv = ((ABIDStrategy*)ss)->_pv;
			slave_output.num_leaves = ss->_sc->_leavesVisited;
			slave_output.num_nodes = ss->_sc->_nodesVisited;
			MPI_Send(&slave_output, sizeof(Slave_Output), MPI_BYTE, 0, 10, MPI_COMM_WORLD);
		}

	}
	MPI_Finalize();

}
Exemplo n.º 29
0
int _tmain(int argc, _TCHAR* argv[])
{
	int NUMBER_OF_GAMES;

	bool choice;
	char charchoice;

	cout << "Would you like to watch a game after the program has run? Y for yes, not Y for no.";
	cin >> charchoice;

	if (charchoice == 'Y' || charchoice == 'y')
	{
		choice = true;
	}

	else
	{
		choice = false;
	}

	cout << "Enter a number of games to loop: ";
	cin >> NUMBER_OF_GAMES;

	srand(time(NULL));

	Board board = Board();
	vector<Move> allMoves = PopulateMoves();
	vector<Move> currentGame;

	for (int i = 1; i <= NUMBER_OF_GAMES; i++)
	{
		bool result = GameLoop(board, allMoves, currentGame, false);

		AdjustCoefficients(board, currentGame, allMoves, result);

		board.ResetBoard();
		currentGame.clear();

		if (i % 1000 == 0)
		{
			cout << "Game " << i << " complete.\n";
		}
	}

	cout << "Learning complete. Beginning final game." << endl;
	cin.get();

	ofstream os;

	os.open("coefficients.txt", std::ofstream::out | std::ofstream::trunc);

	if (os.is_open())
	{
		for (int i = 0; i < allMoves.size(); i++)
		{
			for (int j = 0; j < 8; j++)
			{
				for (int k = 0; k < 8; k++)
				{
					os << allMoves[i].GetCoefficient(j, k) << "\n";
				}
			}
		}
	}

	os.close();

	cout << "Would you like to play a game? Y for yes, not Y for no.\n";
	cin >> charchoice;

	if (charchoice == 'Y' || charchoice == 'y')
	{
		HumanVsAI(board, allMoves, currentGame, true);
	}

	else
	{
		GameLoop(board, allMoves, currentGame, choice);
	}
}
Exemplo n.º 30
0
/*
 * Sai Kiran Vadlamudi  C05
 *
 * Main
 * Driver function
 */
int main(const int argc, const char* argv[]) {

	// Seed for random number generator
	srand((unsigned)time(NULL));

	// Check for correct number of command line arguments
	if (argc == 6)
	{
		// Temp variables to store user input from file
		int id = 0, startTime = 0, sendNum = 0, sendSize = 0, routeSize = 0, routeId = 0;
		FILE *input, *outputFCFS, *outputPQ;
		
		// Open files
		outputFCFS = fopen("manetSimFCFS.txt", "w");
		outputPQ = fopen("manetSimPQ.txt", "w");
		input = fopen(argv[5], "r");

		if (outputFCFS != NULL && input != NULL) {
			
			// Print heading and output format
			fprintf(outputFCFS, "Name: Sai Kiran Vadlamudi  Section: C05\n\n");
			fprintf(outputFCFS, "| Source: Arrival Time | All Mules: All Arrival Times | Receiver: Arrival Time\n\n");
			fprintf(outputPQ, "Name: Sai Kiran Vadlamudi  Section: C05\n\n");
			fprintf(outputPQ, "| Source: Arrival Time | All Mules: All Arrival Times | Receiver: Arrival Time\n\n");
			
			// Set-up, Randomize, and print board for first time
			Board manetMap = *new Board(atoi(argv[4]), atoi(argv[4]) + 2, *new vector<Node>(), atoi(argv[1]), atoi(argv[3]), atoi(argv[2]));
			manetMap.createNodeVector();
			manetMap.initializeBoard();
			manetMap.generateRandomNodePos();
			manetMap.setNodePos();
			manetMap.printBoard(outputFCFS);
			manetMap.printBoard(outputPQ);

			// Read in the source node info
			for (int i = 0; i < atoi(argv[1]); i++)
			{
				// Read in the first five properties of the source node in the current line 
				fscanf(input, "%d %d %d %d %d", &id, &startTime, &sendNum, &sendSize, &routeSize);
				
				// Create a vector of ids of mule nodes along the route
				vector<int> temp = *new vector<int>();
				for (int j = 0; j < routeSize; j++)
				{
					fscanf(input, "%d", &routeId);
					temp.push_back(routeId);
				}

				// Add the input properties to the source node matching the given id
				manetMap.findSet(id, startTime, sendNum, sendSize, temp);
			}

			// Run simulation
			manetMap.runSimulation(outputFCFS, outputPQ);

			// Close files
			fclose(input);
			fclose(outputFCFS);
			fclose(outputPQ);

			return 0;
		}
		else {
			// Output file corrupted
			if (outputFCFS == NULL)
				printf("Output File couldn't be opened\n\n");
			// Input file corrupted
			else
				printf("Input File couldn't be opened\n\n");

			return 1;
		}
	}
	else {
		printf("Incorrect Usage! Usage is ./prog5 #_of_sources #_of_recievers #_of_mules dimension input_file\n\n");
		return 1;
	}
}