public virtual int AlphaBeta(Position p, int depth, int alpha, int beta, double extension, MoveList pv, long Zkey, int move) { if (nodecount[1] + nodecount[0] > NODELIMIT) //wenn Knotenlimit überschritten, gehe zu Exception { throw new TooManyNodesException(); } if (depth < maxDepth) { maxDepth = depth; } p.makeMove(move); nodecount[0] += 1; int hashflag = HASHALPHA; //letzte Bits des Keys in Index umwandeln int index = (int)Zkey & (HASHSIZE - 1); //Hash Tables hvalue = -1; bestMove = -1; newbeta = beta; newalpha = alpha; if (HashTable2[index].key == Zkey) { if (HashTable2[index].depth >= (depth + extension)) { if (HashTable2[index].flag == HASHEXACT) { hvalue = HashTable2[index].value_Renamed; } if (HashTable2[index].flag == HASHALPHA && HashTable2[index].value_Renamed <= alpha) { hvalue = alpha; } if (HashTable2[index].flag == HASHALPHA && HashTable2[index].value_Renamed < beta) { newbeta = HashTable2[index].value_Renamed; } if (HashTable2[index].flag == HASHBETA && HashTable2[index].value_Renamed >= beta) { hvalue = beta; } if (HashTable2[index].flag == HASHBETA && HashTable2[index].value_Renamed > alpha) { newalpha = HashTable2[index].value_Renamed; } } bestMove = HashTable2[index].move; } if (HashTable1[index].key == Zkey) { if (HashTable1[index].depth >= (depth + extension)) { if (HashTable1[index].flag == HASHEXACT) { hvalue = HashTable1[index].value_Renamed; } if (HashTable1[index].flag == HASHALPHA && HashTable1[index].value_Renamed <= alpha) { hvalue = alpha; } if (HashTable1[index].flag == HASHALPHA && HashTable1[index].value_Renamed < beta) { newbeta = HashTable1[index].value_Renamed; } if (HashTable1[index].flag == HASHBETA && HashTable1[index].value_Renamed >= beta) { hvalue = beta; } if (HashTable1[index].flag == HASHBETA && HashTable1[index].value_Renamed > alpha) { newalpha = HashTable1[index].value_Renamed; } } bestMove = HashTable1[index].move; } if (HashTable3[index].key == Zkey) { hvalue = HashTable3[index].value_Renamed; } beta = newbeta; alpha = newalpha; if (hvalue != -1) { pv.length = 0; return hvalue; } MoveList mypv = new MoveList(); //entschiedene Positionen if (p.isWon(!p.toMove, move)) { pv.length = 0; addHashEntries(Zkey, index, depth + extension, -1000 + p.numberOfDiscs(), HASHEXACT, -1); return -1000 + p.numberOfDiscs(); } if (p.Draw) { pv.length = 0; addHashEntries(Zkey, index, depth + extension, 0, HASHEXACT, -1); return 0; } //Eröffnungsbuchzugriff if (opening) { if (p.numberOfDiscs() <= 8) { value_Renamed = searchBook(p); if (value_Renamed != -1) { pv.length = 0; addHashEntries(Zkey, index, depth + extension, value_Renamed, HASHEXACT, -1); return value_Renamed; } } } //Interior Node Recognition firstFreeColumn = -1; secondFreeColumn = -1; freeColumns = 0; for (int i = 0; i < 7; i++) { if (p.height[i] != 6) { freeColumns += 1; if (freeColumns == 3) break; if (freeColumns == 1) firstFreeColumn = i; if (freeColumns == 2) secondFreeColumn = i; } } //Wenn nur mehr wenige Spalten frei sind (Ende des Spieles) if (freeColumns == 1 || (freeColumns == 2 && (secondFreeColumn - firstFreeColumn >= 4))) { if (acuteThreat(p, p.toMove) == -1 && acuteThreat(p, !p.toMove) == -1) { value_Renamed = evaluate(p, true); pv.length = 0; addHashEntries(Zkey, index, depth + extension, value_Renamed, HASHEXACT, -1); return value_Renamed; } } if (depth <= (0 - extension)) { int akut2 = acuteThreat(p, p.toMove); if (akut2 != -1) { pv.length = 0; addHashEntries(Zkey, index, depth + extension, 1000 - p.numberOfDiscs() - 1, HASHEXACT, -1); return 1000 - p.numberOfDiscs() - 1; } int akut = acuteThreat(p, !p.toMove); if (akut == -1) { pv.length = 0; int val = evaluate(p, false); addHashEntries(Zkey, index, depth + extension, val, HASHEXACT, -1); return val; } extension += 2; Zkey = Zkey ^ (p.toMove ? zobristKeys[akut][0] : zobristKeys[akut][1]); int value_Renamed = -AlphaBeta(p, depth - 1, -beta, -alpha, extension, mypv, Zkey, akut); p.undoMove(akut); Zkey = Zkey ^ (p.toMove ? zobristKeys[akut][0] : zobristKeys[akut][1]); if (value_Renamed >= beta) { addHashEntries(Zkey, index, depth + extension - 2, beta, HASHBETA, -1); return beta; } if (value_Renamed > alpha) { hashflag = HASHEXACT; alpha = value_Renamed; pv.First = new MoveListElement(akut); if (mypv.length != 0) { pv.Rest = mypv; } pv.length = mypv.length + 1; } addHashEntries(Zkey, index, depth + extension - 2, alpha, hashflag, -1); return alpha; } int[] moves = generateMoves(p, searchDepth - depth); sort(moves, p); //Sortiert Züge nach Feldgewichten und nach dem besten Zug aus den Hash Tables //Suchvertiefung for (int i = 0; i < moves[7]; i++) { Zkey = Zkey ^ (p.toMove ? zobristKeys[moves[i]][0] : zobristKeys[moves[i]][1]); value_Renamed = -AlphaBeta(p, depth - 1, -beta, -alpha, extension, mypv, Zkey, moves[i]); p.undoMove(moves[i]); Zkey = Zkey ^ (p.toMove ? zobristKeys[moves[i]][0] : zobristKeys[moves[i]][1]); if (value_Renamed >= beta) { addHashEntries(Zkey, index, depth + extension, value_Renamed, HASHBETA, moves[i]); return beta; } if (value_Renamed > alpha) { hashflag = HASHEXACT; alpha = value_Renamed; pv.First = new MoveListElement(moves[i]); if (mypv.length != 0) { pv.Rest = mypv; } pv.length = mypv.length + 1; } } addHashEntries(Zkey, index, depth + extension, alpha, hashflag, (hashflag == HASHEXACT ? pv.pop() : -1)); return alpha; }
/* * Für den initialen Aufruf von AlphaBeta gibt es eine spezielle Funktion. * a) Hier wird kein Wert aus den Hash Tables, aus dem Eröffnungsbuch oder aus einer Form von Evaluation übernommen, * da man sonst 0 Level im Suchbaum und demzufolge keine PV, also auch keinen besten Zug erhält. * b) Hier muß nicht auf gewonnene oder unentschiedene Positionen getestet werden, da playGame() solche Stellungen abfängt. * c) Hier wird kein Zug-Argument übergeben. Diese Methode stellt stets den Wurzelknoten dar. */ public virtual int StartAlphaBeta(Position p, int depth, int alpha, int beta, double extension, MoveList pv, long Zkey) { nodecount[0] += 1; int hashflag = HASHALPHA; //letzte Bits des Keys in Index umwandeln int index = (int)Zkey & (HASHSIZE - 1); //Hashtables zugriff bestMove = -1; if (HashTable1[index].key == Zkey) //HashTable 1 suchen { bestMove = HashTable1[index].move; } if (HashTable2[index].key == Zkey) //in HashTable 2 suchen { bestMove = HashTable2[index].move; } MoveList mypv = new MoveList(); int[] moves = generateMoves(p, searchDepth - depth); //mögliche Züge generieren sort(moves, p); //Sortiert Züge nach Feldgewichten und nach dem besten Zug aus den Hash Tables for (int i = 0; i < moves[7]; i++) //moves[7] = Anzahl der möglichen Züge { Zkey = Zkey ^ (p.toMove == Position.WHITE ? zobristKeys[moves[i]][0] : zobristKeys[moves[i]][1]); value_Renamed = -AlphaBeta(p, depth - 1, -beta, -alpha, extension, mypv, Zkey, moves[i]); p.undoMove(moves[i]); Zkey = Zkey ^ (p.toMove == Position.WHITE ? zobristKeys[moves[i]][0] : zobristKeys[moves[i]][1]); if (value_Renamed >= beta) { addHashEntries(Zkey, index, depth + extension, value_Renamed, HASHBETA, moves[i]); return beta; } if (value_Renamed > alpha) { hashflag = HASHEXACT; alpha = value_Renamed; pv.First = new MoveListElement(moves[i]); if (mypv.length != 0) { pv.Rest = mypv; } pv.length = mypv.length + 1; } } addHashEntries(Zkey, index, depth + extension, alpha, hashflag, (hashflag == HASHEXACT ? pv.pop() : -1)); return alpha; }
/* * * Hauptmethode des Computerspielers, die eine Position annimmt und einen Zug zurückgibt. * Sie kapselt den Alpha-Beta-Algorithmus. */ public override int returnMove(Position arg) { //Spielfeld übernehmen Position p = new Position(arg); //Startwerte für das Iterative Deepening nodecount[1] = savedSum; int lastRoundMove = -1; int lastRoundValue = -1000; int bestFoundValue = 0; // Bewertung des besten Zuges searchDepth = 1; //aktuelle Suchtiefe int alpha = -10000; int beta = 10000; MoveList pv = new MoveList(); bool repeated = false; //Zobrist-Key erstellen long Zkey = 0; for (int i = 0; i < 42; i++) { if ((p.whiteDiscs & (0x0000000000400000L << i)) == (0x0000000000400000L << i)) { Zkey = Zkey ^ zobristKeys[i][0]; //^ = XOR } else if ((p.blackDiscs & (0x0000000000400000L << i)) == (0x0000000000400000L << i)) { Zkey = Zkey ^ zobristKeys[i][1]; } } //Löschen der HashTables 1 und 2. for (int i = 0; i < HASHSIZE; i++) { HashTable1[i].clear(); HashTable2[i].clear(); } //feststellen, ob man sich noch in der Eröffnung befindet if (bookEnabled && p.numberOfDiscs() < 8) { opening = true; } else { opening = false; } //Iterative-Deepening-Schleife while (!(searchDepth > (42 - p.numberOfDiscs()))) { repeated = false; nodecount[0] = 0; maxDepth = 100; counterrecognized = 0; counterevaluated = 0; counterhash1 = 0; counterhash2 = 0; counterhash3 = 0; pv = new MoveList(); //Zugliste long startTime = 0; long duration = 0; try { //Aspiration Search verlangt ggf. mehrere Anläufe while (true) { startTime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; bestFoundValue = StartAlphaBeta(p, searchDepth, alpha, beta, 0, pv, Zkey); //Aufruf des eigentlichen Algorithmusses duration = repeated ? duration + (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - startTime : (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - startTime; //Start Aspiration Windows if (bestFoundValue <= alpha && !repeated) //erweitern des Suchfenster nach unten { repeated = true; alpha = -10000; beta = bestFoundValue + 2; continue; } if (bestFoundValue >= beta && !repeated) //erweitern des Suchfensters nach oben { repeated = true; beta = 10000; alpha = bestFoundValue - 2; continue; } if (repeated && (bestFoundValue <= alpha || bestFoundValue >= beta)) //setzen des Suchfensters auf Startwerte { alpha = -10000; beta = 10000; continue; } if (bestFoundValue == 0) //Unentschieden oder Ungeklärte Situation { alpha = bestFoundValue - 2; beta = bestFoundValue + 2; } if (bestFoundValue > 0 && bestFoundValue < 600) //alles offen { alpha = bestFoundValue; beta = bestFoundValue + 2; } if (bestFoundValue < 0 && bestFoundValue > -600) //alles offen für anderen Spieler { alpha = bestFoundValue - 2; beta = bestFoundValue; } if (bestFoundValue > 600) //sicher gewonnen { alpha = bestFoundValue - 1; beta = bestFoundValue + 1; } if (bestFoundValue < -600) //sicher gewonnen für anderen Spieler { alpha = bestFoundValue - 1; beta = bestFoundValue + 1; } //Ende Aspiration Windows break; } } catch (TooManyNodesException) //max. Anzahl von Knoten überschritten { duration = repeated ? duration + (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - startTime : (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - startTime; totalDuration = totalDuration + duration; nodecount[2] = nodecount[2] + nodecount[0]; nodecount[1] = nodecount[1] + nodecount[0]; return lastRoundMove; } lastRoundMove = pv.pop(); lastRoundValue = bestFoundValue; totalDuration = totalDuration + duration; nodecount[2] = nodecount[2] + nodecount[0]; nodecount[1] = nodecount[1] + nodecount[0]; int overwritten1 = 0; int overwritten2 = 0; int overwritten3 = 0; for (int i = 0; i < HASHSIZE; i++) { if (HashTable1[i].depth != -1) { counterhash1 += 1; overwritten1 += HashTable1[i].overwritten; } if (HashTable2[i].depth != -1) { counterhash2 += 1; overwritten2 += HashTable2[i].overwritten; } if (HashTable3[i].depth != -1) { counterhash3 += 1; overwritten3 += HashTable3[i].overwritten; } } if (bestFoundValue > 900 || bestFoundValue < -900) { break; } searchDepth += 1; } if (bestFoundValue < -900) { if (!opening) { return lastRoundMove; } else { //Wenn man in der Eröffnung in einer verlorenen Position ist, löscht man die Hash Tables und sucht ohne Eröffnungsbuch von vorne. bookEnabled = false; savedSum = nodecount[1]; for (int i = 0; i < HASHSIZE; i++) { HashTable3[i].clear(); } int result = returnMove(p); for (int i = 0; i < HASHSIZE; i++) { HashTable3[i].clear(); } savedSum = 0; bookEnabled = true; return result; } } else { return lastRoundMove; } }
/// <summary> /// Start a new game /// </summary> /// <param name="mode"></param> public Connect4Game(GameSettings.GAMEMODE mode, int startingPlayer, GameSettings.DIFFICULTY difficulty, GameSettings settings) { startTime = DateTime.Now; RED_PLAYER = settings.RED_PLAYER; YELLOW_PLAYER = settings.YELLOW_PLAYER; COLUMNS = settings.COLUMNS; ROWS = settings.ROWS; this.aiStrength = difficulty; this.GameMode = mode; this.STARTING_PLAYER = startingPlayer; this.activePlayer = startingPlayer; map = new int[settings.COLUMNS, settings.ROWS]; switch (GameMode) { case (GameSettings.GAMEMODE.SinglePlayer): { position = new Position(); zuege = new MoveList(); comp = new ComputerPlayer(Position.WHITE, "Machine", true, difficulty); this.GameState = GameSettings.GAMESTATE.S_BeforeGame; break; } case (GameSettings.GAMEMODE.CPUvsCPU): { position = new Position(); zuege = new MoveList(); comp = new ComputerPlayer(Position.WHITE, "Machine1", true, difficulty); if (this.STARTING_PLAYER == RED_PLAYER) { this.GameState = GameSettings.GAMESTATE.S_WaitForCPU; this.HUMAN_PLAYER = RED_PLAYER; } else { this.GameState = GameSettings.GAMESTATE.S_WaitForCPU; this.HUMAN_PLAYER = YELLOW_PLAYER; } break; } case (GameSettings.GAMEMODE.LocalMultiPlayer): { position = new Position(); zuege = new MoveList(); this.GameState = GameSettings.GAMESTATE.S_BeforeGame; break; } case (GameSettings.GAMEMODE.NetworkGame): { position = new Position(); zuege = new MoveList(); /*string line = ""; using (StreamReader sr = new StreamReader("net.txt")) { string tmp; while ((tmp = sr.ReadLine()) != null) { line = tmp; } sr.Close(); } int port = Convert.ToInt32(line.Split(',')[0]); string ip = line.Split(',')[1]; if (Convert.ToInt32(line.Split(',')[2]) == 2) { netStartPlayer = 1; } else { netStartPlayer = 2; } NetGame = new Networking(port, ip);*/ this.GameState = GameSettings.GAMESTATE.S_WaitForConnection; break; } } }
/// <summary> /// Returns an array containing the stone-numbers of the winner /// </summary> /// <param name="value">Return value of position.isWonPos()</param> /// <param name="tempzuege">Movelist</param> /// <returns></returns> public int[] isWonConvert(long value, MoveList tempzuege) { int[] winmoves = new int[4]; int[] winlist = new int[4]; int[] zuegearray = new int[tempzuege.length]; int j = 0; string wonpos = Convert.ToString(value, 2); for (int i = wonpos.Length - 22; i >= 0; i--) { if (String.Compare(wonpos[i].ToString(), "1") == 0) { winmoves[j] = wonpos.Length - 23 - i; j++; } } for (int i = 0; i < tempzuege.length; i++) { zuegearray[i] = tempzuege.first.value_Renamed; if (tempzuege.first.next != null) tempzuege.first = tempzuege.first.next; } j = 0; for (int i = 0; i < zuegearray.Length; i++) { for (int z = 0; z < winmoves.Length; z++) { if (zuegearray[i] == winmoves[z]) { winlist[j] = i; j++; } } } // Divide by two, because only 21 stones exist per color for(int i = 0; i < winlist.Length; i++) { winlist[i] = winlist[i] / 2; } return winlist; }
// Free ressources public void Dispose() { position = null; comp = null; zuege = null; AIStarted = false; ClearGame(); }