void bt_Click(object sender, RoutedEventArgs e) { Button bt = (Button)sender; if (SelectButton.Uid != "") { //棋子移动信息 Str_ChessInfo chessinfo = new Str_ChessInfo(); chessinfo.category = Convert.ToInt32(SelectButton.Uid); if ((chessinfo.category > 0 && IsRed == true) || (chessinfo.category < 0 && IsRed == false)) { Grid origin_grid = (Grid)this.GetType().GetField(SelectButton.Name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).GetValue(this); Grid now_grid = (Grid)this.GetType().GetField(bt.Name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).GetValue(this); int origin_Position = cast_Name(origin_grid.Name); int now_Position = cast_Name(now_grid.Name); chessinfo.origin_position = origin_Position; chessinfo.target = now_Position; if (rule.Rule_Judge(ref ChessLoad.Auxiliary_array, chessinfo)) { ChessLoad.Auxiliary_array[chessinfo.target] = chessinfo.category; ChessLoad.Auxiliary_array[chessinfo.origin_position] = 0; origin_grid.Children.Clear(); now_grid.Children.Clear(); SelectButton.Name = now_grid.Name; SelectButton.Uid = chessinfo.category.ToString(); now_grid.Children.Add(SelectButton); ChessAI ai = new ChessAI(score); ChessTree tree = new ChessTree(); tree.State = new Struct_State(); tree.State.array_chess = ChessLoad.Auxiliary_array; tree.State.isRed = false; tree.State = ai.Ai_Result(ref tree, depth); Button AiButton = new Button(); ChessLoad.Auxiliary_array[tree.State.target_position] = tree.State.category; ChessLoad.Auxiliary_array[tree.State.origin_position] = 0; origin_grid = (Grid)this.GetType().GetField("po_" + tree.State.origin_position, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).GetValue(this); now_grid = (Grid)this.GetType().GetField("po_" + tree.State.target_position, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).GetValue(this); AiButton = (Button)origin_grid.Children[0]; AiButton.Name = "po_" + tree.State.target_position; AiButton.Uid = tree.State.category.ToString(); //避免重复走棋 //if (ChessLoad.same_action_state.Count == 2) // ChessLoad.same_action_state.Dequeue(); //Struct_Simple_State simple_state = new Struct_Simple_State(); //simple_state.category = tree.State.category; //simple_state.origin_position = tree.State.origin_position; //simple_state.target_position = tree.State.target_position; //ChessLoad.same_action_state.Enqueue(simple_state); origin_grid.Children.Clear(); now_grid.Children.Clear(); now_grid.Children.Add(AiButton); } else { SelectButton = bt; } } } SelectButton = bt; }
public void PlayMove(Move move) { GameUi.Instance.OnMovePlayed(move); Board.ExecuteMove(move); move.piece.transform.position = new Vector3( move.targetPosition.x, move.piece.transform.position.y, move.targetPosition.y); if (currentTurn == Color.White) { currentTurn = Color.Black; } else { currentTurn = Color.White; } var winner = Board.GetWinner(); if (winner.HasValue) { GameUi.Instance.OnWon(winner.Value); } else if (currentTurn == Color.Black) { PlayMove(ChessAI.GetNextMove(Board, Color.Black)); } }
IEnumerator RunAI() { ChessAI AI = new ChessAI(board); float coroutineStepStartTime = Time.realtimeSinceStartup; while (!AI.isStepResultReady) { AI.RunAIStep(); if (Time.realtimeSinceStartup - coroutineStepStartTime > Time.fixedDeltaTime) { yield return(new WaitForFixedUpdate()); coroutineStepStartTime = Time.realtimeSinceStartup; } } ChessBoard.Move AIMove = AI.ConsumeAIResult(); board.MovePiece(board.GetMove(AIMove.startPosition, AIMove.endPosition)); attackers.ComputeAttackers(); UpdateTileHighlights(); if (GameIsOver()) { endPopup.Show(GetWinner(), playerColor); } }
/// <summary> /// Defines the decision-making logic of the agent. Given the information /// about the agent, returns a vector of actions. /// </summary> /// <returns>Vector action vector.</returns> /// <param name="vectorObs">The vector observations of the agent.</param> /// <param name="visualObs">The cameras the agent uses for visual observations.</param> /// <param name="reward">The reward the agent received at the previous step.</param> /// <param name="done">Whether or not the agent is done.</param> /// <param name="memory"> /// The memories stored from the previous step with /// <see cref="MakeMemory(List{float}, List{Texture2D}, float, bool, List{float})"/> /// </param> public override float[] Decide(List <float> vectorObs, List <Texture2D> visualObs, float reward, bool done, List <float> memory) { if (chessGame == null) { chessGame = FindObjectOfType <ChessGame> (); } if (academy == null) { academy = FindObjectOfType <ChessAcademy> (); } else { if (academy.resetParameters.ContainsKey("ai-depth")) { depth = Mathf.FloorToInt(academy.resetParameters["ai-depth"]); } } currentTeam = chessGame.GetChess().currentTeam; Move bestmove = ChessAI.GetBestMove(ObservationToChess(vectorObs), depth); float[] act = new float[brainParameters.vectorActionSize.Length]; act[0] = MoveToIndex(bestmove); chessGame.GetChess().currentTeam = currentTeam; return(act); }
private void AIMove(Team team) { if (chessGame.GetChess().currentTeam == team) { Move move = ChessAI.GetBestMove(chessGame.GetChess(), depth); chessGame.GetChess().currentTeam = team; chessGame.MakeMove(move); } }
public void endPlayerTurn() { isPlayerTurn = false; Board pieces = boardManager.pieces; Move bestMoveForAi = ChessAI.getBestMove(pieces); Debug.Log(bestMoveForAi.start.x + "," + bestMoveForAi.start.y); //boardManager.movePiece(bestMoveForAi.start, bestMoveForAi.end); isPlayerTurn = true; }
void Start() { validPos = new Vector2[size, size]; fields = new Field[size, size]; desk = new char[size, size]; FillLocation(); ai = new ChessAI(fields); StartNewGame(); }
public override void OnInspectorGUI() { if (GUILayout.Button("GetNextMove")) { Debug.Log(ChessAI.GetNextMove(GameManager.Instance.Board, Color.Black)); } // Show default inspector property editor DrawDefaultInspector(); }
void Start() { Instance = this; ai = new ChessAI(); ChessFigurePositions = new ChessFigure[8, 8]; SpawnAllChessFigures(); }
private void grid3_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Str_ChessInfo chessinfo = new Str_ChessInfo(); //棋子移动信息 Grid now_grid = (Grid)sender; //当前的Grid值 if (SelectButton.Uid != "") { //通过反射获取选中棋子的信息 Grid origin_grid = (Grid)this.GetType().GetField(SelectButton.Name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).GetValue(this); int origin_Position = cast_Name(origin_grid.Name); int now_Position = cast_Name(now_grid.Name); chessinfo.category = Convert.ToInt32(SelectButton.Uid); if ((chessinfo.category < 0 && IsRed == false) || chessinfo.category > 0 && IsRed == true) { chessinfo.origin_position = origin_Position; chessinfo.target = now_Position; //棋盘模块判断 if (rule.Rule_Judge(ref ChessLoad.Auxiliary_array, chessinfo)) { ChessLoad.Auxiliary_array[chessinfo.target] = chessinfo.category; ChessLoad.Auxiliary_array[chessinfo.origin_position] = 0; origin_grid.Children.Clear(); SelectButton.Name = now_grid.Name; now_grid.Children.Add(SelectButton); ChessAI ai = new ChessAI(score); ChessTree tree = new ChessTree(); tree.State = new Struct_State(); tree.State.array_chess = new int[ChessLoad.Auxiliary_array.Length]; ChessLoad.Auxiliary_array.CopyTo(tree.State.array_chess, 0); tree.State.isRed = false; tree.State = ai.Ai_Result(ref tree, depth); ChessLoad.Auxiliary_array[tree.State.target_position] = tree.State.category; ChessLoad.Auxiliary_array[tree.State.origin_position] = 0; Button AiButton = new Button(); origin_grid = (Grid)this.GetType().GetField("po_" + tree.State.origin_position, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).GetValue(this); now_grid = (Grid)this.GetType().GetField("po_" + tree.State.target_position, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).GetValue(this); AiButton = (Button)origin_grid.Children[0]; AiButton.Name = "po_" + tree.State.target_position; AiButton.Uid = tree.State.category.ToString(); //避免重复走棋 //if(ChessLoad.same_action_state.Count==2) //ChessLoad.same_action_state.Dequeue(); //Struct_Simple_State simple_state = new Struct_Simple_State(); //simple_state.category = tree.State.category; //simple_state.origin_position = tree.State.origin_position; //simple_state.target_position = tree.State.target_position; //ChessLoad.same_action_state.Enqueue(simple_state); origin_grid.Children.Clear(); now_grid.Children.Clear(); now_grid.Children.Add(AiButton); } } } }
void Start() { Instance = this; Winner_Panel.SetActive(false); ai = new ChessAI(); ChessFigurePositions = new ChessFigure[5, 5]; SpawnAllChessFigures(); }
private void Start() { StartCoroutine(FadeIn()); Instance = this; spawnAllChessPieces(); winText = GameObject.Find("WinText"); winText.SetActive(false); gameCamera = Camera.main; if (CPU) { ComputerAI.SetActive(true); AI = ComputerAI.GetComponent <ChessAI> (); } }
public int[] decideAndMoveEnemyPiece() { int[] ai_move = new int[4]; Move bestMoveForAi = ChessAI.getBestMove(pieces); Debug.Log(bestMoveForAi.start.x + "," + bestMoveForAi.start.y + "to" + bestMoveForAi.end.x + "," + bestMoveForAi.end.y); movePiece(bestMoveForAi.start, bestMoveForAi.end, true); ai_move[0] = bestMoveForAi.start.x; ai_move[1] = bestMoveForAi.start.y; ai_move[2] = bestMoveForAi.end.x; ai_move[3] = bestMoveForAi.end.y; return(ai_move); }
public void GetNegaMaxMoveWrapper(Object stateInfo) { WorkerInfo workerInfo = (stateInfo as WorkerInfo); using (var Context = _dbContextFactory.Create()) { WorkerResult workerResult = Context.WorkerResults.Find(workerInfo.WorkerID); Move newMove; ChessAI.NegaMax(3, ChessAI.NegInfinity, ChessAI.Infinity, workerInfo.GamePosition, workerInfo.Color, out newMove); workerResult.Fen = Fen.PositionToFen(PieceData.MakeMove(workerInfo.GamePosition, newMove)); workerResult.Finished = true; Context.Update(workerResult); Context.SaveChanges(); } }
void Start() { //纹理初始化------ WhitePawn = Resources.Load <Texture2D>("Icons/WhitePawn"); WhiteRook = Resources.Load <Texture2D>("Icons/WhiteRook"); WhiteBishop = Resources.Load <Texture2D>("Icons/WhiteBishop"); WhiteKnight = Resources.Load <Texture2D>("Icons/WhiteKnight"); WhiteQueen = Resources.Load <Texture2D>("Icons/WhiteQueen"); WhiteKing = Resources.Load <Texture2D>("Icons/WhiteKing"); BlackKing = Resources.Load <Texture2D>("Icons/BlackKing"); BlackQueen = Resources.Load <Texture2D>("Icons/BlackQueen"); BlackPawn = Resources.Load <Texture2D>("Icons/BlackPawn"); BlackRook = Resources.Load <Texture2D>("Icons/BlackRook"); BlackBishop = Resources.Load <Texture2D>("Icons/BlackBishop"); BlackKnight = Resources.Load <Texture2D>("Icons/BlackKnight"); blackTex = Resources.Load <Texture2D>("BlackSquare"); whiteTex = Resources.Load <Texture2D>("WhiteSquare"); //------ newBoard(); instantiateBoard(); attacksWhite = new AttacksTable(board, true); attacksBlack = new AttacksTable(board, false); leftCastling = false; rightCastling = false; check = false; promotion = false; playing = true; fin = false; checkedCooldown = Time.time - 4f; history = new ArrayList(); enemy = GameObject.FindObjectOfType <ChessAI>(); white = true; enemyPlaying = false; turnCD = Time.time; starting = true; }
// Use this for initialization void Start() { //Return the current Active Scene in order to get the current Scene's name Scene scene = SceneManager.GetActiveScene(); //Check if the current Active Scene's name is your first Scene if (scene.name == "StoneScene") { orientation = Quaternion.Euler(0, 0, 0); } Instance = this; SpawAllPieces(); audioSource = this.GetComponent <AudioSource>(); ia = new ChessAI(); }
void Start() { turnText = GameObject.Find("Turn").GetComponent <Text> (); resultPanel = GameObject.Find("ResultPanel"); resultText = GameObject.Find("ResultText").GetComponent <Text> (); resultPanel.SetActive(false); selectText = GameObject.Find("SelectName").GetComponent <Text>(); turncount = 1; ai = GetComponent <ChessAI> (); isWhiteTurn = true; Instance = this; SpawnAllChessman(); //Debug.Log (EnemyChessmans.Length); }
private List <ChessAI> MakeChildren(List <ChessAI> playerList, List <int> pointsList, int maxPlayerNumber) { List <ChessAI> raffle = new List <ChessAI>(); for (int i = 0; i < playerList.Count; i++) { if (pointsList[i] > 5) { raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); } else if (pointsList[i] > 0) { raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); } else { raffle.Add(playerList[i]); } } while (playerList.Count < maxPlayerNumber) { int father = Random.Range(0, raffle.Count); int mother = Random.Range(0, raffle.Count); if (father != mother) { ChessAIDNA kid = CrossOver(raffle[father], raffle[mother]); kid = Mutate(kid); ChessAI newAI = BuildNetworkFromGene(kid); playerList.Add(newAI); } } Debug.Log("Next Generation ready!"); return(playerList); }
public void PrepareGame(bool resetScore = true) { chessAI = ChessAI.Instance; // Start game boardState.Reset(); teamTurn = EChessTeam.White; if (scores == null) { scores = new List <uint>(); scores.Add(0); scores.Add(0); } if (resetScore) { scores.Clear(); scores.Add(0); scores.Add(0); } }
void Start() { AI = new ChessAI(Game, computerLvl); for (int i = 0; i < 64; i++) { var chessButton = Instantiate(chessButtonPrefub); chessButton.transform.SetParent(ChessBoard.transform); VisualBoard[i] = (new ChessButton(chessButton, i)); var temp = i; VisualBoard[i].Button.onClick.AddListener(() => ButtonClicked(VisualBoard[temp])); VisualBoard[i].Shape = Instantiate(Shape); VisualBoard[i].Shape.transform.SetParent(VisualBoard[i].Button.transform); } allButtons = GameObject.FindObjectsOfType <Button>(); NewGame(); playSounds = true; TextComputerLvl.text = computerLvl.ToString(); AI.compLvl = computerLvl; ChessPieceAnimation.enabled = false; }
private void AITurn() { if (first) { first = false; Debug.Log(String.Format("White Chess Down:{0},{1},{2}", 7, 7, 0)); boardData[7, 7] = (GameObject)Instantiate(whiteChessPrefab, new Vector3(7, 0, 7), Quaternion.identity); ChessAI.board[7, 7] = 2; end = ChessAI.CheckWinner(7, 7, 2); Debug.Log(end); role = 1; return; } int[] maxPoint = ChessAI.NextMove(role); Debug.Log(String.Format("White Chess Down:{0},{1},{2}", maxPoint[0], maxPoint[1], maxPoint[2])); boardData[maxPoint[0], maxPoint[1]] = (GameObject)Instantiate(whiteChessPrefab, new Vector3(maxPoint[0], 0, maxPoint[1]), Quaternion.identity); ChessAI.board[maxPoint[0], maxPoint[1]] = 2; end = ChessAI.CheckWinner(maxPoint[0], maxPoint[1], 2); Debug.Log(end); role = 1; }
private ChessAIDNA CrossOver(ChessAI father, ChessAI mother) { highestTransmitterNumber = father.aIDNA.highestTransmitterNumber; if (mother.aIDNA.highestTransmitterNumber > highestTransmitterNumber) { highestTransmitterNumber = mother.aIDNA.highestTransmitterNumber; } List <ChessDNA> kidDNA = new List <ChessDNA>(); for (int i = 0; i < father.aIDNA.DNA.Count; i++) { int chooseOne = Random.Range(0, 2); if (chooseOne == 0) { kidDNA.Add(CopyDNA(father.aIDNA.DNA[i].chessGenes)); } else { kidDNA.Add(CopyDNA(mother.aIDNA.DNA[i].chessGenes)); } } return(new ChessAIDNA(kidDNA, highestTransmitterNumber)); }
private void DrawPrefab() { first = false; if (clone != null && selectionX == lastSelectionX && selectionY == lastSelectionY && Input.GetMouseButtonDown(0) && boardData[selectionX, selectionY] == null) { Debug.Log(String.Format("Black Chess Down:{0},{1}", selectionX, selectionY)); boardData[selectionX, selectionY] = (GameObject)Instantiate(blackChessPrefab, new Vector3(selectionX, 0, selectionY), Quaternion.identity); ChessAI.board[selectionX, selectionY] = 1; end = ChessAI.CheckWinner(selectionX, selectionY, 1); Debug.Log(end); role = 2; } if (clone != null && (selectionX != lastSelectionX || selectionY != lastSelectionY)) { Destroy(clone); } if (clone == null && selectionX >= 0 && selectionX < 15 && selectionY >= 0 && selectionY < 15 && boardData[selectionX, selectionY] == null) { clone = (GameObject)Instantiate(blackChessPrefab, new Vector3(selectionX, 0, selectionY), Quaternion.identity); lastSelectionX = selectionX; lastSelectionY = selectionY; } }
// Use this for initialization void Start() { chess = GameObject.FindObjectOfType <Chess>(); chessAI = GameObject.FindObjectOfType <ChessAI>(); }
void Awake() { Instance = this; }
public void ConnectPlayers(ChessAI p1, ChessAI p2) { player1 = p1; player2 = p2; }
public void GetRandMoveWrapper(Object stateInfo) { WorkerInfo workerInfo = (stateInfo as WorkerInfo); using (var Context = _dbContextFactory.Create()) { WorkerResult workerResult = Context.WorkerResults.Find(workerInfo.WorkerID); workerResult.Fen = Fen.PositionToFen(PieceData.MakeMove(workerInfo.GamePosition, ChessAI.GetRandMove(workerInfo.GamePosition, workerInfo.Color))); workerResult.Finished = true; Context.Update(workerResult); Context.SaveChanges(); } }
public ChessGameWithPC( ) { _validator = new ChessToolValidate(new ChessDotNet.ChessGame()); _ai = new ChessAI(); level = Config.Get().BotLevel; }
private List <ChessAI> CullAIs(List <ChessAI> playerList, List <int> pointsList) { // Find out the highest score and save it to make sure the highest score does not get deleted. int highestScore = int.MinValue; foreach (int score in pointsList) { if (score > highestScore) { highestScore = score; } } // Cull the weak // Currently every AI with positive score gets the same treatment... Need a better system? List <ChessAI> raffle = new List <ChessAI>(); for (int i = 0; i < playerList.Count; i++) { if (pointsList[i] == highestScore) { // Don't remove this score. } else if (pointsList[i] < -14) { raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); } else if (pointsList[i] < -5) { raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); } else if (pointsList[i] < 0) { raffle.Add(playerList[i]); raffle.Add(playerList[i]); raffle.Add(playerList[i]); } else { raffle.Add(playerList[i]); } } if (raffle.Count < numToCull) { // all AIs are generally equal. We should just cull at random. raffle = new List <ChessAI>(); foreach (ChessAI ai in playerList) { raffle.Add(ai); } Debug.Log("All players equal, deleting at random!"); } for (int i = 0; i < numToCull; i++) { int toCUll = Random.Range(0, raffle.Count); ChessAI aIToCull = raffle[toCUll]; playerList.Remove(aIToCull); raffle.RemoveAll(aI => aI == aIToCull); } return(playerList); }
public ChessAI BuildNetworkFromGene(ChessAIDNA gene) { // Keep a list of all neurons that are available to make new connections (initialize at input neurons) // If the neuron is set to wait, let it wait, otherwise, find a neuron that can be connected // If there is no neuron available with the correct transmitter, make a new neuron with the settings from the gene ChessAI aI = new ChessAI(gene); aI.inputNeurons = new List <ChessNeuron>(); List <ChessNeuron> availableOutNeurons = new List <ChessNeuron>(); List <ChessNeuron> availableInNeurons = new List <ChessNeuron>(); List <ChessNeuron> outputNeurons = new List <ChessNeuron>(); List <ChessNeuron> allNeurons = new List <ChessNeuron>(); // First, make the list of output neurons. outputNeurons = MakeOutputNeurons(); foreach (ChessDNA chessDNA in gene.DNA) { ChessNeuron tempNeuron = new ChessNeuron(chessDNA.chessGenes); tempNeuron.MakeInputNeuron(); aI.inputNeurons.Add(tempNeuron); availableOutNeurons.Add(tempNeuron); allNeurons.Add(tempNeuron); } while (availableOutNeurons.Count > 0) { // Build the network List <ChessNeuron> nextAvailableList = new List <ChessNeuron>(); foreach (ChessNeuron neuron in availableOutNeurons) { if (neuron.CheckIfAvailable()) { List <int> possibleOut = neuron.CheckPossibleOut(); foreach (int i in possibleOut) { ChessNeuron possibleConnection = CheckPossibleIns(i, availableInNeurons); if (possibleConnection != null) { neuron.ConnectToNeuron(possibleConnection, i); if (possibleConnection.CheckIfInConnectionsFull()) { availableInNeurons.Remove(possibleConnection); } } else { ChessNeuron tempNeuron = neuron.MakeNewNeuron(i); allNeurons.Add(tempNeuron); if (tempNeuron.GetNeuronType() == 1) { neuron.ForceConnect(tempNeuron); if (!tempNeuron.CheckIfInConnectionsFull()) { availableInNeurons.Add(tempNeuron); } nextAvailableList.Add(tempNeuron); } else if (tempNeuron.GetNeuronType() == 2) { tempNeuron.MakePreOutputNeuron(outputNeurons); if (!tempNeuron.CheckIfInConnectionsFull()) { availableInNeurons.Add(tempNeuron); } } else { Debug.Log("Error: unexpected Neuron type?"); } } } } else { // put the neuron in the nextavailableList with a position equal to its wait time if (nextAvailableList.Count >= neuron.waitForConnection) { nextAvailableList.Insert(neuron.waitForConnection, neuron); neuron.waitForConnection = 0; } else { nextAvailableList.Add(neuron); neuron.waitForConnection -= nextAvailableList.Count; } } } availableOutNeurons = nextAvailableList; } aI.outputNeurons = outputNeurons; aI.allNeurons = allNeurons; return(aI); }