本文整理匯總了C#中Board.Copy方法的典型用法代碼示例。如果您正苦於以下問題:C# Board.Copy方法的具體用法?C# Board.Copy怎麽用?C# Board.Copy使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Board
的用法示例。
在下文中一共展示了Board.Copy方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: PerftCount
private long PerftCount(Board boardBase, int depth)
{
long total = 0;
// find all the moves
var moves = Moves.GetMoves(boardBase);
for (int i = 0; i < moves.Length; i++)
{
Move move = moves[i];
var board = boardBase.Copy();
bool valid = board.Move(move.From, move.To, true);
if(!valid)
continue;
if(move.Promotion > 0)
board.Promote(move.To, move.Promotion);
long cnt = (depth == 1) ? 1 : PerftCount(board, depth - 1);
total += cnt;
// log data in the top node
if (Results.StartDepth == depth)
Results.Entries.Add(new PerftEntry() { Count = cnt, From = move.From, To = move.To });
}
if (Results.StartDepth == depth)
Results.Total = total;
return total;
}
示例2: PlaceMarkAndCheckWinner
public bool PlaceMarkAndCheckWinner(Board board, int[] tempPos, bool tempFirst)
{
int DIM = board.GetDIM();
tempBoard = new Board(DIM);
tempBoard.SetBoard(board.Copy());
tempBoard.SetCell(tempPos, tempFirst);
GameStats gameStats = new GameStats();
return gameStats.IsWinner(tempBoard, tempFirst);
}
示例3: LongestPathLengthInternal
private static int LongestPathLengthInternal(Board board, Func<Board, IEnumerable<BoardSpace>> moveGetter, Action<Board, BoardSpace> makeMove)
{
var longest = 0;
foreach (var move in moveGetter(board))
{
var newBoard = board.Copy();
makeMove(newBoard, move);
var pathLength = LongestPathLengthInternal(newBoard, moveGetter, makeMove) + 1;
if (pathLength > longest)
{
longest = pathLength;
}
// fail safe in case this heuristic is used too early
// going more than 20 moves deep causes everything to die
if (longest > 20)
{
break;
}
}
return longest;
}
示例4: NeuralEngine_Test
static void NeuralEngine_Test(string boardText, int bestMove)
{
IEngine engine = new EndGameEngine();
var board = new Board(boardText);
var color = board.EmptyCount % 2 == 1 ? StoneType.White : StoneType.Black;
var searchResult = engine.Search(board.Copy(), color, 16);
Console.WriteLine("EndGameEngine Best Move Act:{0},Exp:{1} | Score Act:{2}, {3}, Nodes:{4}, Times:{5}",
searchResult.Move, bestMove, searchResult.Score / Constants.HighestScore, searchResult.Message,
searchResult.Nodes, searchResult.TimeSpan);
engine = new NeuralEngine();//"4-6-2012-04-24.net"
searchResult = engine.Search(board.Copy(), color, 4);// (Constants.StoneCount - 4) / 2
Console.WriteLine("NeuralEngine Best Move Act:{0},Exp:{1} | Score Act:{2}, {3}, Nodes:{4}, Times:{5}",
searchResult.Move, bestMove, searchResult.Score, searchResult.Message,
searchResult.Nodes, searchResult.TimeSpan);
}
示例5: BestMoveInternal
// recursive alpha beta
private BestMoveResultWithStats BestMoveInternal(Board board, int depth, int alpha, int beta, CancellationToken cancelToken)
{
// if we reached the bottom, return
if (depth == 0)
{
_numNodesAtDepthLimit++;
return new BestMoveResultWithStats(_config.Heuristic.Evaluate(board), null);
}
var isMaxTurn = board.MyPlayer == board.PlayerToMove;
var validMoves = board.GetValidMoves();
// if we hit game over before the depth limit, return infinity/-infinity if it's our/their turn
if (!validMoves.Any())
{
return new BestMoveResultWithStats(isMaxTurn ? int.MinValue : int.MaxValue, null);
}
BoardSpace bestMove = null;
// generate new boards for each move and evaluate them so we can sort
var validMovesWithBoard = validMoves.Select(x =>
{
var newBoard = board.Copy().Move(x);
_nodesGeneratedByDepth[depth]++;
var score = _config.Heuristic.Evaluate(newBoard);
return new {move = x, newBoard, score};
});
// if we're maxing, sort with largest first, otherwise sort with smallest first
if (isMaxTurn)
{
validMovesWithBoard = validMovesWithBoard.OrderByDescending(x => x.score);
}
else
{
validMovesWithBoard = validMovesWithBoard.OrderBy(x => x.score);
}
// evaluate this board because we'll need to for quiessence search
var boardScore = _config.Heuristic.Evaluate(board);
foreach (var move in validMovesWithBoard)
{
BestMoveResultWithStats childResult;
// if we're doing a quiessence search, check to see if heuristic score change is interesting
if (IsInterestingMove(boardScore, move.score))
{
// extend search depth because this move looks interesting
_numNodesQuiessenceSearched++;
childResult = BestMoveInternal(move.newBoard, depth, alpha, beta, cancelToken);
}
else
{
// normal evaluation
childResult = BestMoveInternal(move.newBoard, depth - 1, alpha, beta, cancelToken);
}
// if we're near timeout or asked to cancel, just bail :(
if (_timer.Timeout() || cancelToken.IsCancellationRequested)
{
_timedOut = true;
break;
}
if (isMaxTurn) // if it's a max turn, we want to check alpha
{
if (childResult.Score > alpha)
{
alpha = childResult.Score;
bestMove = move.move;
}
}
else // else it's a min turn, so we want to check beta
{
if (childResult.Score < beta)
{
beta = childResult.Score;
bestMove = move.move;
}
}
// alpha-beta trim
if (alpha >= beta)
{
break;
}
}
// if we didn't find anything good, just return the first one
if (bestMove == null)
{
bestMove = validMoves.First();
}
return new BestMoveResultWithStats(isMaxTurn ? alpha : beta, bestMove);
}
示例6: ParseToken
private Board ParseToken(
GameVariation variation,
List<PGNToken> tokens,
ref int i,
List<Board> positions,
Board position)
{
var token = tokens[i];
switch (token.TokenType)
{
case (PGNTokenType.Annotation):
variation.Elements.Add(new GameAnnotation(token.Value));
break;
case (PGNTokenType.Comment):
variation.Elements.Add(new GameComment(token.Value));
break;
case (PGNTokenType.Ellipsis):
// Assert its blacks turn
if (position.PlayerTurn != Color.Black)
throw new PGNException("Encountered unexpected token. It should be blacks turn to play", token);
break;
case (PGNTokenType.Move):
position = position.Copy();
var move = MakeMove(token, position);
variation.Elements.Add(move);
break;
case (PGNTokenType.MoveNumber):
if (position.MoveCount > token.GetMoveNumber())
throw new PGNException("Unexpected move number", token);
break;
case (PGNTokenType.Results):
variation.Elements.Add(new GameResults(token.Value));
break;
case (PGNTokenType.VariationStart):
var startpos = GetStartPosition(tokens, ref i, positions);
var newVariation = GetVariation(tokens, ref i, startpos);
variation.Elements.Add(newVariation);
break;
}
return position;
}
示例7: LongestPathInReverseOrder
// depth first search of longest walkable path, returns path length and the sequence of moves and boards in reverse order
private Tuple<int, List<Tuple<Board, BoardSpace>>> LongestPathInReverseOrder(Board board, Func<Board, IEnumerable<BoardSpace>> moveGetter, Action<Board, BoardSpace> makeMove)
{
var longestPathLength = 0;
var path = new List<Tuple<Board, BoardSpace>>();
foreach (var move in moveGetter(board))
{
// bail if we're timing out
if (_timer.Timeout() || _cancelToken.IsCancellationRequested)
{
break;
}
var newBoard = board.Copy();
makeMove(newBoard, move);
var child = LongestPathInReverseOrder(newBoard, moveGetter, makeMove);
var pathLength = child.Item1 + 1;
if (pathLength > longestPathLength)
{
longestPathLength = pathLength;
path = new List<Tuple<Board, BoardSpace>>(child.Item2) { Tuple.Create(newBoard, move) };
}
}
return Tuple.Create(longestPathLength, path);
}
示例8: GetMyNextMove
public BoardSpace GetMyNextMove(Board board)
{
// start the timer
MoveTimer.I.StartTimer();
// cancel all tasks that are now irrelevant
foreach (var task in _tasksByOpponentMove.Where(x => !x.Key.Equals(board.LastMove)))
{
task.Value.CancelSource.Cancel();
}
TimeSpan? asyncTimeElapsed = null;
IBestMoveResult bestMoveResult;
if (board.LastMove == null || !_tasksByOpponentMove.ContainsKey(board.LastMove))
{
// we were not precomputing this path, so we need to start fresh
bestMoveResult = MoveGetter().BestMove(board, _config, MoveTimer.I, new CancellationToken());
}
else
{
// we already started down this branch, so use the result from the task
bestMoveResult = _tasksByOpponentMove[board.LastMove].BestMoveTask.Result;
// check how long that took us
asyncTimeElapsed = _tasksByOpponentMove[board.LastMove].Timer.GetTimeElapsed();
}
// stop timer and grab timer stats
var percentRemaining = MoveTimer.I.GetPercentOfTimeRemaining();
var elapsed = MoveTimer.I.GetTimeElapsed();
var timedOut = MoveTimer.I.Timeout();
MoveTimer.I.ResetTimer();
// report stats, for debugging only, will be off in production
if (_config.ReportStatistics)
{
Console.WriteLine("Time Taken (s): " + elapsed.TotalSeconds);
Console.WriteLine("Time Left (%): " + percentRemaining * 100);
if (asyncTimeElapsed != null)
{
Console.WriteLine("Async Time Taken (s): " + asyncTimeElapsed.Value.TotalSeconds);
}
Console.WriteLine(bestMoveResult.ToString());
}
// if we have enough time remaining, increase the depth limit
if (percentRemaining > _config.PercentTimeLeftToIncrementDepthLimit)
{
// if we didn't do the search async, just increase depth
if (asyncTimeElapsed == null)
{
_config.DepthLimit++;
}
else
{
// only increase depth if async time was decent
var asyncPercentTimeLeft = (_config.MoveTimeout.TotalMilliseconds - asyncTimeElapsed.Value.TotalMilliseconds) / _config.MoveTimeout.TotalMilliseconds;
if (asyncPercentTimeLeft > _config.PercentTimeLeftToIncrementDepthLimit/2)
{
_config.DepthLimit++;
}
}
}
// if we timed out, decrease depth limit so we stop shooting ourself in the foot
if (timedOut)
{
_config.DepthLimit--;
}
var emptySpaces = board.GetEmptySpacesRemaining();
// figure out where we are in the game
if (_config.GameMode == GameMode.Beginning)
{
if (emptySpaces <= 40)
{
_config.DepthLimit--;
_config.GameMode = GameMode.Middle;
}
}
else if (_config.GameMode == GameMode.Middle && !timedOut)
{
// find out what our areas look like
var boardPostMove = board.Copy().Move(bestMoveResult.Move);
var myArea = OpenAreaHeuristic.GetOpenArea(boardPostMove, boardPostMove.MyPlayer);
var oppArea = OpenAreaHeuristic.GetOpenArea(boardPostMove, boardPostMove.OpponentPlayer);
// if we are walled off, switch to end game
if (myArea.All(x => !oppArea.Contains(x)))
{
_isWalledOff = true;
_config.GameMode = GameMode.End;
}
else // we aren't walled off
{
// if it's time for end game, switch and max out depth
if (emptySpaces <= 28)
//.........這裏部分代碼省略.........
示例9: PreComputeNextMove
public void PreComputeNextMove(Board board)
{
// cancel any tasks that are running from last round
foreach (var task in _tasksByOpponentMove.Select(x => x.Value).Where(x => !x.BestMoveTask.IsCompleted))
{
task.CancelSource.Cancel();
}
// remove all saved tasks
_tasksByOpponentMove.Clear();
// for every possible opponent move, pretend like the opponent picks it and start computing my response
foreach (var move in board.GetValidMoves())
{
var newBoard = board.Copy().Move(move);
var task = new AsyncSearchTask(TimeSpan.MaxValue);
task.BestMoveTask = Task.Factory.StartNew(() =>
{
task.Timer.StartTimer();
var result = MoveGetter().BestMove(newBoard, _config, MoveTimer.I, task.CancelSource.Token);
task.Timer.StopTimer();
return result;
}, task.CancelSource.Token);
_tasksByOpponentMove[move] = task;
}
}
示例10: Gen
private void Gen(TextWriter writer, Board board, int color, bool prevmove = true)
{
if (Records >= Limit) {
return;
}
if (board.EmptyCount == EndGameDepth) {
var searchResult = Engine.Search(board.Copy(), color, this.SearchDepth);
WriteRecord(writer, board, searchResult.Score, searchResult.Move, color);
Records++;
//每1000條記錄就Flush一次
if (Records % 1000 == 0) {
Console.WriteLine("Write Records: {0}", Records);
writer.Flush();
}
return;
}
int opp = color.Opp();
var moves = rule.FindFlips(board, color).ToList();
if (moves.Count == 0) {
if (prevmove) {
Gen(writer, board, opp, false);
}
return;
}
foreach (var move in moves) {
int flipCount = board.MakeMove(move.Pos, color);
Gen(writer, board, opp);
board.Reback(move.Pos, flipCount, opp);
}
}
示例11: Fight
private FightResult Fight(IEngine engineA, IEngine engineB, Board board, int color = StoneType.Black)
{
Clock clock = new Clock();
clock.Start();
IEngine[] engines = new[] { engineA, engineB };
int[] stoneTypes = new[] { StoneType.Black, StoneType.White };
int turn = color - 1; //0;
Console.WriteLine(board);
while (true) {
//board.CurrentColor = stoneTypes[turn];
var searchResult = engines[turn].Search(board.Copy(), stoneTypes[turn], (Constants.StoneCount - 4) / 2);
Console.WriteLine("[{0}] {1}", engines[turn].Name, searchResult);
Console.Out.Flush();
if (searchResult.Move < 0 ||
searchResult.Move >= Constants.StoneCount ||
!rule.CanFlip(board[searchResult.Move], stoneTypes[turn])) {
clock.Stop();
//下棋異常
Console.WriteLine(board);
return new FightResult() {
WinnerName = engines[1 - turn].Name,
LoserName = engines[turn].Name,
WinnerStoneType = (turn == 0 ? StoneType.Black : StoneType.White),
Score = 1,
TimeSpan = clock.TotalMilliseconds
};
}
else {
board.MakeMove(searchResult.Move, stoneTypes[turn]);
Console.WriteLine(board);
}
turn = 1 ^ turn;
var canFlip = rule.CanFlip(board, stoneTypes[turn]);
if (!canFlip) {
//對方無棋可下,輪換
turn = 1 ^ turn;
canFlip = rule.CanFlip(board, stoneTypes[turn]);
if (!canFlip) {
//雙方都無棋可下,結束
break;
}
}
}
clock.Stop();
//Console.WriteLine(board);
return new FightResult(board, engines) {
TimeSpan = clock.TotalMilliseconds
};
}
示例12: CopyEmptyBoard
public void CopyEmptyBoard()
{
var repository = new TestRepository();
// create a board without any associated data
var board = new Board();
board.Name = "test1";
repository.Add(board);
// clone the board
var copiedBoard = board.Copy();
// verify that the board is copied
Assert.AreNotEqual(board.Id, copiedBoard.Id);
Assert.AreEqual(board.Name, copiedBoard.Name);
}