示例#1
0
 private string ToLog(CGameResult move)
 {
     try
     {
         string log = "{0} {1}→{2}".Form(move.Piece.Symbol(), Alphabet[move.Origin], Alphabet[move.Destination]);
         return(move.Piece.Color == PieceColor.White ? log : "[{0}]".Form(log));
     }
     catch (IndexOutOfRangeException)
     {
         return("<unknown>");
     }
 }
    protected override IEnumerator TwitchHandleForcedSolve()
    {
        // This cancels any selected square prior.
        if (Module.last != null)
        {
            Module.Buttons[(int)Module.last].OnInteract();
        }

        while (!Module.IsSolved)
        {
            var game = new CGameResult {
            };

            bool isReady = false;

            while (!Module.isReady)
            {
                yield return(true);
            }

            new Thread(() =>
            {
                game    = Engine.Calculate(Module.position, Position.Depth, Module.color == PieceColor.White);
                isReady = true;
            }).Start();

            while (!isReady)
            {
                yield return(true);
            }

            int[] indices = new[] { (int)game.Origin, game.Destination };

            if (indices.Any(i => i == -1))
            {
                Module.Solve("The autosolver seemed to trip up a bit there. Force-solving now.");
            }
            else
            {
                yield return(OnInteractSequence(Module.Buttons, 1 / 64f, indices));
            }
        }
    }
示例#3
0
文件: Maingame.cs 项目: KHCmaster/PPD
        public override void Load()
        {
            if (!Param.ContainsKey("PPDGameUtility"))
            {
                throw new PPDException(PPDExceptionType.SkinIsNotCorrectlyImplemented);
            }
            ppdgameutility = Param["PPDGameUtility"] as PPDGameUtility;
            currentLatency = ppdgameutility.SongInformation.Latency;
            if (Param.ContainsKey("ExitOnReturn"))
            {
                exitonreturn = true;
            }
            if (Param.ContainsKey("StartTime"))
            {
                ppdgameutility.IsDebug = true;
                startTime   = (float)Param["StartTime"] - 3;
                mmStartTime = (float)Param["StartTime"];
            }
            else if (Param.ContainsKey("StartTimeEx"))
            {
                ppdgameutility.IsDebug = true;
                startTime   = (float)Param["StartTimeEx"];
                mmStartTime = (float)Param["StartTimeEx"];
            }
            else
            {
                startTime   = ppdgameutility.SongInformation.StartTime;
                mmStartTime = startTime;
            }

            black        = new PictureObject("img\\default\\black.png", 0, 0, false, ResourceManager, Device);
            black.Alpha  = 0;
            black.Hidden = true;

            string moviefile = ppdgameutility.SongInformation.MoviePath;

#if x64
            if (Path.GetExtension(moviefile) == ".mp4")
            {
                PlatformGap = 0.03f;
            }
#endif
            if (moviefile != "")
            {
                m = GameHost.GetMovie(moviefile);
                try
                {
                    if (m.Initialize() == -1)
                    {
                        throw new PPDException(PPDExceptionType.CannotOpenMovie);
                    }
                    readmoviesetting();
                    initialized = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    initialized = false;
                    ReturnToMenu();
                    return;
                }
            }
            else
            {
                MessageBox.Show("No moviefile");
                black.Hidden = false;
                if (exitonreturn)
                {
                    Application.Exit();
                }
                else
                {
                    ReturnToMenu();
                    return;
                }
            }
            keychange = new int[(int)ButtonType.Start];
            for (int i = 0; i < keychange.Length; i++)
            {
                keychange[i] = i;
            }
            if (ppdgameutility.Random)
            {
                randomchange();
            }
            readprofile();
            hm                  = new HoldManager(Device, ResourceManager);
            hm.ScoreGained     += new HoldManager.GainScoreEventHandler(hm_ScoreGained);
            ppdem               = new PPDEffectManager(Device, ResourceManager);
            km                  = new KasiManager(ppdgameutility);
            km.KasiChanged     += new KasiManager.KasiChangeEventHandler(km_KasiChanged);
            cgi                 = GameHost.GetCGameInterface();
            cgi.PPDGameUtility  = ppdgameutility;
            cgi.ResourceManager = ResourceManager;
            cgi.Load();
            sm = new SoundManager(Sound as ExSound, ppdgameutility);
            if (ppdgameutility.SongInformation.IsOld)
            {
                em = new EventManager(ppdgameutility);
                mm = new MarkManager(Device, em, ppdgameutility, keychange, ppdem, GameHost.GetMarkImagePath(), ResourceManager);
            }
            else
            {
                string              path   = Path.Combine(ppdgameutility.SongInformation.DirectoryPath, DifficultyUtility.ConvertDifficulty(ppdgameutility.Difficulty) + ".ppd");
                PackReader          reader = new PackReader(path);
                PPDPackStreamReader ppdpsr = reader.Read("evd");
                em = new EventManager(ppdgameutility, ppdpsr);
                ppdpsr.Close();
                ppdpsr = reader.Read("ppd");
                mm     = new MarkManager(Device, em, ppdgameutility, keychange, ppdem, GameHost.GetMarkImagePath(), ppdpsr, ResourceManager);
                ppdpsr.Close();
                reader.Close();
            }
            grm = new GameResultManager();
            gr  = GameHost.GetGameResult();
            gr.PPDGameUtility  = ppdgameutility;
            gr.ResourceManager = ResourceManager;
            gr.TweetManager    = this;
            gr.Load();
            pd = GameHost.GetPauseMenu();
            pd.PPDGameUtility  = ppdgameutility;
            pd.ResourceManager = ResourceManager;
            pd.Load();
            pd.Resumed           += new EventHandler(pd_Resumed);
            pd.Retryed           += new EventHandler(pd_Retryed);
            pd.Returned          += new EventHandler(pd_Returned);
            pd.LatencyChanged    += new ChangeLatencyEventHandler(pd_LatencyChanged);
            gr.Retryed           += new EventHandler(this.Retry);
            gr.Returned          += new EventHandler(this.Return);
            mm.ChangeCombo       += new MarkManager.ChangeComboHandler(mm_ChangeCombo);
            mm.PlaySound         += new MarkManager.SpecialSoundHandler(this.SpecialPlaySound);
            mm.StopSound         += new MarkManager.SpecialSoundHandler(this.SpecialStopSound);
            mm.EvaluateCount     += new MarkManager.EvaluateCountHandler(this.EvaluateCount);
            mm.PressingButton    += new MarkManager.PressingButtonHandler(mm_PressingButton);
            em.ChangeMovieVolume += new EventManager.VolumeHandler(ChangeMovieVolume);
            //seek
            mm.Seek(mmStartTime);
            em.Seek(startTime > 0 ? startTime : 0);
            sm.Seek(startTime);
            km.Seek(startTime);
            if (m != null && m.Initialized)
            {
                m.Play();
                m.Pause();
                m.Seek(startTime);
            }
            if (startTime < 0)
            {
                waitingmoviestart = true;
                lasttime          = Win32API.timeGetTime();
            }
            else
            {
                if (m != null && m.Initialized)
                {
                    m.Play();
                }
            }

            this.AddChild(black);
        }
示例#4
0
    private IEnumerator GetGoodPosition()
    {
        isWinning = true;
        isReady   = false;

        ChangeText("Waiting for", "other modules...");

        // This waits for an arbitrary amount of time, to let other copies of this module through at different rates.
        yield return(new WaitForSecondsRealtime(URandom.Range(0, 2)));

        // This waits until another module that uses threads in this exact method is finished.
        yield return(new WaitWhile(() => _isUsingThreads));

        _isUsingThreads = true;

        bool isEvaluating = false;

        string position = "";

        ChangeText("Preparing...", "Please wait.");

        var game  = new CGameResult {
        };
        var moves = new List <CGameResult>();

        new Thread(() =>
        {
            // Find a game that takes 6-8 moves to complete in ideal play, using the Rust library.
            while (true)
            {
                position     = RandomPosition;
                isEvaluating = true;
                game         = Engine.Calculate(position, Position.Depth, true);

                if (!Mathf.Abs(game.Evaluation).InRange(112, 116))
                {
                    continue;
                }

                // Sometimes the evaluation is in favor of black, we need to advance the game by one move so that it is black to move.
                if (game.Evaluation < 0)
                {
                    position = game.Move(position);
                }

                // Set the player side to always whichever one is winning.
                color = (PieceColor)Convert.ToInt32(game.Evaluation < 0);

                // Reset the move list.
                moves = new List <CGameResult>();

                var colorMut             = color;
                string positionMut       = position;
                bool isGameCorrectlyOver = false;

                // The bot plays against itself until the perfect game is constructed.
                for (int depth = Position.Depth; depth > 0; depth--)
                {
                    var gameMut = Engine.Calculate(positionMut, depth, colorMut == PieceColor.White);

                    if ((gameMut.Evaluation == sbyte.MaxValue && color == PieceColor.White) ||
                        (gameMut.Evaluation == sbyte.MinValue && color == PieceColor.Black))
                    {
                        isGameCorrectlyOver = true;
                    }

                    try
                    {
                        positionMut = gameMut.Move(positionMut);
                    }
                    // There are no moves to play when this exception is triggered.
                    catch (IndexOutOfRangeException)
                    {
                        break;
                    }

                    colorMut = colorMut.Flip();

                    moves.Add(gameMut);
                }

                // Ensures that what it logs is indeed a checkmate. This reverifies that the puzzle is possible.
                if (isGameCorrectlyOver && moves.Count == 128 - Math.Abs(game.Evaluation) - (color == PieceColor.White ? 1 : 0))
                {
                    break;
                }
            }

            this.position = position;

            souvenirPositions = new List <string>();

            isReady = true;
        }).Start();

        // As long as the thread is running, it should generate and render random positions to distract the player.
        while (!isReady)
        {
            yield return(new WaitUntil(() => isEvaluating || isReady));

            isEvaluating = false;

            RenderPosition(position);

            PlaySound(new[] { Sounds._1dch.Capture, Sounds._1dch.Check, Sounds._1dch.Opponent, Sounds._1dch.Self }.PickRandom());
        }

        Log("The position is {0}; {1} to play, mate in {2}. To beat Rustmate, the best sequence of moves are {3}.", position, color, (128 - Math.Abs(game.Evaluation)) / 2, ToLog(moves));

        MovesLeft = (128 - Math.Abs(game.Evaluation)) / 2;

        _isUsingThreads = false;

        PlaySound(Sounds._1dch.GameStart);

        ChangeText("Mate in", "", MovesLeft.ToString());
    }
示例#5
0
    private void OnInteract(int arg)
    {
        // This prevents you from making a move while the computer is thinking.
        if (!isReady)
        {
            return;
        }

        // This prevents you from selecting an empty space as the origin.
        if (position[arg] == Position.PieceChars[0] && last == null)
        {
            return;
        }

        // This prevents you from selecting a piece that isn't yours as the origin.
        if (position[arg].GetPieceColor() != color && last == null)
        {
            return;
        }

        // Gives button feedback.
        ButtonEffect(Buttons[arg], 1, Sounds._1dch.Click);

        // Highlight the selected square.
        BoardRenderers[arg].material.color = _colorScheme[2];

        // The destination is selected.
        if (last != null)
        {
            // The user did not deselect.
            if (last != arg)
            {
                bool isLegalMove = Engine.IsLegalMove(position, (sbyte)last, (sbyte)arg);

                // Updates the position on a legal move, cancels the selection otherwise.
                if (isLegalMove)
                {
                    // Creates the desired move.
                    var move = new CGameResult
                    {
                        Piece       = position[(int)last].Piece(),
                        Origin      = (sbyte)last,
                        Destination = (sbyte)arg
                    };

                    position = move.Move(position, this);

                    Log("You play {0}, the position is now {1}.", ToLog(move), position);

                    souvenirPositions.Add(ToLog(move));

                    MovesLeft--;
                    StartCoroutine(GetEngineMove());
                }

                PlaySound(isLegalMove ? Sounds._1dch.Self : Sounds._1dch.Illegal);
            }

            RenderPosition(position);
        }

        // Toggle _lastSelect between null and the argument passed in to the method.
        last = last == null ? (int?)arg : null;
    }