示例#1
0
文件: BFS2.cs 项目: martugin/tetris
        public void ReachStateUsingPhrases(UnitState startState, UnitState finalState)
        {
            var backBfs = new BFS2(_field, _unit, _gameData);
            #if false// DEBUG
            DebugPrinter.WriteLine("Checking what is reachable back from: ({0}, {1}) rot {2}", finalState.Pivot.x, finalState.Pivot.y, finalState.Rotation);
            var reachableArr = backBfs.DoSimpleBfs(finalState, true).Select(st => st.UnitState).ToArray();

            foreach (var st in reachableArr)
                DebugPrinter.WriteLine("    reachable: ({0}, {1}) rot {2}", st.Pivot.x, st.Pivot.y, st.Rotation);
            var reachableStates = new HashSet<UnitState>(reachableArr);
            #else
            var reachableStates = new HashSet<UnitState>(backBfs.DoSimpleBfs(finalState, true, false).Select(st => st.UnitState));
            #endif

            _visited[startState] = new VisitInfo
            {
                MoveFuncIndex = -1,
                PrevState = null,
                AllPrevStates = new HashSet<UnitState>(),
            };

            UnitState curState = startState;

            PowerPhraseInfo prevPhrase = _gameData.PowerPhraseData.Phrases[0]; // empty phrase

            List<int> curReversedPath = null;

            while (curState != finalState)
            {
                UnitState stateAfterPhrase;
                PowerPhraseInfo appliedPhrase;
                List<int> reversedPathAfterPhrase;
                var prevState = curState;
                bool phraseApplied = ApplySomePhrase(curState, prevPhrase, reachableStates, finalState,
                    out stateAfterPhrase, out appliedPhrase, out reversedPathAfterPhrase);
                curState = stateAfterPhrase;

                if (phraseApplied)
                {
                    //movesStr += appliedPhrase.Phrase;
                    curReversedPath = reversedPathAfterPhrase;
                    prevPhrase = appliedPhrase;
                    continue;
                }

                prevPhrase = _gameData.PowerPhraseData.Phrases[0];

                // Do BFS step
                if (curReversedPath == null)
                {
                    bool reachable = _IsReachable(curState, finalState, out curReversedPath);
                    Debug.Assert(reachable);
                }

                int move = curReversedPath[curReversedPath.Count - 1];
                var state = curState;
                curState = UnitState.MoveFuncs[move](curState);
                curState.Normalize(_unit);
                curReversedPath.RemoveAt(curReversedPath.Count - 1);

                _visited[curState] = new VisitInfo
                {
                    MoveFuncIndex = move,
                    PrevState = state,
                    MoveChar = ANY_CHAR,
                };
            }
        }
示例#2
0
文件: Algo2.cs 项目: martugin/tetris
        public AlgoResult Run(int seed)
        {
            DebugPrinter.WriteLine("------------------------\nseed: {0}", seed);
            int cnt = 0;
            #if DEBUG
            var allMoves = new List<int>();
            #endif
            var allMovesStr = "";
            int prevScore = 0;
            int totalBricks = 0;

            var randSequence = RandGen.RandSequence(seed, _gameData.InputData.sourceLength).Select(x => x % _gameData.Units.Length).ToArray();

            var field = new Field(_gameData.InputData);
            #if DEBUG
            var simulator = new Simulator(new Field(_gameData.InputData));
            #endif
            field.MetricUnits = new MetricUnits(field, _gameData, randSequence);
            field.MetricUnits.CalcTailMetrics(0);
            DebugPrinter.WriteLine("RowPower: {0}", field.MetricUnits.AverageRowPower);

            for (int i = 0; i < randSequence.Length; i++)
            {
                if ((i+1) % 10 == 0)
                    DebugPrinter.WriteTrace("        unit #{0}/{1}", i + 1, randSequence.Length);

                var rnd = randSequence[i];
                field.MetricUnits.CalcTailMetrics(i);
                int unitIndex = rnd % _gameData.Units.Length;
                DebugPrinter.WriteLine("step {0}, unit #{1}", cnt, unitIndex);

                Unit unit = _gameData.Units[unitIndex];
                DebugPrinter.WriteLine(PrettyPrinter.PrettyPrint(unit));

                var startState = field.SpawnUnit(unit);
                if (startState == null)
                {
                    DebugPrinter.WriteLine("No space to spawn unit");
                    break;
                }

                var bfs = new BFS2(field, unit, _gameData);
                BestStateInfo bestState = null;

                foreach (var bfsState in bfs.DoSimpleBfs(startState, false, true))
                {
                    //DebugPrinter.WriteLine("got state: ({0}, {1}), rot {2}", bfsState.UnitState.Pivot.x, bfsState.UnitState.Pivot.y, bfsState.UnitState.Rotation);
                    ////#if DEBUG
                    //DebugPrinter.WriteLine("On the field:");
                    //DebugPrinter.WriteLine(PrettyPrinter.PrettyPrintBeforeUpdate(field, unit,
                    //    bfsState.UnitState, bfs.GetPathCells(bfsState.UnitState)));
                    ////#endif

                    var newBestState = new BestStateInfo(field, unit, bfsState);
                    if (bestState != null && !newBestState.IsBetter(bestState))
                        continue;

                    bestState = newBestState;
                }
                //DebugPrinter.WriteLine("Best state: ({0}, {1}), rot {2}", bestState.BfsState.UnitState.Pivot.x, bestState.BfsState.UnitState.Pivot.y, bestState.BfsState.UnitState.Rotation);

                // now try to reach the state using phrases
                bfs = new BFS2(field, unit, _gameData);
                bfs.ReachStateUsingPhrases(startState, bestState.BfsState.UnitState);

            #if DEBUG
                Debug.Assert(bestState != null);
            #else
                if (bestState == null)
                    continue;
            #endif

                DebugPrinter.WriteLine("best state: ({0}, {1}), rot {2}, minY {3}, maxY {4}",
                    bestState.BfsState.UnitState.Pivot.x, bestState.BfsState.UnitState.Pivot.y, bestState.BfsState.UnitState.Rotation, bestState.MinY, bestState.MaxY);

            #if DEBUG
                var moves = bfs.GetMoves(bestState.BfsState.UnitState, startState);
                DebugPrinter.WriteLine("Moves:");
                foreach (int move in moves)
                    DebugPrinter.Write("{0},", move);
                DebugPrinter.WriteLine("");

                DebugPrinter.WriteLine(MovesPrinter.PrintMoves(moves));

                allMoves.AddRange(moves);
                allMoves.Add(bestState.BfsState.BlockingMove);
            #endif

                var movesStr = bfs.GetMovesString(bestState.BfsState.UnitState);
                DebugPrinter.WriteLine(movesStr);
                allMovesStr += movesStr;
                allMovesStr += MovesPrinter.PrintOneMove(bestState.BfsState.BlockingMove);

            //#if DEBUG

                DebugPrinter.WriteLine("Blocking move: {0} {1}", bestState.BfsState.BlockingMove, MovesPrinter.PrintOneMove(bestState.BfsState.BlockingMove));

                DebugPrinter.WriteLine("Before update:");
                DebugPrinter.WriteLine(PrettyPrinter.PrettyPrintBeforeUpdate(field, unit,
                    bestState.BfsState.UnitState, bfs.GetPathCells(bestState.BfsState.UnitState)));
            //#endif

                field.Update(unit, bestState.BfsState.UnitState);

            //#if DEBUG
                DebugPrinter.WriteLine("After update:");
                DebugPrinter.Write(PrettyPrinter.PrettyPrint(field));
                DebugPrinter.WriteLine("Score: {0}", field.Score);
                DebugPrinter.WriteLine("Score diff: {0}", field.Score - prevScore);
                DebugPrinter.WriteLine("");
            //#endif

                prevScore = field.Score;
                totalBricks += unit.members.Length;
                _UpdatePowerPhraseUsage(movesStr);
                ++cnt;
                //if (cnt >= 20)
                //    break;
            #if DEBUG
                simulator.SimulateUnit(unit, startState, movesStr + MovesPrinter.PrintOneMove(bestState.BfsState.BlockingMove));
            #endif
            }

            #if DEBUG
            DebugPrinter.WriteLine("All moves:");
            foreach (int move in allMoves)
                DebugPrinter.Write("{0},", move);
            DebugPrinter.WriteLine("");
            #endif

            DebugPrinter.WriteLine("Total move score: {0}", field.Score);
            int phraseScore = _gameData.GetPowerPhraseScore(allMovesStr);
            DebugPrinter.WriteLine("Total phrase score: {0}", phraseScore);
            DebugPrinter.WriteLine("Total score: {0}", field.Score + phraseScore);

            DebugPrinter.WriteLine("Total bricks: {0}", totalBricks);
            int totalRowsKilled = field.RowsKilled.Sum(r => r.Key*r.Value);
            DebugPrinter.WriteLine("Total rows killed: {0}", totalRowsKilled);
            var rowsKilledKeys = field.RowsKilled.Keys.ToArray();
            Array.Sort(rowsKilledKeys);
            foreach (int rows in rowsKilledKeys)
                DebugPrinter.WriteLine("Rows {0}: {1}",  rows, field.RowsKilled[rows]);

            DebugPrinter.WriteTrace("Total move score: {0}", field.Score);
            DebugPrinter.WriteTrace("Total phrase score: {0}", phraseScore);
            DebugPrinter.WriteTrace("Total score: {0}", field.Score + phraseScore);

            DebugPrinter.WriteTrace("Total bricks: {0}", totalBricks);
            DebugPrinter.WriteTrace("Total rows killed: {0}", totalRowsKilled);
            foreach (int rows in rowsKilledKeys)
                DebugPrinter.WriteTrace("Rows {0}: {1}", rows, field.RowsKilled[rows]);

            string res = allMovesStr; //MovesPrinter.PrintMoves(allMoves);
            DebugPrinter.WriteLine(res);
            return new AlgoResult(res, field.Score + phraseScore);
        }