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 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); }
public ReversiWindow() { InitializeComponent(); winnerLabel.Visibility = Visibility.Hidden; gameHistory = new List<ReversiBoard>(); myRepaint = new Repaint(this.repaint); board = new ReversiBoard(0); ReversiPlayer player = new ReversiPlayer(ComputerPlayer); alg = new Algorithms(player); intializeVisualBoard(); this.UpdateLabel += new ReversiWindow.GameOver(updateWinnerLabel); upDateGameStatus(-1, -1, 0); board.NoLegalMoveAvailable += new ReversiBoard.HasMoves(board_NoLegalMoveAvailable); board.GameOver += new ReversiBoard.EndGame(board_GameOver); board.MoveComplete += new ReversiBoard.BoardMove(board_MoveComplete); if (board.GetCurrentPlayer().GetPlayerID() == alg.ComputerPlayerID) { computerThread = new Thread(this.computerMove); computerThread.Start(); } }
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; } }
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 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 void Main(string[] args) { double[] naive = new double[11]; Individual Naive = new Individual(naive, "Naive"); Naive.SearchDepth = 2; double[] optimal = { 1, 1.5, 0.304941560283742, 0.398957574925831, 0.808534060050051, 0.0123464008850727, 0.947831550123092, 0.983976080074895, 0.157787902819825, 0.999516903422548, 0.164692896960626 }; double[] simple = new double[11]; simple[0] = 1; simple[1] = 1.5; Individual Simple = new Individual(simple, "Simple"); Simple.SearchDepth = 2; Individual MiniMax = new Individual(simple, "MiniMax"); MiniMax.SearchDepth = 8; Individual Optimal = new Individual(optimal, "Optimal"); Optimal.SearchDepth = 7; Individual Adaptive = new Individual(optimal, "Adaptive"); Adaptive.SearchDepth = 8; int minimaxBaseSearchDepth = 8; int[] generatedDepths = new int[100]; //for (int index = 0; index < 100; index++) //{ // if (rand.NextDouble() < 0.075) // { // if (MiniMax.SearchDepth < 8) // MiniMax.SearchDepth++; // } // FileStream fileSearchDepth = new FileStream("E:\\Scoala\\Minimax" + minimaxBaseSearchDepth.ToString() + "\\SearchDepths.txt", // FileMode.Append, FileAccess.Write); // StreamWriter wr = new StreamWriter(fileSearchDepth); // int trueDepth = MiniMax.SearchDepth; // if (rand.NextDouble() < 0.1) // { // double random = rand.NextDouble(); // if (random < 0.5 && MiniMax.SearchDepth < 8) // MiniMax.SearchDepth++; // else if (random > 0.5 && MiniMax.SearchDepth > 2) // MiniMax.SearchDepth--; // } // wr.Write(" " + MiniMax.SearchDepth.ToString()); // wr.Close(); // fileSearchDepth.Close(); // generatedDepths[index] = MiniMax.SearchDepth; // MiniMax.SearchDepth = trueDepth; //} while (minimaxBaseSearchDepth >= 2) { GameAI.Algorithms alg = new Algorithms(new CheckersPlayer(1)); DateTime time = DateTime.Now; for (int i = 0; i < 100; i++) { MiniMax.SearchDepth = minimaxBaseSearchDepth; Individual[] weights = { Adaptive, MiniMax }; ThreadProc(weights, "E:\\Scoala\\Minimax" + minimaxBaseSearchDepth.ToString() + "\\Game" + i.ToString() + ".txt");//, alg); } TimeSpan span = new TimeSpan(); span = DateTime.Now - time; FileStream file = new FileStream(@"E:\Minimax" + minimaxBaseSearchDepth.ToString() + "vsAdaptive.txt", FileMode.Create, FileAccess.Write); StreamWriter writer = new StreamWriter(file); writer.WriteLine(MiniMax.ToString()); writer.WriteLine(Adaptive.ToString()); writer.WriteLine("Time for simulation " + span.ToString()); writer.Flush(); writer.Close(); file.Close(); minimaxBaseSearchDepth--; MiniMax.SearchDepth = minimaxBaseSearchDepth; MiniMax.TotalBlackWins = 0; MiniMax.TotalWhiteWins = 0; MiniMax.Draws = 0; MiniMax.Loses = 0; Adaptive.TotalWhiteWins = 0; Adaptive.TotalBlackWins = 0; Adaptive.Draws = 0; Adaptive.Loses = 0; } }
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; }