protected void Page_Load(object sender, EventArgs e) { Session.Timeout = 5; this.board = this.Session["board"] as CheckersBoard; this.alg = this.Session["alg"] as Algorithms; this.gameHistory = this.Session["gameHistory"] as List<CheckersMove>; if (this.Session["AIID"] != null) this.AIID = this.Session["AIID"].ToString()[0]; if (board != null && alg != null && this.gameHistory != null && !this.board.GameIsOver()) { this.board.MakeMove(parsePlayerMove()); if (!board.GameIsOver()) { this.computerMove(); this.generateBoardElements(); } if (this.board.GameIsOver()) { this.winner.Text = this.board.Winner == 1 ? "The player RED is the winner." : "The player BLACK is the winner."; Response.Redirect("~/Results.aspx"); } } }
public CheckersBoard(CheckersBoard board, bool isVisualBoard) { this.gameBoard = new int[8, 8]; this.players = new CheckersPlayer[2]; for (int row = 0; row < 8; ++row) for (int col = 0; col < 8; ++col) { this.gameBoard[row, col] = board.gameBoard[row, col]; } this.weights = new double[board.weights.Length]; for (int index = 0; index < this.weights.Length; ++index) this.weights[index] = board.weights[index]; this.players[1] = new CheckersPlayer(1); this.players[0] = new CheckersPlayer(-1); if (board.currentPlayer.GetPlayerID() == 1) this.currentPlayer = players[1]; else this.currentPlayer = players[0]; this.GameOver += new EndGame(calculateWinner); this.GameMaxLength = board.GameMaxLength; if (isVisualBoard) GameOver = board.GameOver; this.updateLegalMoves(); if (legalMoves.Count > 0) this.updateCounters(); }
public CheckersWindow() { this.InitializeComponent(); board = new CheckersBoard(0, x); board.GameMaxLength = 150; lastMove = new CheckersMove(null, false, 1); moveList.Tag = new List<CheckersMove>(); myRepaint = new Repaint(this.repaint); CheckersPlayer player = new CheckersPlayer(ComputerPlayer); alg = new Algorithms(player); int blackWhite = 1; for (int row = 0; row < 8; ++row) { for (int col = 0; col < 8; ++col) { if (blackWhite % 2 == 0) { BlackSquare square = new BlackSquare(); square.SetValue(Grid.ColumnProperty, col); square.SetValue(Grid.RowProperty, row); square.Tag = new System.Windows.Point(row, col); square.DragEnter += new DragEventHandler(square_DragEnter); square.Drop += new DragEventHandler(square_Drop); square.MouseLeftButtonDown += new MouseButtonEventHandler(square_MouseLeftButtonDown); UIBoard.Children.Add(square); blackSquares.Add(square); } else { WhiteSquare square = new WhiteSquare(); square.SetValue(Grid.ColumnProperty, col); square.SetValue(Grid.RowProperty, row); UIBoard.Children.Add(square); } blackWhite++; } blackWhite++; } StringBuilder stringBuilder = new StringBuilder("Current Player is:\n"); stringBuilder.Append(board.GetCurrentPlayer().GetPlayerID().ToString() == "-1" ? "Black" : "White"); currentPlayerLabel.Content = stringBuilder.ToString(); repaint(null); board.GameOver += new CheckersBoard.EndGame(board_GameOver); if (board.GetCurrentPlayer().GetPlayerID() == alg.ComputerPlayerID) { computerThread = new Thread(this.computerMove); computerThread.Start(); } this.visualGameOver = new EndGame(this.theGameIsOver); }
protected void startButton_Click(object sender, EventArgs e) { if (startButton.Enabled == true) { this.startButton.Enabled = false; this.winner.Visible = true; this.winner.Text = "Game in progress!"; this.pickPlayerLabel.Visible = false; this.playBlack.Visible = false; this.playRed.Visible = false; //X is a double[] that contains the weigths for the //evaluation function this.board = new CheckersBoard(0, x); double random = rand.NextDouble(); if (random < 0.33) { this.AIID = 'H'; } else if (random > 0.66) { this.AIID = 'E'; } else { this.AIID = 'P'; } this.gameHistory = new List<CheckersMove>(); if (playBlack.Checked) { this.alg = new Algorithms(board.GetCurrentPlayer(),0.5); this.computerMove(); } else { alg = new Algorithms(new CheckersGame.CheckersPlayer(1)); } board.GameMaxLength = 150; playerMove.Text = "nothing"; generateBoardElements(); Session.Add("board", this.board); Session.Add("alg", this.alg); Session.Add("gameHistory", this.gameHistory); Session.Add("AIID", this.AIID); } }
private int eval(CheckersBoard board) { int colorKing; int colorForce = 0; int enemyForce = 0; int piece; if (color == CheckersBoard.WHITE) { colorKing = CheckersBoard.WHITE_KING; } else { colorKing = CheckersBoard.BLACK_KING; } try { for (int i = 0; i < 32; i++) { piece = board.getCell(i); if (piece != CheckersBoard.EMPTY) { if (piece == color || piece == colorKing) { colorForce += calculateValue(piece, i); } else { enemyForce += calculateValue(piece, i); } } } } catch { } return(colorForce - enemyForce); }
private List minimax(CheckersBoard board) { List sucessors; List move, bestMove = null; CheckersBoard nextBoard; int value, maxValue = Int32.MinValue; sucessors = board.legalMoves(); while (mayPlay(sucessors)) { move = (List)sucessors.pop_front(); nextBoard = (CheckersBoard)board.clone(); nextBoard.move(move); value = minMove(nextBoard, 1, maxValue, Int32.MaxValue); if (value > maxValue) { maxValue = value; bestMove = move; } } return(bestMove); }
public IBoardGame TestMove(IMove move) { CheckersBoard board = new CheckersBoard(this, false); board.MakeMove(move); return board; }
public void setBoard(CheckersBoard board) { this.board = board; }
private bool cutOffTest(CheckersBoard board, int depth) { return(depth > maxDepth || board.whiteCell == 0 || board.blackCell == 0); }
public Computer(CheckersBoard gameBoard) { board = gameBoard; color = CheckersBoard.BLACK; }
private void moveList_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e) { ListView list = sender as ListView; if (list != null) { if (list.SelectedIndex != -1) { MessageBoxResult result = MessageBox.Show("Do you wish to restore the game from this position? ", "Restore", MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.No); if (result == MessageBoxResult.Yes) { List<CheckersMove> moves = moveList.Tag as List<CheckersMove>; int selectedIndex = list.SelectedIndex; for (int index = list.Items.Count - 1; index > selectedIndex; --index) { list.Items.RemoveAt(index); moves.RemoveAt(index); } board = new CheckersBoard(0, x); board.GameOver += new CheckersBoard.EndGame(board_GameOver); board.GameMaxLength = 200; foreach (var move in moves) { board.MakeMove(move); StringBuilder builder = new StringBuilder(move.PlayerID.ToString() == "1" ? "White: " : "Black: "); foreach (var item in move.GetPath()) { builder.Append(Convert.ToChar(65 + item.Y)); builder.Append((item.X + 1).ToString()); builder.Append('-'); } // builder.Remove(builder.Length - 1, 1); builder.Append(move.Duration.TotalSeconds.ToString()); } moveList.ScrollIntoView(moveList.Items[moveList.Items.Count - 1]); this.repaint(null); if (alg.ComputerPlayerID == board.GetCurrentPlayer().GetPlayerID()) { computerThread = new Thread(this.computerMove); computerThread.Start(); } } } } e.Handled = true; }
protected void submitAnswers_Click(object sender, EventArgs e) { this.board = this.Session["board"] as CheckersBoard; this.alg = this.Session["alg"] as Algorithms; this.gameHistory = this.Session["gameHistory"] as List<CheckersMove>; if (this.Session["AIID"] != null) this.AIID = this.Session["AIID"].ToString()[0]; if (this.board == null || !this.board.GameIsOver()) { this.incorrectAnswers.Visible = true; this.incorrectAnswers.Text = "The game has not ended yet"; return; } if ((this.undecided.Checked || this.smart.Checked || this.stupid.Checked) && (this.fairTrue.Checked || this.fairFalse.Checked) && (this.againFalse.Checked || this.againTrue.Checked)) { this.incorrectAnswers.Visible = true; this.incorrectAnswers.Text = "Thank you for submitting!"; this.submitAnswers.Visible = false; string q1Answer = "debug"; string q2Answer = "debug"; string q3Answer = "debug"; if (this.undecided.Checked) { q3Answer = "undecided"; } else if (this.smart.Checked) { q3Answer = "smart"; } else if (this.stupid.Checked) { q3Answer = "stupid"; } if (this.fairFalse.Checked) { q1Answer = "false"; } else if (this.fairTrue.Checked) { q1Answer = "true"; } if (this.againTrue.Checked) { q2Answer = "true"; } else if (this.againFalse.Checked) { q2Answer = "false"; } DBOperations op = new DBOperations(); op.SaveData(this.AIID.ToString(), this.board, this.gameHistory, this.alg, q1Answer, q2Answer, q3Answer); this.submitAnswers.Enabled = false; } else { this.incorrectAnswers.Text = "Please answer all of the questions before submitting!"; this.incorrectAnswers.Visible = true; } }
private static object threadProc(Object data) { Individual[] weights = data as Individual[]; Algorithms alg = new Algorithms(new CheckersPlayer(1)); CheckersBoard whiteBoard = new CheckersBoard(0, weights[0].Weights); CheckersBoard blackBoard = new CheckersBoard(0, weights[1].Weights); whiteBoard.GameMaxLength = 150; blackBoard.GameMaxLength = 150; while (!blackBoard.GameIsOver()) { CheckersMove move = alg.ABNegamax(blackBoard, weights[1].SearchDepth, 0, double.MinValue, double.MaxValue) as CheckersMove; whiteBoard.MakeMove(move); blackBoard.MakeMove(move); if (blackBoard.GameIsOver()) break; else { move = alg.ABNegamax(whiteBoard, weights[0].SearchDepth, 0, double.MinValue, double.MaxValue) as CheckersMove; whiteBoard.MakeMove(move); blackBoard.MakeMove(move); } } switch (whiteBoard.Winner) { case 0: weights[0].Draws += 1; weights[1].Draws += 1; break; case 1: weights[0].TotalWhiteWins += 1; weights[1].Loses += 1; break; case -1: weights[1].TotalBlackWins += 1; weights[0].Loses += 1; break; } return weights as object; }
/// <summary> /// This procedure takes two individuals and makes them play against each other /// </summary> /// <param name="data">Should be an array of doubles representing two individuals</param> /// <returns>The individuals after playing against each other</returns> static object ThreadProc(Object data) { Individaul[] weights = data as Individaul[]; GameAI.Algorithms alg = new Algorithms(new CheckersPlayer(1)); CheckersBoard whiteBoard = new CheckersBoard(0, weights[0].Weights); CheckersBoard blackBoard = new CheckersBoard(0, weights[1].Weights); whiteBoard.GameMaxLength = 200; blackBoard.GameMaxLength = 200; while (!blackBoard.GameIsOver()) { CheckersMove move = alg.ABNegamax(blackBoard, 4, 0, double.MinValue, double.MaxValue) as CheckersMove; whiteBoard.MakeMove(move); blackBoard.MakeMove(move); if (blackBoard.GameIsOver()) break; else { move = alg.ABNegamax(whiteBoard, 4, 0, double.MinValue, double.MaxValue) as CheckersMove; whiteBoard.MakeMove(move); blackBoard.MakeMove(move); } } switch (whiteBoard.Winner) { case 0: weights[0].AddToFitness(1); weights[1].AddToFitness(1); break; case 1: weights[0].AddToFitness(3); break; case -1: weights[1].AddToFitness(3); break; } return weights as object; }
public void SaveData(string playerType, CheckersBoard board, List<CheckersMove> moveHistory, Algorithms alg, string q1Answer,string q2Answer, string q3Answer,int aIStrength = 0) { MySql.Data.MySqlClient.MySqlConnection con = new MySql.Data.MySqlClient.MySqlConnection(this.connectionString); MySqlTransaction transaction; int computerPlayerIndex = alg.ComputerPlayerID == -1 ? 0 : 1; try { if (con.State != System.Data.ConnectionState.Open) { con.Open(); transaction = con.BeginTransaction(); try { MySqlCommand command = new MySqlCommand("INSERT INTO games (AIID,AIColor,AIStrength,Outcome,Q1,Q2,Q3) VALUES (@AIID,@AIColor,@AIStrength,@Outcome,@Q1,@Q2,@Q3);"); command.Connection = con; command.Transaction = transaction; command.Parameters.Add("@AIID", MySqlDbType.VarChar, 45).Value = playerType; command.Parameters.Add("@AIColor", MySqlDbType.VarChar, 45).Value = alg.ComputerPlayerID; command.Parameters.Add("@AIStrength", MySqlDbType.Int32).Value = aIStrength; command.Parameters.Add("@Outcome", MySqlDbType.Int32).Value = board.Winner; command.Parameters.Add("@Q1", MySqlDbType.String, 45).Value = q1Answer; command.Parameters.Add("@Q2", MySqlDbType.String, 45).Value = q2Answer; command.Parameters.Add("@Q3", MySqlDbType.String, 45).Value = q3Answer; command.ExecuteNonQuery(); command = new MySqlCommand("SELECT LAST_INSERT_ID() as idGames;", con,transaction); int newId = -1; System.Data.IDataReader reader = command.ExecuteReader(); if (reader != null && reader.Read()) { newId = reader.GetInt32(0); Console.WriteLine(newId); } reader.Close(); for (int index = 0; index < moveHistory.Count; index++) { command = new MySqlCommand("INSERT INTO moves (idGames,MoveNumber,Observation,Prediction,MoveString) VALUES (@idGames,@MoveNumber,@Observation,@Prediction,@MoveString);" , con, transaction); command.Parameters.Add("@idGames", MySqlDbType.Int32).Value = newId; command.Parameters.Add("@MoveNumber", MySqlDbType.Int32).Value = index; if (moveHistory[index].PlayerID == alg.ComputerPlayerID) { if (playerType == "P") { if ((index + computerPlayerIndex) % 2 == 0 && (index + computerPlayerIndex) / 2 < alg.Statistics.Count) { command.Parameters.Add("@Observation", MySqlDbType.Double).Value = alg.Statistics[(index + computerPlayerIndex) / 2].Observation; command.Parameters.Add("@Prediction", MySqlDbType.Double).Value = alg.Statistics[(index + computerPlayerIndex) / 2].Prediction; } else { command.Parameters.Add("@Observation", MySqlDbType.Double).Value = 0; //this 100 is impossible. That's why we use it for a "oh shit" marker. command.Parameters.Add("@Prediction", MySqlDbType.Double).Value = 100; } } else { command.Parameters.Add("@Observation", MySqlDbType.Double).Value = 0; command.Parameters.Add("@Prediction", MySqlDbType.Double).Value = 0; } } else { command.Parameters.Add("@Observation", MySqlDbType.Double).Value = 0; command.Parameters.Add("@Prediction", MySqlDbType.Double).Value = 0; } command.Parameters.Add("@MoveString", MySqlDbType.VarChar, 45).Value = moveHistory[index].ToString(); command.ExecuteNonQuery(); } transaction.Commit(); } catch (MySqlException ex) { transaction.Rollback(); Console.WriteLine(ex.Message); } } } catch (Exception ex) { System.Console.WriteLine(ex.Message); } finally { con.Close(); } }
static object ThreadProcAdaptive(Object data) { Individual[] weights = data as Individual[]; GameAI.Algorithms alg = new Algorithms(new CheckersPlayer(1)); CheckersBoard whiteBoard = new CheckersBoard(0, weights[0].Weights); CheckersBoard blackScore = new CheckersBoard(0, weights[0].Weights); CheckersBoard blackBoard = new CheckersBoard(0, weights[1].Weights); whiteBoard.GameMaxLength = 200; blackBoard.GameMaxLength = 200; while (!blackBoard.GameIsOver()) { CheckersMove move = alg.ABNegamax(blackBoard, weights[1].SearchDepth, 0, double.MinValue, double.MaxValue) as CheckersMove; List<IMove> opponentsMoves = alg.EvaluateMoves(blackScore, weights[0].SearchDepth, 0, double.MinValue, double.MaxValue); whiteBoard.MakeMove(move); blackScore.MakeMove(move); blackBoard.MakeMove(move); if (blackBoard.GameIsOver()) break; else { move = alg.AdaptiveABNegamax(whiteBoard, weights[0].SearchDepth, 0, double.MinValue, double.MaxValue, opponentsMoves, move) as CheckersMove; whiteBoard.MakeMove(move); blackScore.MakeMove(move); blackBoard.MakeMove(move); } } switch (whiteBoard.Winner) { case 0: weights[0].Draws += 1; weights[1].Draws += 1; break; case 1: weights[0].TotalWhiteWins += 1; weights[1].Loses += 1; break; case -1: weights[1].TotalBlackWins += 1; weights[0].Loses += 1; break; } return weights as object; }
//, GameAI.Algorithms alg) static object ThreadProc(Object data, string path) { Individual[] weights = data as Individual[]; GameAI.Algorithms alg = new Algorithms(new CheckersPlayer(1)); CheckersBoard whiteBoard = new CheckersBoard(0, weights[0].Weights); CheckersBoard blackBoard = new CheckersBoard(0, weights[1].Weights); whiteBoard.GameMaxLength = 200; blackBoard.GameMaxLength = 200; while (!blackBoard.GameIsOver()) { CheckersMove move = alg.ABNegamax(blackBoard, weights[1].SearchDepth, 0, double.MinValue, double.MaxValue) as CheckersMove; whiteBoard.MakeMove(move); blackBoard.MakeMove(move); if (blackBoard.GameIsOver()) break; else { //move = alg.ABNegamax(whiteBoard, weights[0].SearchDepth, 0, double.MinValue, double.MaxValue) as CheckersMove; move = alg.POSM(whiteBoard, 0.5) as CheckersMove; // writer.WriteLine(move.GetMoveScore().ToString()); whiteBoard.MakeMove(move); blackBoard.MakeMove(move); } } FileStream file = new FileStream(path, FileMode.Append, FileAccess.Write); StreamWriter wr = new StreamWriter(file); switch (whiteBoard.Winner) { case 0: weights[0].Draws += 1; weights[1].Draws += 1; wr.WriteLine("Draw"); wr.WriteLine(alg.ToString()); break; case 1: weights[0].TotalWhiteWins += 1; weights[1].Loses += 1; wr.WriteLine("Win for Adaptive"); alg.GameObervationUpdate(1); wr.WriteLine(alg.ToString()); break; case -1: weights[1].TotalBlackWins += 1; weights[0].Loses += 1; wr.WriteLine("Los for Adaptive"); alg.GameObervationUpdate(-1); wr.WriteLine(alg.ToString()); break; } wr.Close(); file.Close(); return weights as object; }
void square_Drop(object sender, DragEventArgs e) { BlackSquare square = sender as BlackSquare; if (currentItemContainer != null) { if (square.Opacity != 1) { currentItemContainer.Children.Clear(); currentItemContainer = null; square.backGround.Children.Add((Ellipse)e.Data.GetData(typeof(Ellipse))); parentSquare.Opacity = 1; parentSquare = null; System.Windows.Point squareCoords = (System.Windows.Point)square.Tag; if (isInMove == false) { isInMove = true; } List<CheckersMove> newLegalMoves = new List<CheckersMove>(); foreach (var item in movesForCurrentPiece) { CheckersGame.Point moveCoords = item.GetPathAt(moveIndex); if (moveCoords != null && moveCoords.IsEqual((int)squareCoords.X, (int)squareCoords.Y)) { newLegalMoves.Add(item); } } movesForCurrentPiece = newLegalMoves; ++moveIndex; if (movesForCurrentPiece.Count == 1)// && moveIndex == movesForCurrentPiece[0].GetPath().Count) { if (SearchDepth == 8) { lastPlayerMove = movesForCurrentPiece[0]; evaluator = new CheckersBoard(board, false); } board.MakeMove(movesForCurrentPiece[0]); repaint(movesForCurrentPiece[0]); if (!board.GameIsOver()) { computerThread = new Thread(this.computerMove); computerThread.Start(); } isInMove = false; } } //else // MessageBox.Show("Illegal move!", "Illegal", MessageBoxButton.OK, MessageBoxImage.Exclamation); } foreach (var elem in blackSquares) { elem.Opacity = 1.0; foreach (var item in elem.backGround.Children) if (item is Ellipse) { Ellipse elli = item as Ellipse; int row = (int)elem.GetValue(Grid.RowProperty); int col = (int)elem.GetValue(Grid.ColumnProperty); elli.Tag = new System.Windows.Point(row, col); } } }
public Checkers() { InitializeComponent(); board = new CheckersBoard(panel1); game = new Game(panel1, board); }
private void load_Click(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog fileDiag = new System.Windows.Forms.OpenFileDialog(); System.Windows.Forms.DialogResult result = fileDiag.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { FileStream file = new FileStream(fileDiag.FileName, FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(file); string currentString = reader.ReadLine(); List<CheckersMove> list = new List<CheckersMove>(); try { while (currentString != null) { string[] parseData = currentString.Split(' '); int pathLength = int.Parse(parseData[0]); List<CheckersGame.Point> pathPoints = new List<CheckersGame.Point>(); for (int index = 0; index < pathLength; ++index) { pathPoints.Add(new CheckersGame.Point(int.Parse(parseData[index * 2 + 1]), int.Parse(parseData[(index + 1) * 2]))); } bool isJump = false; if (parseData[pathLength * 2 + 1] == "True") isJump = true; int playerID = int.Parse(parseData[parseData.Length - 1]); list.Add(new CheckersMove(pathPoints, isJump, playerID)); currentString = reader.ReadLine(); } } catch { MessageBox.Show("This is not a valid document"); return; } moveList.Tag = list; moveList.Items.Clear(); board = new CheckersBoard(0, x); board.GameOver += new CheckersBoard.EndGame(board_GameOver); board.GameMaxLength = 200; foreach (var move in list) { board.MakeMove(move); StringBuilder builder = new StringBuilder(move.PlayerID.ToString() == "1" ? "White: " : "Black: "); foreach (var item in move.GetPath()) { builder.Append(Convert.ToChar(65 + item.Y)); builder.Append((item.X + 1).ToString()); builder.Append('-'); } builder.Remove(builder.Length - 1, 1); moveList.Items.Add(builder.ToString()); } moveList.ScrollIntoView(moveList.Items[moveList.Items.Count - 1]); this.repaint(null); if (board.GetCurrentPlayer().GetPlayerID() == alg.ComputerPlayerID) { computerThread = new Thread(computerMove); computerThread.Start(); } reader.Close(); file.Close(); } }