基本上我遇到的问题是我的MinMax
算法并没有按预期工作。
我需要将我的数组片段复制到newPieces
,以便在pieces
时newPieces
不会更改。{/ p>
以下是MinMax
算法的摘录:
private int MinMax(
int depth, Piece[] pieces, bool blacksTurn,
List<Move> Moves, Game game, int alpha, Move nextMove) {
Piece[] newPieces=new Piece[24];
Moves=Game.possibleMoves(pieces, blacksTurn, false);
if(depth==0||Moves.Count==0) {
return Evaluation(ref pieces);
}
int value;
if(blacksTurn==true) {
foreach(Move i in Moves) {
newPieces=DeepCopy.ObjectExtensions.Copy(pieces);
game.MovePiece(newPieces, blacksTurn, i.Moving, i.Destination, true);
game.DisplayBoard(pieces);
value=minMax(depth-1, newPieces, !blacksTurn, Moves, game, alpha, nextMove);
if(alpha>value) {
alpha=value;
nextMove=i;
}
// ...
这是Piece类。
[StructLayout(LayoutKind.Sequential)]
public class Piece
{
public CellReference Location;
public bool isBlack { get; set; }
public bool isKing { get; set; }
private int Value { get; set; }
public bool taken { get; set; }
public Piece()
{
}
public Piece(int i, bool isBlack, bool isKing, int CellsEast, int CellsNorth, bool taken)
{
this.Value = i;
Location.CellsEast = CellsEast;
Location.CellsNorth = CellsNorth;
this.isBlack = isBlack;
this.isKing = isKing;
this.taken = taken;
}
}
答案 0 :(得分:2)
我会在ICloneable<T>
课程上实施 ICloneable
Piece
。
public interface ICloneable<T>
{
T Clone();
}
pieces.Select(p => p.Clone()).ToArray();
或只使用foreach
循环。
答案 1 :(得分:1)
将属性添加到类/结构Piece
:
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public class Piece {
代码正在关注
namespace DeepCopy {
public static class ObjectExtensions {
public static T[] Copy<T>(this T[] pieces) {
return pieces.Select(x => {
var handle=Marshal.AllocHGlobal(Marshal.SizeOf(typeof(T)));
try {
Marshal.StructureToPtr(x, handle, false);
return (T)Marshal.PtrToStructure(handle, typeof(T));
}
finally {
Marshal.FreeHGlobal(handle);
}
}).ToArray();
}
}
}
我暂时将Piece.Value
修改为公开测试,并使用测试类进行测试
public static partial class TestClass {
public static void TestDeepCopy(Piece[] pieces) {
Piece[] newPieces=new Piece[24];
newPieces=DeepCopy.ObjectExtensions.Copy(pieces);
newPieces[0].isKing=true;
newPieces[0].Value=3;
newPieces[1].isKing=true;
newPieces[1].taken=true;
newPieces[1].Value=4;
Console.WriteLine("=== newPieces ===");
foreach(var x in newPieces)
Console.WriteLine(
"x.isKing={0}; x.isBlack={1}; x.Value={2}",
x.isKing, x.isBlack, x.Value
);
Console.WriteLine();
Console.WriteLine("=== pieces ===");
foreach(var x in pieces)
Console.WriteLine(
"x.isKing={0}; x.isBlack={1}; x.Value={2}",
x.isKing, x.isBlack, x.Value
);
}
public static void StartTest() {
var pieceA=new Piece(1, false, false, 1, 1, false);
var pieceB=new Piece(2, true, false, 1, 1, false);
var pieces=new[] { pieceA, pieceB };
TestDeepCopy(pieces);
}
}
它有效。要执行测试,请致电
TestClass.StartTest();
答案 2 :(得分:0)
我认为this可能有助于解决您的问题。它使用ICloneable接口使对象知道如何克隆自己。