Dejwi
Dejwi

Reputation: 4487

C++ implementation of game tree

I'm going to represent a chess game as C++ structure. I think, that the best option will be a tree structure(cause at each deep we have several possible moves).

Is it a good approach?

struct TreeElement{
  SomeMoveType move;
  TreeElement *parent;
  std::vector<TreeElement*> children;
};

How to efficiency store this kind of data in a file? Is there a way to make sure, that the whole tree structure will be stored in the same part of memory, which will allow to use mmap function?

Upvotes: 1

Views: 2352

Answers (2)

david nash
david nash

Reputation: 11

I think using a std::vector is not the best way to create the tree, singly linked lists style tree construction is probably simpler and best.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490028

To store the data in the same section of memory, you probably want to supply an Allocator object for the std::vector<TreeElement *> you use, and have that allocate from your block.

To be able to serialize it, instead of storing actual pointers, you might consider storing offsets in the block. Then when you read the data back in, you can add the address of the start of the block to each offset to turn it back into an address.

Depending on the OS/compiler you're using, there may be some support for this already. For example, Microsoft's compiler supports __based pointers, that are pretty much what I've described: a base address, and each pointer based off that address is really just an offset, not a full pointer. The mention of mmap indicates that's probably not available to you directly, but it's possible that the compiler/OS you're using has something similar. Otherwise, you'll probably have to do the job on your own (e.g., with a based_pointer class).

The real question is why you're trying to serialize a move-tree at all. In a typical case, you're better off just saving the current board position (or, about equivalently, the move history) and re-generating the move tree from that when/if needed. That's enough smaller that it's really easy to store.

Upvotes: 3

Related Questions