Beispiel #1
0
void Game::initialize(std::string whiteName, int whiteLevel, std::string blackName, int blackLevel)
{
	tearDown();

	// Game starts with white players turn
	board = Board();
	activeSquare = -1;
	initPlayers(whiteName, whiteLevel, blackName, blackLevel);

	playerOnTurn = white;
	//whitePlayerText.setString("White: " + white->getName());
	//blackPlayerText.setString("Black: " + black->getName());

	// To format info text
	//infoText.setString("Game started!\n" +  playerOnTurn->getName() + "'s turn.");

	timeOffset = 0;
	//clock.restart();
}
void BoardNode::generateChildren(){
	bool flag;
	Board _b;
	///attempt to make every move
	for (int i = 1; i < 9; i++){
		_b = Board(b);
		//update state to reflect turn
		_b._play_state = !_b._play_state;
		flag = _b.applyMove(i);
		if (flag){
			hasChildren = true;
			BoardNode* newChild = new BoardNode(_b);
			newChild->parent = this;
			newChild->b.last_move = i;
			newChild->depth = this->depth + 1;
			this->children.push_back(newChild);
		}
	}
}
void GoUctDefaultPriorKnowledge::AddLocalityBonus(GoPointList& emptyPoints,
                                                  bool isSmallBoard)
{
    const GoBoard& bd = Board();
    const SgPoint last = bd.GetLastMove();
    SgUctValue count = isSmallBoard ? 4 : 5;
    AddBonusNearPoint(emptyPoints, count, last,
                     SgUctValue(1.0),
                     SgUctValue(0.6),
                     SgUctValue(0.6),
                     true /* addPass*/);

    const SgPoint last2 = bd.Get2ndLastMove();
    count = isSmallBoard ? 2 : 3;
    AddBonusNearPoint(emptyPoints, count, last2,
                     SgUctValue(0.8),
                     SgUctValue(0.55),
                     SgUctValue(0.55),
                     false /* don't addPass*/);
}
GoBlock* GoRegionBoard::GetBlock(const SgPointSet& boundary,
                                 SgBlackWhite color) const
{
    SG_ASSERT(UpToDate());

    for (SgVectorIteratorOf<GoBlock> it(AllBlocks(color)); it; ++it)
    {   if (boundary.SubsetOf((*it)->Stones()))
        /* */ return *it; /* */
    }

    SgDebug() << "ERROR: no block on set";
    const int size = Board().Size();
    boundary.Write(SgDebug(), size);
    SgDebug() << "blocks:";
    for (SgVectorIteratorOf<GoBlock> it(AllBlocks(color));it; ++it)
        (*it)->Stones().Write(SgDebug(), size);

    SG_ASSERT(false);
    return 0;
}
// this is a recursive function, the field current_field must be constantly switching now
int MinMaxPlayerNew::getMinMaxScore(Board const& board, Field current_field) {
    
    std::vector<Position> possible_moves = board.getEmptyPositions();
    
    //get the opposite field
    Field opposite_field = getOppositeField(current_field);
    
    //set scores to very low
    int score = -10000;
    int highest_score = -10000;
    
    for (Position move : possible_moves) {
        Board fake_board = Board(board);
        
        //now do an enemy move (switch field) and get the min score for it (then convert it by * -1 to get our score) so we still get the score we want
        fake_board.doMove(move, opposite_field);
        score = -getMinMaxScore(fake_board, opposite_field);
        
        //update highest score if score is higher
        highest_score = std::max(score, highest_score);
    }
    
    
    /* check for the winner

     this function is called with:
     int score = -getMinMaxScore(fake_board, current_field);
     and then repeatedly with:
     score = -getMinMaxScore(fake_board, opposite_field);
     our score is always the - score of the opposite field, so the values are switched, since the fields are constantly switched */
    
    if (board.isWinner(current_field)) { //if the enemy wins
        return -1;
    } else if (board.isWinner(getOppositeField(current_field))) { //if the enemy loses
        return 1;
    } else if (board.isFull()) { //draw
        return 0; 
    }
    
    return highest_score;
}
Beispiel #6
0
/// @brief Initialise window
///
/// @return success or fail
bool SquareApp::OnInit() {
	currentPosition = Board();
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		std::cout << "Error in initialising! SDL error: " << SDL_GetError() << std::endl;
		return false;
	}
	window = SDL_CreateWindow("SDL test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
	if (window == NULL) {
		std::cout << "Window could not be created! SDL error: " << SDL_GetError() << std::endl;
		return false;
	}
	screensurface = SDL_GetWindowSurface(window);
	if ((renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED)) == NULL) {
		std::cout << "Renderer could not be created! SDL error: " << SDL_GetError() << std::endl;
		return false;
	}
	xDistribution = std::uniform_int_distribution<int>(0, SQUARES_X);
	yDistribution = std::uniform_int_distribution<int>(0, SQUARES_Y);
	horverDistribution = std::uniform_int_distribution<int>(0, 1);
	return true;
}
Beispiel #7
0
void SquareApp::KeyPress(SDL_Keysym keyp) {
	switch (keyp.sym) {
		case SDLK_q:
			running = false;
			break;
		case SDLK_r:
			currentPosition = Board();
			break;
		case SDLK_F11:
			if (fullscreen)
				SDL_SetWindowFullscreen(window, 0);
			else
				SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP);
			fullscreen = !fullscreen;
			centreInWindow();
			break;
		case SDLK_c:
			centreInWindow();
		default:
			break;
	}
}
Beispiel #8
0
 std::ostream& operator<< ( std::ostream& s, fas::tuple< Pos, Fig, Board> ) 
 { 
   s << Board();
   
   enum {
     nopos   = fas::same_type< Pos, fas::int_<-1> >::value, 
     nofig   = fas::same_type< e, Fig>::value
   };
   
   if ( nopos )
   {
     if (nofig)
       s << "Draw" << std::endl;
     else
       s << Fig() << " winner (you)" << std::endl;
   }
   else if ( !nofig )
   {
     s << Fig() << " winner (compiler)" << std::endl;
   }
   return s;
 }
Beispiel #9
0
Game::Game(int numTeams, int numPlayers)
{

    board = Board();
    teams = vector<Team>();
    for (int i = 0; i < numTeams; i++){
        teams.push_back(Team());
    }
    players = vector<Player*>();
    for (int i = 0; i < numPlayers; i++){
        players.push_back(new Player_Human());
    }
    deck = deque<Card>();
    this->createDeck();
    discard = vector<Card>();
    currentTurn = 0;
    gameCompleted = false;
    for (unsigned long i = 0; i < players.size(); i++){
        dealHandToPlayer(players[i]);
    }
    for (unsigned long i = 0; i < players.size(); i++){
        players[i]->printHand();
    }
}
Beispiel #10
0
void GameManager::testDriver(std::ifstream &input) {
    std::string nextLine;
    char layout[7][7];
    for (int i = 0; i < 7; i++) {
        std::getline(input, nextLine);
        for (int j = 0; j < 7; j++) {
            layout[i][j] = nextLine[j];
        }
    }
    board = Board(layout);
    if (!gameHasBeenWon()) {
        updateCurrentPlayer();
        playOneFullTurn(input);
        if (!gameHasBeenWon()) {
            updateCurrentPlayer();
            playOneFullTurn(input);
        } else {
            printWinner();
        }
    } else {
        printWinner();
    }
    std::cout << board;
}
void 
GoUctDefaultPriorKnowledge::InitializeForGlobalHeuristic(
	const GoPointList& empty,
    const SgPointSet& pattern,
    const SgPointSet& atari,
    int nuSimulations)
{
    const GoBoard& bd = Board();
    for (GoPointList::Iterator it(empty); it; ++it)
    {
        const SgPoint p = *it;
        SG_ASSERT (bd.IsEmpty(p));
        if (BadSelfAtari(bd, p))
            Initialize(p, 0.1f, nuSimulations);
        else if (atari[p])
            Initialize(p, 1.0f, 3);
        else if (pattern[p])
            Initialize(*it, 
                       0.6 + (m_patternGammas[*it] / m_maxPatternGamma) * 0.4,
                       3);
		else
            Initialize(p, 0.5f, 3);
    }
}
Beispiel #12
0
Board
Board::scaled( double s )
{
  return static_cast<const Board &>( Board( *this ).scale( s ) );
}
Beispiel #13
0
Board
Board::translated( double dx, double dy )
{
  return static_cast<const Board &>( Board( *this ).translate( dx, dy ) );
}
Beispiel #14
0
Board
Board::rotated( double angle )
{
  return static_cast<const Board &>( Board( *this ).rotate( angle ) );
}
Beispiel #15
0
Board
Board::rotated( double angle, const Point & center )
{
  return static_cast<const Board &>( Board( *this ).rotate( angle, center ) );
}
void ribi::tictactoe::Game::Test() noexcept
{
  {
    static bool is_tested{false};
    if (is_tested) return;
    is_tested = true;
  }
  {
    Board();
  }
  const TestTimer test_timer(__func__,__FILE__,1.0);
  const bool verbose{false};
  {
    //Check draw detection
    {
      Game t;
      assert(t.GetCurrentPlayer() == Player::player1);
      assert(t.GetCurrentTurn()   == 0);
      t.DoMove(1,1);
      assert(t.GetCurrentPlayer() == Player::player2);
      assert(t.GetCurrentTurn()   == 1);
      t.DoMove(0,0);
      assert(t.GetCurrentPlayer() == Player::player1);
      assert(t.GetCurrentTurn()   == 2);
      t.DoMove(1,2);
      assert(t.GetCurrentPlayer() == Player::player2);
      assert(t.GetCurrentTurn()   == 3);
      t.DoMove(1,0);
      assert(t.GetCurrentPlayer() == Player::player1);
      assert(t.GetCurrentTurn()   == 4);
      t.DoMove(2,0);
      assert(t.GetCurrentPlayer() == Player::player2);
      assert(t.GetCurrentTurn()   == 5);
      t.DoMove(0,2);
      assert(t.GetCurrentPlayer() == Player::player1);
      assert(t.GetCurrentTurn()   == 6);
      t.DoMove(0,1);
      assert(t.GetCurrentPlayer() == Player::player2);
      assert(t.GetCurrentTurn()   == 7);
      t.DoMove(2,1);
      assert(t.GetCurrentPlayer() == Player::player1);
      assert(t.GetCurrentTurn()   == 8);
      t.DoMove(2,2);
      assert(t.GetCurrentPlayer() == Player::player2);
      assert(t.GetCurrentTurn()   == 9);
      assert(t.GetWinner() == Winner::draw);
    }
    //Check player1 wins horizontally detection
    {
      Game t;
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,0);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,0);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,2);
      assert(t.GetWinner() == Winner::player1);
    }
    //Check player2 wins vertically detection
    {
      Game t;
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,0);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,0);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(2,2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,2);
      assert(t.GetWinner() == Winner::player2);
    }
    //Check player1 wins diagonally detection
    {
      Game t;
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,0);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,0);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(2,2);
      assert(t.GetWinner() == Winner::player1);
    }
    //Check no-winner detection
    {
      Game t;
      t.DoMove(1,1);
      t.DoMove(0,0);
      t.DoMove(1,2);
      t.DoMove(1,0);
      t.DoMove(2,0);
      t.DoMove(0,2);
      t.DoMove(0,1);
      t.DoMove(2,1);
      //t.DoMove(2,2); //Final move to make a draw
      assert(t.GetWinner() == Winner::no_winner);
    }
    //Check CanDoMove
    for (int i=0; i!=9; ++i)
    {
      Game t;
      t.DoMove(i/3,i%3);
      assert(t.CanDoMove(i/3,i%3)==false);
    }
    //Check AI's
    {
      for (int a = 0; a!=3; ++a)
      {
        for (int b = 0; b!=3; ++b)
        {
          boost::shared_ptr<Ai> c;
          switch (a)
          {
            case 0: c.reset(new AiEnforceDraw); break;
            case 1: c.reset(new AiEnforceWin); break;
            case 2: c.reset(new AiPlayRandom); break;
          }
          assert(c);
          boost::shared_ptr<Ai> d;
          switch (b)
          {
            case 0: d.reset(new AiEnforceDraw); break;
            case 1: d.reset(new AiEnforceWin); break;
            case 2: d.reset(new AiPlayRandom); break;
          }
          assert(d);
          Game g;
          while (g.GetWinner() == Winner::no_winner)
          {
            const std::pair<int,int> move_1(c->SuggestMove(g));
            assert(g.CanDoMove(move_1.first,move_1.second));
            g.DoMove(move_1.first,move_1.second);
            if (g.GetWinner() != Winner::no_winner) break;
            const std::pair<int,int> move_2(c->SuggestMove(g));
            assert(g.CanDoMove(move_2.first,move_2.second));
            g.DoMove(move_2.first,move_2.second);
          }
          if (verbose) { TRACE(WinnerToName(g.GetWinner())); }
        }
      }
    }
  }
}
GoBlock* GoRegionBoard::GenBlock(SgPoint anchor, SgBlackWhite color)
{
    GoBlock* b = new GoBlock(color, anchor, Board());
    AddBlock(b);
    return b;
}
Beispiel #18
0
Game::Game(Player p1,Player p2) : _p1(p1),_p2(p2),_b{Board()}{

}
Beispiel #19
0
		Game()
		{
			 board = Board();
		}
Beispiel #20
0
void Player::set_board(const Board& b) {
  board = Board(b);
}
Beispiel #21
0
void ModelTest()
{
	int array[4][4]={1};
	int i,j;
	try
	{
		BaseShape bs1(1);
		if (bs1.get_color()==0)
			throw int(2);
		BaseShape bs2(2);
		if (bs2.get_color()!=2)
			throw int(2);

		BaseShape bs3(bs1);
		if (ShapeEqual(bs1,bs3))
			throw int(2);
		if (!ShapeEqual(bs2,bs3))
			throw int(2);
		if (ShapeEqual(bs3,BaseShape(bs1)))
			throw int(2);
		if (!ShapeEqual(bs3,BaseShape(bs2)))
			throw int(2);
		
		BaseShape bs4=bs1;
		if (ShapeEqual(bs1,bs4))
			throw int(2);
		if (!ShapeEqual(bs2,bs4))
			throw int(2);
		BaseShape bs5=BaseShape(bs2);
		if (ShapeEqual(bs2,bs5))
			throw int(2);
		if (!ShapeEqual(bs1,bs5))
			throw int(2);

		BaseShape s(0);

		s.set_x(1);
		if (s.get_x()!=1)
			throw int(2);
		s.set_x(2);
		if (s.get_x()==1)
			throw int(2);
		
		s.set_y(1);
		if (s.get_y()!=1)
			throw int(2);
		s.set_y(2);
		if (s.get_y()==1)
			throw int(2);

		s.set_color(1);
		if (s.get_color()!=1)
			throw int(2);
		s.set_color(2);
		if (s.get_color()==1)
			throw int(2);

		s.move_left();
		if (s.get_x()!=1)
			throw int(2);

		s.move_right();
		s.move_right();
		if (s.get_x()!=3)
			throw int(2);

		s.move_down();
		if (s.get_color()!=1)
			throw int(2);

		for(i=0 ;i<4 ;i++)
		for(j=0 ;j<4 ;j++)
			if (s.get_matrix(i,j))
				throw int(2);

		s.Rotate();
		if (s.get_dir()!=1)
			throw int(2);

	}
	catch(...)
	{
		printf("shape exception!");
	}

	try
	{
		Map m1;
		for(i=0 ;i<4 ;i++)
		for(j=0 ;j<4 ;j++)
			if(m1.get_exist(i,j)||m1.get_color(i,j))
				throw int(3);
		Map m2(m1);
		for(i=0 ;i<4 ;i++)
		for(j=0 ;j<4 ;j++)
			if(m2.get_exist(i,j)||m2.get_color(i,j))
				throw int(3);

		if(Map(m1).get_exist(0,0))
				throw int(3);

		Map m3=m1;
		for(i=0 ;i<4 ;i++)
		for(j=0 ;j<4 ;j++)
			if(m3.get_exist(i,j)||m3.get_color(i,j))
				throw int(3);
		Map m4=Map(m1);
		for(i=0 ;i<4 ;i++)
		for(j=0 ;j<4 ;j++)
			if(m4.get_exist(i,j)||m4.get_color(i,j))
				throw int(3);


	}
	catch(...)
	{
		printf("map exception!");
	}

	try
	{
		Board b1;
		if (b1.get_points()!=0)
			throw int(4);
		Board b2(b1);
		if (b2.get_points()!=0)
			throw int(4);
		if (b1.add_points(10) != 10)
			throw int(4);

		if (Board(b2).get_points()!=0)
			throw int(4);	
		Board b4=b2;
		if (b4.get_points()!=0)
			throw int(4);
		Board b5=Board(b2);
		if (b5.get_points()!=0)
			throw int(4);
	}
	catch(...)
	{
		printf("board exception!");
	}
}
constexpr Board buildBoard(int N) {
  return buildBoardRecurse(N, 0, Board());
}
void GoSafetySolver::Test2Vital(GoRegion* r, SgBWSet* safe)
{
    if (r->ComputeAndGetFlag(GO_REGION_STATIC_2V))
        GoSafetyUtil::AddToSafe(Board(), r->Points(), r->Color(),
                  safe, "2-vital:", 0, true);
}
Beispiel #24
0
 TEST(BoardTest, equality_comparison_should_compare_sizes)
 {
     EXPECT_TRUE(Board(2, 3) == Board(2, 3));
     EXPECT_FALSE(Board(2, 7) == Board(2, 3));
     EXPECT_FALSE(Board(7, 3) == Board(2, 3));
 }
void GoRegionBoard::GenBlocks()
{
    for (GoBlockIterator it(Board()); it; ++it)
        GenBlock(*it, Board().GetStone(*it));
}
Beispiel #26
0
int main(int argc, char** argv)
{
    osg::ArgumentParser arguments( &argc, argv );

    std::string dbPath;
    arguments.read("--db_path", dbPath);

    std::srand ( unsigned ( std::time(0) ) );

    auto board = Board(boardDefinition, boardSizeX, boardSizeY, dbPath);
    auto ghostFactory = GhostFactory();

    auto main_obj = make_ref<osg::Group>();
    main_obj->addChild(board.draw().get());

    auto ghostModel = osgDB::readNodeFile(dbPath + "/cow.osg");
    auto ghostCount = 16;
    while(ghostCount--)
    {
        main_obj->addChild(ghostFactory.drawGhost(board, ghostModel).get());
    }

    // init rotate
    auto init_rotate = make_ref<osg::MatrixTransform>();
    init_rotate->setMatrix( osg::Matrix::rotate(osg::PI * 2, osg::Vec3(1.0f, 0.0f, 0.0f)) );

    // chain rotates
    init_rotate->addChild(main_obj);

    // Root group
    auto root = make_ref<osg::Group>();
    root->addChild(init_rotate);

    // Setup fog
    if(FogEnabled) {
        osg::ref_ptr<osg::Fog> fog = new osg::Fog;
        fog->setMode( osg::Fog::EXP2 );
        fog->setStart( 0.0f );
        fog->setEnd(board.getFieldSizeX() * 20);
        fog->setDensity(0.0135);
        fog->setColor( osg::Vec4(0., 0., 0., 1.0) );

        root->getOrCreateStateSet()->setAttributeAndModes(fog.get());
    }

    // Start viewer
    osgViewer::Viewer viewer;

    // Set up flashlight
    auto lightSource = make_ref<osg::LightSource>();
    lightSource->setReferenceFrame(osg::LightSource::ABSOLUTE_RF);
    auto light = lightSource->getLight();
    const osg::Vec3 lightPosition{1.5, -1, -1}; // right, down, front
    light->setPosition(osg::Vec4{lightPosition, 1});
    light->setDirection(osg::Vec3{0, 0, -1} * 30 - lightPosition);
    light->setSpotExponent(60);
    light->setSpotCutoff(90);
    light->setDiffuse(osg::Vec4(1, 1, 1, 1));
    light->setAmbient(osg::Vec4(0.6, 0.6, 0.6, 1));
    light->setSpecular(osg::Vec4(1, 1, 1, 1));
    light->setLinearAttenuation(0.001);
    light->setConstantAttenuation(0.5);
    root->addChild(lightSource);

    double height = std::min(board.getFieldSizeX(), board.getFieldSizeY()) / 1.5;

    auto fpsManipulator = make_ref<FPSManipulator>(board, viewer, *light);
    fpsManipulator->setHomePosition(
        osg::Vec3d(board.getFieldCenterX(1), board.getFieldCenterY(10), height),
        osg::Vec3d(0.0f, 0.0f, height),
        osg::Vec3d(0.0f, 0.0f, 1.0f)
    );


    auto keySwitch = make_ref<osgGA::KeySwitchMatrixManipulator>();
    keySwitch->addNumberedMatrixManipulator(make_ref<osgGA::OrbitManipulator>());
    keySwitch->addNumberedMatrixManipulator(fpsManipulator);
    viewer.setCameraManipulator(keySwitch);

    viewer.home();
    viewer.setSceneData( root );

    osgViewer::Viewer::Windows windows;
    viewer.getWindows(windows);
    viewer.getCamera()->setClearColor(osg::Vec4{0, 0, 0, 0});

    viewer.getCamera()->getView()->setLightingMode(osg::View::HEADLIGHT);
    auto defaultLight = viewer.getCamera()->getView()->getLight();
    defaultLight->setDiffuse(osg::Vec4(0, 0, 0, 1));
    defaultLight->setAmbient(osg::Vec4(0, 0, 0, 1));
    defaultLight->setSpecular(osg::Vec4(0, 0, 0, 1));

    // Shaders
    auto program = make_ref<osg::Program>();
    auto fragmentObject = make_ref<osg::Shader>(osg::Shader::FRAGMENT);
    loadShaderSource(fragmentObject, dbPath + "/shader.frag");
    auto vertexObject = make_ref<osg::Shader>(osg::Shader::VERTEX);
    loadShaderSource(vertexObject, dbPath + "/shader.vert");
    program->addShader(vertexObject);
    program->addShader(fragmentObject);
    root->getOrCreateStateSet()->setAttributeAndModes(program, osg::StateAttribute::ON);

    root->getOrCreateStateSet()->addUniform(new osg::Uniform("samplerName", TEXTURE_UNIT));
    root->getOrCreateStateSet()->addUniform(new osg::Uniform("Shininess", BoardObjectsShininess));
    root->getOrCreateStateSet()->addUniform(new osg::Uniform("FogEnabled", FogEnabled));

    // Optimize
    osgUtil::Optimizer optimzer;
    optimzer.optimize(root);

    viewer.setUpViewOnSingleScreen(0);

    return viewer.run();
}
Beispiel #27
0
void solve(std::string infile)
{
	Board board = Board(infile);
	Sudoku_solver solver;
	solver.execute(board);
}
Beispiel #28
0
int main(void)
{
  Board tmp;
  for(uint8_t i = 0; i < 3; ++i)
  {
    tmp = Board(T1[i]);
    tmp.print();
  }
  return 0;
	SudokuBoard::Difficulty difficulty = SudokuBoard::INTERMEDIATE;

  // Initialize the random number generator
  int timeSeed = 0;
  srand(timeSeed);

  // Create a new puzzle board
  // and set the options
  SudokuBoard* ss = new SudokuBoard();
	/*SudokuBoard sss;
	SudokuBoard* ss = &sss;*/
  // Solve puzzle or generate puzzles
  // until end of input for solving, or
  // until we have generated the specified number.
	int number_to_benchmark=1000;
  bool done = false;
  while (!done){

      // Record whether the puzzle was possible or not,
      // so that we don't try to solve impossible givens.
      bool havePuzzle = false;
      // Generate a puzzle
      havePuzzle = ss->generatePuzzle();
      if (!havePuzzle){
          //cout << "Could not generate puzzle.";
          //cout << endl;
				usart_str("Could not generate puzzle.");
				usart_str("\r\n");
      }

      if (havePuzzle){

          // Count the solutions if requested.
          // (Must be done before solving, as it would
          // mess up the stats.)

          // Solve the puzzle
          ss->solve();

          // Bail out if it didn't meet the difficulty standards for generation
          if (difficulty!=SudokuBoard::UNKNOWN && difficulty!=ss->getDifficulty()){
              havePuzzle = false;
          } else {
              // Set loop to terminate if enough have been generated.
							if(!(--number_to_benchmark)) done = true;
							srand(number_to_benchmark);
							//char bufor[5];
							//sprintf(bufor,"%d",1000-number_to_benchmark);
							//usart_str(bufor);
						  //usart_str("\r\n");
          }
      }

      if (havePuzzle){
          //table
          // Print the puzzle itself.
          //ss->printPuzzle();

          //ss->printSolution();
          Board tmp(ss->puzzle,ss->solution);
          tmp.print();
          printf(",\n");
      }
  }
	
}
Beispiel #29
0
/*
 * Testsuite "Win at Chess"
 *
 * 300 Board positions which should be found a path to checkmate.
 *
 */
void CLI::run_wac_test() {
    ifstream file;
    file.open(WAC_FILE);
    if (!file) {
        cerr << "Can not run Win At Chess test: Test file '" << WAC_FILE;
        cerr << "' is missing.\n";
        return;
    }

    vector<string> found;
    vector<string> should;
    vector<bool> results;
    vector<string> fens;
    string algebraic = "";

    int total_tested = 0;
    int total_solved = 0;

    string line = "";
    while (!file.eof()) {
        getline(file, line);
        if (line.size() < 4) {
            continue;
        }

        string cmd = "";
        cmd = line.substr(0, 4);

        if (cmd.compare("noop") == 0) {
            continue;
        } else if (cmd.compare("echo") == 0) {
            printf("%s\n", line.substr(5, line.length() - 5).c_str());
        } else if (cmd.compare("svfe") == 0) {
            string fen = "";
            fen = line.substr(5, line.length() - 5);
            fens.push_back(fen);
            Board board = Board(fen);
            Player* player = new ComputerPlayer(false);
            player->set_board(&board);
            player->set_max_thinking_time(max_thinking_time);
            player->set_show_best_score(show_best_score);
            player->set_show_thinking(show_thinking);
            move m = player->get_move();
            algebraic = move_to_algebraic(m, board);
            found.push_back(algebraic);
            delete player;
        } else if (cmd.compare("srch") == 0) {
            string answer = line.substr(5, line.length() - 5);
            should.push_back(answer);
            bool success = compare_found_move(algebraic, answer);
            results.push_back(success);
            total_tested++;

            if (success) {
                total_solved++;
                cout << "Test " << total_tested << " successful. ";
                cout << "Found: " << algebraic << endl;
            } else {
                cout << "Test " << total_tested << " failed. ";
                cout << "Found: " << algebraic;
                cout << ", should be: " << answer << endl;
            }
            printf("Solved %d/%d tests (%.1f%%)\n\n",
                    total_solved, total_tested,
                    (float) (total_solved) / total_tested * 100);
        }
    }

    file.close();

    cout << "---- Test Results ----\n";
    printf("Solved %d/%d tests (%.1f%%)\n\n",
            total_solved,
            total_tested,
            (float) (total_solved) / total_tested * 100);

    cout << "---- Failed results ----\n";

    if (found.size() == should.size() && fens.size() == results.size()
            && fens.size() == found.size()) {
        for (unsigned i = 0; i < results.size(); i++) {
            if (!results[i]) {
                cout << setw(3) << i + 1 << ". " << fens[i] << endl;
                cout << "     Found: " << found[i] << ", should be: " << should[i] << endl;
                cout << endl;
            }
        }
    } else {
        cerr << "Something went wrong with the results. Check the test file.\n";
    }
}
void GoRegionBoard::OnUndoneMove()
// Called after a move has been undone. The board is guaranteed to be in
// a legal state.
{
    //SG_ASSERT(false); // incremental code is incomplete, do not call
    if (DEBUG_REGION_BOARD)
        SgDebug() << "OnUndoneMove " << '\n';

    const bool IS_UNDO = false;
    SgVectorOf<GoRegion> changed;

    for (int val = m_stack.PopEvent(); val != SG_NEXTMOVE;
         val = m_stack.PopEvent())
    {

        switch (val)
        {
            case REGION_REMOVE:
            {   GoRegion* r = static_cast<GoRegion*>(m_stack.PopPtr());
                AddRegion(r, IS_UNDO);
                changed.Insert(r);
            }
            break;
            case REGION_ADD:
            {   GoRegion* r = static_cast<GoRegion*>(m_stack.PopPtr());
                RemoveRegion(r, IS_UNDO);
            }
            break;
            case REGION_REMOVE_BLOCK:
            {   GoBlock* b = static_cast<GoBlock*>(m_stack.PopPtr());
                AddBlock(b, IS_UNDO);
                for (int nu = m_stack.PopInt(); nu > 0; --nu)
                {
                    GoRegion* r = static_cast<GoRegion*>(m_stack.PopPtr());
                    if (CHECK)
                        SG_ASSERT(! r->Blocks().Contains(b));
                    r->BlocksNonConst().PushBack(b);
                    changed.Insert(r);
                }
            }
            break;
            case REGION_ADD_BLOCK:
            {   GoBlock* b = static_cast<GoBlock*>(m_stack.PopPtr());
                RemoveBlock(b, IS_UNDO, true);
            }
            break;
            case REGION_ADD_STONE:
            {   GoRegion* r = static_cast<GoRegion*>(m_stack.PopPtr());
                SgPoint p = m_stack.PopInt();
                r->OnRemoveStone(p);
                m_region[r->Color()][p] = r;
                changed.Insert(r);
            }
            break;
            case REGION_ADD_STONE_TO_BLOCK:
            {   GoBlock* b = static_cast<GoBlock*>(m_stack.PopPtr());
                SgPoint p = m_stack.PopInt();
                b->RemoveStone(p);
                m_block[p] = 0;
            }
            break;
            default:
                SG_ASSERT(false);
        }
    }

    for (SgVectorIteratorOf<GoRegion> it(changed); it; ++it)
    {
        (*it)->ResetNonBlockFlags();
        (*it)->ComputeBasicFlags();
    }

    if (HEAVYCHECK)
    {
        for (SgBWIterator it; it; ++it)
        {
            SgBlackWhite color(*it);
            for (SgVectorIteratorOf<GoRegion> it(AllRegions(color)); it; ++it)
            {
                const GoRegion* r = *it;
                SG_UNUSED(r);
                SG_ASSERT(r->IsValid());
            }
        }
    }

    m_code = Board().GetHashCode();
    if (HEAVYCHECK)
        CheckConsistency();
}