我基本上有一个游戏板,玩家不能多次移动到同一个地方,否则你就输了。玩家只能移动 -1、+1、-16 或 +16。我想使用 minimax 来解决这个问题,并接收 minimax 使用的输入,这样我就可以看到它是如何完成的。
这是我目前的做法
#pragma optimize("", off)
#include <stdio.h>
#include <Windows.h>
#define hitcount 4
#define POINT 1
#define MINE 2
#define END 3
//4 targets: hit all 1's
//player/mine is 2
//game ender is 3
int Board[] = {
0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 1, 0,
2, 0, 0, 1, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0
};
static const int choices[] = {
-1, 1, -16, 16
};
struct mb {
int end;
int score;
int* moveset;
};
mb solve(int Position, int *Board, int BoardSize, int *MoveSet = NULL, int Offset = 0, int Choice = 0, int Score = 0, bool tree = true) {
if( tree ) { //tree
int *BoardCopy = new int[BoardSize];
for( int i = 0; i < sizeof(choices); i++ ) {
MoveSet = new int[256];
for( int i = 0; i < 256; i++ )
MoveSet[i] = 0xFF;
memcpy(BoardCopy, Board, BoardSize);
mb m = solve(Position, BoardCopy, BoardSize, MoveSet, Offset, i, Score, false);
if( m.moveset != NULL ) {
if( m.end == 1 && m.score == hitcount ) {
delete[] BoardCopy;
return m;
}
}
delete[] MoveSet; //this is apparently causing problems??
}
delete[] BoardCopy;
}
else { //branch
mb m = {0, 0, MoveSet};
Position += choices[Choice];
m.moveset[Offset] = choices[Choice];
if( Position < 0 || Position >= BoardSize || Board[Position] == MINE || (Board[Position] == END && Score != hitcount) ) {
m.moveset = NULL;
return m;
}
else if( Board[Position] == POINT ) {
m.score++;
}
else if( Board[Position] == END ) {
m.end = 1;
return m;
}
Board[Position] = MINE;
return solve(Position, Board, BoardSize, m.moveset, Offset + 1, Choice + 1, m.score);
}
mb m = {0, 0, NULL};
return m;
}
int main() {
int Position = 0;
for( int i = 0; i < sizeof(Board); i++ ) {
if( Board[i] == MINE ) Position = i;
}
mb m = solve(Position, Board, sizeof(Board));
if( m.end == 1 && m.moveset != NULL && m.score == hitcount ) {
printf("SUCCESS!\n");
}
getchar();
return 0;
}
但是,它不起作用。我不知道为什么。该算法看起来应该可以工作,而我的问题看起来与内存清理有关。多次调用解决后,我的 VC++ 工作室在 _CrtIsValidHeapPtr 处断点