pgnlib: a c++ library for PGN chess games

Tutorial - 5


5. Give me the moves

This is a very basic example on how to deal with single moves: we simply read each move, one by one, and print them on stdout.

#include <PGNGameCollection.h> 
#include <fstream>

int main(int argc, char *argv[])
{
    try
    {
	// ok, getting the games, iterate, the same stuff we already know.
        ifstream pgnfile("./sample.pgn");
        pgn::GameCollection games;
        pgnfile >> games;

        for (pgn::GameCollection::iterator itr = games.begin(); itr != games.end(); itr++)
        {
             pgn::Game game = *itr;

             // from the game object we now get the list of the moves
             pgn::MoveList movelist = game.moves();

             std::cout << "---- new game ----" << endl;

             // MoveList class defines his own iterator 
             for (pgn::MoveList::iterator itr2 = movelist.begin(); itr2 != movelist.end(); itr2++)
	     {
		  // itr2 points to a single move, let's print it out.
                  std::cout << "move: ."  << *itr2  << "."  << std::endl;
             }
        }
    }
    catch (pgn::Exception &e)
    {
        cerr << "exception: " << e.what() << endl;
        return -1;
    }

    return 0;
}

We can run it and get this rather pointless (to be honest) output stream


	---- new game ----

	move: .1. e4 e5.
	move: .2. Nf3 Nc6.
	move: .3. Nc3 Nf6.
	move: .4. d4 exd4.
	...

and move on to the next example, when we'll try to get something out of the moves.

[4. Processing games] [home page] [6. Moves and Pieces]

SourceForge.net Logo Valid HTML 4.01!