/// <summary> /// Converts a game tree /// </summary> /// <param name="tree">SGF game tree</param> /// <returns>Game tree root</returns> private GameTree ConvertTree(SgfGameTree tree) { var boardSizeInt = tree.GetPropertyInSequence("SZ")?.Value <int>() ?? 19; if (boardSizeInt == 0) { boardSizeInt = 19; } GameBoardSize boardSize = new GameBoardSize(boardSizeInt); var converted = ConvertBranch(tree, boardSize); var ruleset = new ChineseRuleset(boardSize); // Post-processing converted.ForAllDescendants((node) => node.Branches, node => { if (node.Parent == null) { node.FillBoardStateOfRoot(boardSize, ruleset); } else { node.FillBoardState(ruleset); } }); var gameTree = new GameTree(new ChineseRuleset(boardSize), boardSize, converted); gameTree.LastNode = gameTree.GameTreeRoot; return(gameTree); }
/// <summary> /// Run the specified game. /// </summary> /// <param name="game">Game to run.</param> public virtual void Run(Game game) { GameTree.SetRunningGame(game); // - Initialize windows manager Windows.Initialize(); // - Make a new window Window.Make(); Window.Show(); // - Initialize input apis Input.Initialize(); // - Add services GameTree.AddService(Input.GetSettings(PhysicsGameLoop)); GameTree.AddService(Windows.GetSettings(PhysicsGameLoop)); // - Load the game GameTree.Initialize(); // - Start gameloops PhysicsGameLoop.Run(); InputGameLoop.Run(); }
private void SiMove() { var gameTree = new GameTree(gameBoard); var node = gameTree.CreateTree(playerOpponent, 4, null); var miniMax = new Minimax.Minimax(); node.Value = miniMax.Compute(node, 3, int.MinValue, int.MaxValue, true); int value = 0; value = node.Children.Max(c => c.Value); //List<int> forDebbug = new List<int>(); //node.Children.ForEach(a => forDebbug.Add(a.Value)); var nextNode = node.Children.OrderBy(c => Guid.NewGuid()).FirstOrDefault(c => c.Value == value); gameBoard = nextNode.GameBoardState; if (nextNode.ActionType == ActionType.Move) { var gameTreeTemp = new GameTree(gameBoard); var blackPawnCords = gameTreeTemp.GetCoords('b'); int[] temp = new int[2] { blackPawnCords.FirstOrDefault().Y, blackPawnCords.FirstOrDefault().X }; blackPawnPosition = temp; } }
public AiTree(ChessBoard board, PieceColor color) { var rootData = new GameTreeNodeData <AiData, AiAction>(new AiData(board)); var rootColor = color == PieceColor.Red ? GameTreeNodeColor.Red : GameTreeNodeColor.Black; gameTree = new GameTree <AiData, AiAction>(rootData, rootColor); }
// This function should be called when we want this player to play public IEnumerator PlayTurn() { yield return(new WaitUntil(() => playerTurnIndex == globalTurn)); // only play when it is the current player's turn if (GameBoardInformation.isGameOver == true) { WriteTextFile.Write(); yield break; } else { StartCoroutine(MakeMove()); // This is where the player will actually perform the move. yield return(new WaitUntil(() => finishedMove == true)); finishedMove = false; // resets to false, to allow the player to play again GameTree.UpdateGameStateAndTree(lastMove); TechnicalStatistics.LastHeuristic = GameTree.head.HeuristicValue; TechnicalStatistics.LastMoveString = TechnicalStatistics.GetLastMoveString(GameTree.head, secondsPassed); TechnicalStatistics.totalTimePassed += secondsPassed; // once we reach here, all the parameters of TechnicalStatistics have been updated properly. // Therefore, we will add this move to our List of moves here. WriteTextFile.AddMove(); GameBoardInformation.updateGameOver(); globalTurn = (globalTurn + 1) % 2; // increase index to say that it is the other player's turn yield return(PlayTurn()); } }
public async Task <AIDecision> Hint(GameInfo gameInfo, GamePlayer player, GameTree tree, StoneColor color) { var aiTask = Task.Run(() => Program.GetHint(new AiGameInformation(gameInfo, color, player, tree))); AIDecision decision = await aiTask; return(decision); }
public static void DrawTree(GameTree tree, string path) { var renderer = new DotRenderer(@"C:\Program Files (x86)\Graphviz2.38\bin\dot.exe"); var vv = tree.BuildGraph(); renderer.Render(vv.Item1, vv.Item2, path, DotRenderType.png, true); }
public Room(GameTree gt, bool _isMain, bool _isObjective, float _offsetX, float _offsetY, float _locationToSpriteScale) { parentTree = gt; isMain = _isMain; isObjective = _isObjective; offsetX = _offsetX; offsetY = _offsetY; locationToSpriteScale = _locationToSpriteScale; }
/// <summary> /// Informs the AI engine that a move was just made. Stateful AIs (i.e. Fuego) use this. /// <para> /// This is called synchronously in the main thread by the game controller or the assistant. /// </para> /// </summary> /// <param name="move">The move.</param> /// <param name="gameTree">The game tree.</param> /// <param name="informedPlayer">The player who is associated with this AI, not the player who made the move.</param> /// <param name="info">Information about the game</param> public override void MovePerformed(Move move, GameTree gameTree, GamePlayer informedPlayer, GameInfo info) { var action = new OldFuegoAction(this, () => { FixHistory(new AiGameInformation(info, informedPlayer.Info.Color, informedPlayer, gameTree)); return(default(AIDecision)); }); EnqueueAction(action); }
/// <summary> /// Creates a new structure that gives the AI information it needs to make a move. /// </summary> /// <param name="gameInfo">Game info</param> /// <param name="aiColor">The player whose turn it is. The AI will make a move for this player.</param> /// <param name="aiPlayer">AI player</param> /// <param name="gameTree">The current full board state (excluding information about Ko). </param> public AiGameInformation(GameInfo gameInfo, StoneColor aiColor, GamePlayer aiPlayer, GameTree gameTree) { GameInfo = gameInfo; AIColor = aiColor; AiPlayer = aiPlayer; GameTree = gameTree; Node = gameTree.LastNode; // Some concurrency problems may occur here, but they're very unlikely. // If we want to solve them, then gameTree.LastNode should be given as an argument to this. }
public MCTSTest() { testDomainName = "spy-types"; testDomainDirectory = Parser.GetTopDirectory() + @"Benchmarks\" + testDomainName + @"\domain.pddl"; testDomain = Parser.GetDomain(Parser.GetTopDirectory() + @"Benchmarks\" + testDomainName + @"\domain.pddl", PlanType.StateSpace); testProblem = Parser.GetProblemWithTypes(Parser.GetTopDirectory() + @"Benchmarks\" + testDomainName + @"\prob01.pddl", testDomain); path = Parser.GetTopDirectory() + @"GameTrees\Data\Unit-Tests\"; tree = new GameTree(testDomain, testProblem, path); }
private static void Main(string[] args) { GameTree minimax; MCGameTree monteCarlo; Random rng = new Random(); int wins = 0; while (true) { bool miniFirst = rng.Next(0, 2) == 0; minimax = new GameTree(!miniFirst); monteCarlo = new MCGameTree(miniFirst); int miniMove = -1; int mcMove = -1; if (miniFirst) { miniMove = Array.FindIndex(minimax.CurrentStatus.Board, t => t == TileState.X); } else { mcMove = Array.FindIndex(monteCarlo.CurrentStatus.Board, t => t == TileState.X); } while (!minimax.CurrentStatus.IsTerminal) { if (miniFirst) { mcMove = monteCarlo.Move(miniMove); miniMove = minimax.Move(mcMove); } else { miniMove = minimax.Move(mcMove); mcMove = monteCarlo.Move(miniMove); } } if (miniFirst) { mcMove = monteCarlo.Move(miniMove); miniMove = minimax.Move(mcMove); } else { miniMove = minimax.Move(mcMove); mcMove = monteCarlo.Move(miniMove); } Console.WriteLine($"Minimax\t\t{miniFirst}\t{minimax.State}"); Console.WriteLine($"MonteCarlo\t{!miniFirst}\t{monteCarlo.State}\n"); Console.ReadKey(true); } }
public void GameTreeRootTest() { tree = new GameTree(testDomain, testProblem, Parser.GetTopDirectory() + @"GameTrees\Data\"); GameTreeNode root = tree.Root; Assert.AreEqual(root.ID, 0); Assert.IsFalse(root.IsGoal); Assert.AreEqual(root.Outgoing.Count, 4); Assert.IsTrue(tree.Simulate(root.ID)); }
public void PerformanceTests() { var gameTree = new GameTree(); var board = Board.Factory.GetDefault(); var sw = Stopwatch.StartNew(); var moves = gameTree.AlphaBetaRecursive(board, 6, true); var t1 = sw.ElapsedMilliseconds; }
// public void UnsubscribeEveryoneFromController() { GamePhaseStarted = null; GamePhaseChanged = null; GameTree.UnsubscribeEveryoneFromGameTree(); TurnPlayerChanged = null; GameEnded = null; DebuggingMessage = null; MoveUndone = null; }
/// <summary> /// Close the running game. /// </summary> public virtual void Close() { if (!GameTree.CloseGame()) { return; } PhysicsGameLoop.Stop(); InputGameLoop.Stop(); }
/// <summary> /// Dispose all resources used from this class. /// </summary> /// <param name="disposing">Dispose managed resources.</param> protected override void Dispose(bool disposing) { if (disposing) { Input.Dispose(); GameTree.Dispose(); Windows.Dispose(); } base.Dispose(disposing); }
public override void MovePerformed(Move move, GameTree gameTree, GamePlayer informedPlayer, GameInfo info) { if (_brokenDueToInvalidLaunch) { return; } RequireInitialization(new AiGameInformation(info, informedPlayer.Info.Color, informedPlayer, gameTree)); if (_isPrimaryPlayer) { FuegoSingleton.Instance.MovePerformed( new AiGameInformation(info, informedPlayer.Info.Color, informedPlayer, gameTree)); } }
/// <summary> /// Initializes a new instance of GameToolServices. /// </summary> /// <param name="ruleset">a ruleset that should be used for providing ruleset services</param> /// <param name="gameTree">a game tree representing the current game</param> public GameToolServices(Localizer localizer, IDialogService dialogService, IRuleset ruleset, GameTree gameTree) { _localizer = localizer; _dialogService = dialogService; if (ruleset == null) { ruleset = OmegaGo.Core.Rules.Ruleset.Create(RulesetType.Chinese, gameTree.BoardSize); } _ruleset = ruleset; _gameTree = gameTree; }
public void InitializePreparedPositionControl() { preparedPositionsControl.SelectedIndexChanged += PreparedPositions_SelectedIndexChanged; DirectoryInfo preparedPositionsDirectory = new DirectoryInfo(Settings.GoPreparedPositionsDirectoryPath); SgfReader sgfParser = new SgfReader(); foreach (FileInfo file in preparedPositionsDirectory.EnumerateFiles("*.sgf")) { Collection collection = sgfParser.ReadStream(file.OpenRead()); GameTree gameTree = collection.Games.First(); FieldCoordinates[] position = ToPosition(gameTree); preparedPositionsControl.Items.Add(new NamedObject <FieldCoordinates[]>(file.Name, position)); } }
/// <summary> /// Makes a new instance of <see cref="GameHost"/> class. /// </summary> public GameHost() { // - Initialize environment if not initialized pEngine.Platform.Environment.Initialize(); // - Make game loops InputGameLoop = new GameLoop(HandleInput, InputInitialization, "InputThread"); PhysicsGameLoop = new ThreadedGameLoop(HandlePhysics, PhysicsInitialization, "PhysicsThread"); // - Modules Input = new InputEngine(this, InputGameLoop); GameTree = new GameTree(this, PhysicsGameLoop); Windows = new WindowsProvider(this, InputGameLoop); }
public void GameTreeTest() { var gameTree = new GameTree(); var board = Board.Factory.GetDefault(); var moves = gameTree.AlphaBetaRecursive(board, 6, true); var board2 = board.MakeMove(moves.First()); var moves2 = gameTree.AlphaBetaRecursive(board2, 6, false); var board3 = board.MakeMove(moves2.First()); var moves3 = gameTree.AlphaBetaRecursive(board3, 6, true); var board4 = board.MakeMove(moves3.First()); }
public Room(Room parent, GameTree gt, float _difficulty, bool _isObjective, int _depth, Room[,] grid, int initX, int initY, float _locationToSpriteScale, float _offsetX, float _offsetY) { parentRoom = parent; parentTree = gt; roomDifficulty = _difficulty; isObjective = _isObjective; depth = _depth; type = depth; x = initX; y = initY; offsetX = _offsetX; offsetY = _offsetY; grid[initX, initY] = this; locationToSpriteScale = _locationToSpriteScale; makeSpawner(false); }
/// <summary> /// Gets the LastNode of the tree. If none exists yet, we are at the very beginning of a game, and we'll use an empty board instead. /// </summary> protected GameTreeNode GetLastNodeOrEmptyBoard(GameTree gameTree) { GameTreeNode lastNode = gameTree.LastNode; if (lastNode == null) { GameTreeNode empty = new GameTreeNode(Move.NoneMove); empty.BoardState = new GameBoard(gameTree.BoardSize); empty.GroupState = new Rules.GroupState(gameTree.Ruleset.RulesetInfo); return(empty); } else { return(lastNode); } }
public Tournament(int players, string level) { Level = level; Program.Tournament = this; Tree = new GameTree(players); for (int i = Tree.Levels; i > 0; i--) { int j = 0; int LevelSize = (int)Math.Pow(2, i - 1) + 1; foreach (var a in Tree.GetLevel(Tree.Head, i)) { a.Anchor = new Vec2((1.0 / LevelSize) * ++j, (1.0 / (Tree.Levels + 1)) * (Tree.Levels - i + 1)); Frame.Add(a); } } }
public void TestExpansion() { GameTree gameTree = new GameTree(Board.GetBasicBoard(), Status.PlayerOne, 1, 0); gameTree.Expand(); GameTree expected = new GameTree(Board.GetBasicBoard(), Status.PlayerOne, 1, 0); expected.Children = new List <GameTree>(); Board basicBoard = Board.GetBasicBoard(); for (int i = 0; i < basicBoard.Positions.Count; ++i) { Board board = basicBoard.Clone(); board.Positions.ElementAt(i).Status = Status.PlayerOne; expected.Children.Add(new GameTree(board, Status.PlayerTwo, 1, 1)); } Assert.Equal(expected, gameTree); }
void Start() { allActiveGameObjects = new List <GameObject>(); gameTree = new GameTree(); parent = null; started = true; prevMoveLeft = false; prevMoveRight = false; current = new PeopleNode("Elvis Presley"); questionBox = GameObject.Find("QuestionField"); questionButton = GameObject.Find("SubmitQuestion"); yesButton = GameObject.Find("YesButton"); noButton = GameObject.Find("NoButton"); questionTextBox = GameObject.Find("QuestionText"); questionText = questionTextBox.GetComponent <Text>(); resetButton = GameObject.Find("Reset"); startOverButton = GameObject.Find("StartOver"); nameField = GameObject.Find("NameField"); submitName = GameObject.Find("SubmitName"); promptTextBox = GameObject.Find("PromptText"); promptText = promptTextBox.GetComponent <Text>(); addYesButton = GameObject.Find("AddYesButton"); addNoButton = GameObject.Find("AddNoButton"); saveButton = GameObject.Find("SaveGame"); mainButton = GameObject.Find("MainMenu"); saveName = GameObject.Find("SaveName"); submitSave = GameObject.Find("SubmitSave"); questionText.text = "Think of a person...\n" + current.AskQuestion(); questionTextBox.SetActive(true); noButton.SetActive(true); yesButton.SetActive(true); questionButton.SetActive(false); questionBox.SetActive(false); resetButton.SetActive(false); startOverButton.SetActive(false); nameField.SetActive(false); submitName.SetActive(false); promptTextBox.SetActive(false); addYesButton.SetActive(false); addNoButton.SetActive(false); submitSave.SetActive(false); saveName.SetActive(false); }
private FieldCoordinates[] ToPosition(GameTree gameTree) { List <FieldCoordinates> result = new List <FieldCoordinates>(); while (gameTree != null) { foreach (var node in gameTree.Sequence.Nodes) { foreach (var color in new[] { "B", "W" }) { var m = node.Properties.FirstOrDefault(p => color.Equals(p.Ident.Text, StringComparison.OrdinalIgnoreCase)); if (m != null) { result.Add(FieldCoordinates.ParseSgf(m.Values.First())); } } } gameTree = null; } return(result.ToArray()); }
public void TestTreeUsage([Values(true, false)] bool ParallelClone) { Settings.ParallelClone = ParallelClone; var game = _setupGame(7, 2, "Bloodfen Raptor"); game.MaxMinionsOnBoard = 10; // Make a new tree with the game as the root var tree = new GameTree <ProbabilisticGameNode>(new ProbabilisticGameNode(game)); // Add arbitrary number of children int children = 3; var depth1Nodes = tree.RootNode.Branch(children).ToList(); // Check the correct number of games were cloned Assert.AreEqual(children, depth1Nodes.Count); Assert.AreEqual(children, tree.RootNode.Children.Count); // Assert all children have correct parent in both GameNode and Game foreach (var n in depth1Nodes) { Assert.AreSame(game, n.Parent.Game); Assert.AreSame(tree.RootNode, n.Parent); } // Check all child games are unique but exact clones var childGameIds = new List <int>(); foreach (var n in depth1Nodes) { Assert.False(childGameIds.Contains(n.Game.GameId)); Assert.True(game.EquivalentTo(n.Game)); childGameIds.Add(n.Game.GameId); } // Get all games from nodes var depth1Games = depth1Nodes.Select(n => n.Game).ToList(); // Do something different on each child depth1Games[0].CurrentPlayer.Give("Flame Juggler").Play(); depth1Games[1].CurrentPlayer.Give("Arcane Missiles").Play(); depth1Games[2].CurrentPlayer.Give("Whirlwind").Play(); // Check every game is different var childHashes = new List <int>(); foreach (var g in depth1Games) { Assert.False(childHashes.Contains(g.FuzzyGameHash)); childHashes.Add(g.FuzzyGameHash); } // Do a random action on the first game in depth 1 and add all possible outcomes as children Minion FirstBoomBot = depth1Games[0].CurrentPlayer.Board.First(x => x.Card.Id == "GVG_110t"); var boomBotResults = RandomOutcomeSearch.Find(depth1Games[0], () => FirstBoomBot.Hit(1)); var depth2Nodes = depth1Nodes[0].AddChildren(boomBotResults).ToList(); // Check the correct number of games were cloned Assert.AreEqual(boomBotResults.Count, depth2Nodes.Count); Assert.AreEqual(boomBotResults.Count, depth1Nodes[0].Children.Count); // Assert all children have correct parent in both GameNode and Game foreach (var n in depth2Nodes) { Assert.AreSame(depth1Games[0], n.Parent.Game); Assert.AreSame(depth1Nodes[0], n.Parent); } }
static void Main(string[] args) { //Tester.Train(); string[] inputs; Referee.GameReferee.Reset(); GameTree tree = null; // game loop bool firstStep = true; while (true) { inputs = Console.ReadLine().Split(' '); int opponentRow = int.Parse(inputs[0]); int opponentCol = int.Parse(inputs[1]); var oponentMove = new Tuple <int, int>(opponentRow, opponentCol); int validActionCount = int.Parse(Console.ReadLine()); int row = 0, col = 0; for (int i = 0; i < validActionCount; i++) { inputs = Console.ReadLine().Split(' '); row = int.Parse(inputs[0]); col = int.Parse(inputs[1]); } Referee.GameReferee.Move(opponentRow, opponentCol); if (firstStep) { tree = new GameTree(oponentMove, Referee.GameReferee._field, 6 - Referee.GameReferee._field.Player); tree.Simulate(980); firstStep = false; } else { tree.Update(oponentMove, Referee.GameReferee._field); tree.Simulate(80); } // Write an action using Console.WriteLine() // To debug: Console.Error.WriteLine("Debug messages..."); var move = tree.GetNextStep(); if (move == null) { move = new Tuple <int, int>(row, col); } //Console.Error.WriteLine($"{tree._startLeaf.Move.Item1}:{tree._startLeaf.Move.Item2} "); //foreach (var m in tree._startLeaf.SubLeafs) //{ // Console.Error.Write($"{m.Move.Item1}:{m.Move.Item2} "); //} //Console.Error.WriteLine(); //foreach (var m in Referee.GameReferee.GetNextMoves()) //{ // Console.Error.Write($"{m.Item1}:{m.Item2} "); //} var test = Referee.GameReferee.Move(move.Item1, move.Item2); Console.Error.WriteLine(tree._startLeaf.Simulations); tree.Update(move, Referee.GameReferee._field); Console.WriteLine($"{move.Item1} {move.Item2}"); } }
public GameInfo() { GameTree = new GameTree() { Number = 0, Root = true }; }