我最近一直在写一个下棋的人工智能。 AI旨在运行两个单独的实例,每个实例都连接到客户端服务器。服务器依次为每个AI调用一个run函数。我正在尝试做的是编写代码,在另一个AI正在移动时进行思考。但是,我遇到过一个问题。我将展示代码,以便更轻松地解释所述问题:
public override bool run()
{
PonderSearch ponderSearch = new PonderSearch();
Thread ponderThread;
AIMove bestMove = null;
int Depth = 0;
// Print the board
if (moves.Length < 2)
{
theBoard.Print();
}
if (!FirstTurn)
{
AIMove lastMove = new AIMove(AI.moves[0]);
Depth = ponderSearch.Depth;
foreach (MoveTable result in ponderSearch.TheTable)
{
if (result.TheMove == lastMove)
{
bestMove = result.TheResult.Move;
}
}
// End thread
ponderThread.Abort();
ponderThread.Join();
}
// Looks through information about the players
for (int p = 0; p < players.Length; p++)
{
Console.Write(players[p].getPlayerName());
// if playerID is 0, you're white, if its 1, you're black
if (players[p].getId() == playerID())
{
Console.Write(" (ME)");
}
Console.WriteLine(" time remaining: " + players[p].getTime());
}
AIMove otherPMove = new AIMove();
AIPiece pieceMoved = new AIPiece();
// if there has been a move, print the most recent move
if (moves.Length > 0)
{
// Update the board state with previous move
theBoard = theBoard.Update();
pieceMoved = theBoard.GetPiece((short)moves[0].getToRank(),
(short)moves[0].getToFile());
otherPMove = new AIMove(moves[0], pieceMoved);
if (lastMoves.Count >= 8)
{
lastMoves.RemoveAt(7);
}
lastMoves.Insert(0, otherPMove);
}
// Generate move
Search theSearch = new Search(lastMoves);
if (!FirstTurn)
{
theSearch.Update(Depth, bestMove);
}
AIMove theMove = theSearch.Minimax(theBoard, (short)playerID());
// Update last 8 moves
if (lastMoves.Count >= 8)
{
lastMoves.RemoveAt(7);
}
lastMoves.Insert(0, theMove);
if (theMove != null)
{
Console.WriteLine("Move Chosen:");
theMove.Print();
theBoard = theBoard.Move(theMove, (short)playerID());
}
else
{
Console.WriteLine("No move available");
}
theBoard.Print();
// Begin pondering
ponderSearch = new PonderSearch(lastMoves, (short)playerID(), theBoard, theMove);
ponderThread = new Thread(new ThreadStart(ponderSearch.Ponder));
ponderThread.Start();
FirstTurn = false;
return true;
}
无论如何,编写时,编译器会抛出多个错误,说我的线程尚未初始化,但重点是该函数多次运行,结束在最近一次调用中启动的线程。现在的。
我有什么方法可以做到这一点吗?
谢谢,
编辑:我得到的错误是:
Error 4 Use of unassigned local variable 'ponderThread' C:\Users\...\AI.CS 52 13 csclient
答案 0 :(得分:0)
这与线程无关。这是一个简单的范围界定问题。所有局部变量(在方法内声明)通常放在堆栈上,并在方法存在时进行清理。
因此,在ponderThread
方法退出后,run()
将被垃圾收集。因此,下次您的方法输入时,会将成员变量FirstTurn
设置为true,而ponderThread
未初始化,因为它是一个局部变量。
快速解决方法是将ponderThread
变量更改为类变量(在C#中称为成员变量)。
然而,当你要在两个线程之间共享状态时,这会给你线程同步问题。
我建议你在进一步阅读之前先阅读一些关于线程的内容。