Exemple #1
0
        /// <summary> Returns a polyglot compatible
        ///     Zobrist hash of the current position.
        /// </summary>
        public static ulong GetHash(this PositionCore position)
        {
            var keys   = ZobristKeys;
            var result = 0UL;

            var cells = position.Cells;

            for (var i = 0; i < 64; i++)
            {
                var piece = cells[i + (i & ~7)];
                if (piece != 0)
                {
                    result ^= keys[64 * IndexOf(piece) + i];
                }
            }

            var ca = position.CastlingAvailability;

            if ((ca & Castlings.WK) != 0)
            {
                result ^= keys[768 + 0];
            }
            if ((ca & Castlings.WQ) != 0)
            {
                result ^= keys[768 + 1];
            }
            if ((ca & Castlings.BK) != 0)
            {
                result ^= keys[768 + 2];
            }
            if ((ca & Castlings.BQ) != 0)
            {
                result ^= keys[768 + 3];
            }

            if (position.EnPassant.HasValue)
            {
                // But only if theres actually a pawn ready to capture it.
                // Legality of the potential capture is irrelevant.
                var enpSquare = 0;
                switch (position.Turn)
                {
                case Color.White: enpSquare = 4 * 16; break;

                case Color.Black: enpSquare = 3 * 16; break;
                }
                enpSquare += position.EnPassant.Value;
                if (cells[enpSquare - 1] != 0 || cells[enpSquare + 1] != 0)
                {
                    result ^= keys[772 + position.EnPassant.Value];
                }
            }

            if (position.Turn == Color.White)
            {
                result ^= keys[780];
            }

            return(result);
        }
Exemple #2
0
 public Position(PositionCore core, int fiftyMovesClock, int moveNumber, GameStates properties, LegalMove move)
 {
     Core = core;
     FiftyMovesClock = fiftyMovesClock;
     MoveNumber = moveNumber;
     Properties = properties;
     Move = move;
 }
 public override void RefreshList()
 {
     base.RefreshList();
     using (DataManager = new PositionCore())
     {
         BindDataSource <IPositionModel>();
     }
 }
        protected override void Save()
        {
            base.Save();
            var positionModel = PopulateModelFromInterface();

            using (var facade = new PositionCore())
            {
                facade.Save(positionModel);
                ShowMessage(facade);
            }
        }
        protected override void DeleteRecord()
        {
            base.DeleteRecord();
            var id = Convert.ToInt32(recordId.Text);

            using (var facade = new PositionCore())
            {
                facade.Delete(id);
                ShowMessage(facade);
            }
        }
Exemple #6
0
 private void PopulatePosition()
 {
     using (var position = new PositionCore())
     {
         var source = position.Get <IPositionModel>();
         positionName.DisplayMember = "PositionName";
         positionName.ValueMember   = "Id";
         if (source != null)
         {
             positionName.DataSource = source.OrderBy(a => a.PositionName).ToList();
         }
     }
 }
        protected override void SaveUpdate()
        {
            base.SaveUpdate();
            var positionModel = PopulateModelFromInterface();

            positionModel.Id           = Convert.ToInt32(recordId.Text);
            positionModel.ModifiedBy   = modifiedBy.Text;
            positionModel.ModifiedDate = modifiedDate.Value;
            using (var facade = new PositionCore())
            {
                facade.Update(positionModel);
                ShowMessage(facade);
            }
        }
Exemple #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormDialogScriptLoad"/> class.
        /// </summary>
        public FormDialogScriptLoad()
        {
            // Add this form to be positioned..
            PositionForms.Add(this);

            // add positioning..
            PositionCore.Bind(ApplicationType.WinForms);

            InitializeComponent();

            DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation..

            if (Utils.ShouldLocalize() != null)
            {
                DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false);
                return; // After localization don't do anything more..
            }

            // initialize the language/localization database..
            DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages");

            // get the code snippets in the database..
            codeSnippets = ScriptNotepadDbContext.DbContext.CodeSnippets.ToArray();

            // localize the script type default names..
            defaultNameScriptTemplateText =
                DBLangEngine.GetMessage("msgDefaultScriptSnippetText", "A text script snippet|As in a script for manipulating Scintilla contents as text");

            defaultNameScriptTemplateLines =
                DBLangEngine.GetMessage("msgDefaultScriptSnippetLines", "A line script snippet|As in a script for manipulating Scintilla contents as lines");

            // localize the currently supported script types..
            cmbScriptType.Items.Clear();
            cmbScriptType.Items.Add(
                DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text")
                );

            cmbScriptType.Items.Add(
                DBLangEngine.GetMessage("msgScriptTypeLines", "Script lines|As in the C# script type should be handling the Scintilla's contents as lines")
                );

            cmbScriptType.SelectedIndex = 0;

            cmbScriptType.SelectedItem =
                DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text");

            // set the OK button's state based on the value if any script is selected from the script list box..
            btOK.Enabled = lbScriptList.SelectedIndex != -1;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="FormSearchResultTree"/> class.
        /// </summary>
        public FormSearchResultTree()
        {
            // Add this form to be positioned..
            PositionForms.Add(this);

            // add positioning..
            PositionCore.Bind(ApplicationType.WinForms);

            InitializeComponent();

            DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation..

            if (Utils.ShouldLocalize() != null)
            {
                DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false);
                return; // After localization don't do anything more..
            }

            // initialize the language/localization database..
            DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages");

            ttMain.SetToolTip(pnPreviousResult,
                              DBLangEngine.GetMessage("msgPreviousResult",
                                                      "Previous result|A tool-tip message describing that the button would go to the previous search result"));

            ttMain.SetToolTip(pnNextResult,
                              DBLangEngine.GetMessage("msgNextResult",
                                                      "Advance result|A tool-tip message describing that the button would go to the next search result"));

            ttMain.SetToolTip(pnClose,
                              DBLangEngine.GetMessage("msgButtonClose",
                                                      "Close|A message describing a tool-tip for a button which would close something"));

            // don't allow multiple instances of this..
            if (PreviousInstance != null)
            {
                if (PreviousInstance.IsDocked)
                {
                    RequestDockReleaseMainForm?.Invoke(PreviousInstance, new EventArgs());
                }
                else
                {
                    PreviousInstance?.Close();
                }
            }

            // save this as the new previous instance..
            PreviousInstance = this;
        }
Exemple #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormHexEdit"/> class.
        /// </summary>
        public FormHexEdit()
        {
            // Add this form to be positioned..
            PositionForms.Add(this, PositionCore.SizeChangeMode.MoveTopLeft);

            // add positioning..
            PositionCore.Bind(ApplicationType.WinForms);

            InitializeComponent();

            DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation..

            if (Utils.ShouldLocalize() != null)
            {
                DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false);
                return; // After localization don't do anything more..
            }

            hexEditor.ForegroundSecondColor = Brushes.Blue;
        }
 protected override void DataListView1BeforeSorting(object sender, BrightIdeasSoftware.BeforeSortingEventArgs e)
 {
     base.DataListView1BeforeSorting(sender, e);
     if (SortCounter != 0)
     {
         e.Canceled = true;
         return;
     }
     SortCounter++;
     if (e.ColumnToSort == null)
     {
         return;
     }
     SortColumn    = e.ColumnToSort.AspectName;
     SortDirection = GetSort(e.SortOrder);
     using (DataManager = new PositionCore())
     {
         BindDataSource <IPositionModel>();
     }
 }
Exemple #12
0
 private void PopulateInterfaceFromModel(int id)
 {
     using (var facade = new PositionCore())
     {
         var positionModel = facade.Get <IPositionModel>(WhereTerm.DefaultParam(id, "ID")).FirstOrDefault();
         if (positionModel == null || !facade.IsSuccess)
         {
             MsgHelpers.ShowError(this, string.IsNullOrEmpty(facade.Message) ? "Employee Position not found" : facade.Message);
             return;
         }
         createdBy.Text     = positionModel.CreatedBy;
         createdDate.Value  = positionModel.CreatedDate;
         recordId.Text      = positionModel.Id.ToString();
         positionName.Text  = positionModel.PositionName;
         createdBy.Text     = positionModel.CreatedBy;
         createdDate.Value  = positionModel.CreatedDate;
         modifiedBy.Text    = positionModel.ModifiedBy;
         modifiedDate.Value = positionModel.ModifiedDate.HasValue ? positionModel.ModifiedDate.Value : DateTime.Now;
     }
 }
Exemple #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormFileDiffView"/> class.
        /// </summary>
        public FormFileDiffView()
        {
            // Add this form to be positioned..
            PositionForms.Add(this);

            // add positioning..
            PositionCore.Bind(ApplicationType.WinForms);

            InitializeComponent();

            DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation..

            if (Utils.ShouldLocalize() != null)
            {
                DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false);
                return; // After localization don't do anything more..
            }

            // initialize the language/localization database..
            DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages");

            ThisInstance = this;
        }
Exemple #14
0
 public static bool IsSquareAttackedBySide(this PositionCore core, Color side, int square)
 {
     return(side == Color.White
         ? IsSquareAttackedByWhite(core.Cells, square)
         : IsSquareAttackedByBlack(core.Cells, square));
 }
Exemple #15
0
        public static AnalyzedMove Validate(this Position source, Move move)
        {
            var whiteKingSquare = source.Core.WhiteKing;
            var blackKingSquare = source.Core.BlackKing;

            var sourceCells = source.Core.Cells;
            var cells       = source.Core.GetCopyOfCells();

            MoveAnnotations notes;
            // Piece in the from cell?
            var moveFrom = move.FromCell;
            var piece    = (Piece)sourceCells[moveFrom];

            if (piece == Piece.EmptyCell)
            {
                notes = EmptyCell;
                return(new IllegalMove(move, source, notes));
            }

            // Side to move?
            var color = piece.Color();

            if (color != source.Core.Turn)
            {
                notes = (MoveAnnotations)piece.PieceType() | WrongSideToMove;
                return(new IllegalMove(move, source, notes));
            }

            // Move to occupied cell?
            var moveTo  = move.ToCell;
            var toPiece = (Piece)sourceCells[moveTo];

            if (toPiece != Piece.EmptyCell && toPiece.Color() == color)
            {
                notes = (MoveAnnotations)piece.PieceType() | ToOccupiedCell;
                return(new IllegalMove(move, source, notes));
            }
            notes = ValidateMove(cells, piece,
                                 moveFrom, moveTo, toPiece, source.Core.CastlingAvailability);
            if (toPiece != Piece.EmptyCell)
            {
                notes |= Capture;
            }
            // ---------------- SetupBoard ---------------------
            if ((notes & AllErrors) != 0)
            {
                return(new IllegalMove(move, source, notes));
            }
            if ((notes & EnPassant) != 0)
            {
                if (source.Core.EnPassant != moveTo % 16)
                {
                    notes |= HasNoEnPassant;
                    return(new IllegalMove(move, source, notes));
                }
            }
            else if ((notes & Promotion) != 0)
            {
                var proposedPromotion = move.PromoteTo;
                if (move.PromoteTo == PieceType.None)
                {
                    notes            |= MissingPromotionHint;
                    proposedPromotion = PieceType.Queen;
                }
                piece = proposedPromotion.With(color);
            }
            else if (move.PromoteTo != PieceType.None)
            {
                notes |= PromotionHintIsNotNeeded;
            }

            cells[moveTo] = (byte)piece;

            switch (piece)
            {
            case Piece.WhiteKing:
                whiteKingSquare = moveTo;
                break;

            case Piece.BlackKing:
                blackKingSquare = moveTo;
                break;
            }

            cells[moveFrom] = 0;
            var enPassantFile = new int?();

            if ((notes & (DoublePush | EnPassant | AllCastlings)) != 0)
            {
                if ((notes & DoublePush) != 0)
                {
                    enPassantFile = moveFrom % 16;
                }
                else if ((notes & EnPassant) != 0)
                {
                    cells[moveTo + (color == Color.White ? -16 : +16)] = 0;
                }
                else
                {
                    switch (notes)
                    {
                    case (King | WK):
                        cells[S.H1] = (byte)Piece.EmptyCell;
                        cells[S.F1] = (byte)Piece.WhiteRook;
                        break;

                    case (King | WQ):
                        cells[S.A1] = (byte)Piece.EmptyCell;
                        cells[S.D1] = (byte)Piece.WhiteRook;
                        break;

                    case (King | BK):
                        cells[S.H8] = (byte)Piece.EmptyCell;
                        cells[S.F8] = (byte)Piece.BlackRook;
                        break;

                    case (King | BQ):
                        cells[S.A8] = (byte)Piece.EmptyCell;
                        cells[S.D8] = (byte)Piece.BlackRook;
                        break;
                    }
                }
            }
            var isUnderCheck = source.Core.Turn == Color.White
                ? cells.IsSquareAttackedByBlack(whiteKingSquare)
                : cells.IsSquareAttackedByWhite(blackKingSquare);

            if (isUnderCheck)
            {
                notes |= MoveToCheck;
            }
            var castlings = source.Core.CastlingAvailability
                            & ~KilledAvailability(moveTo)
                            & ~KilledAvailability(moveFrom);

            // ---------------- ---------- ---------------------
            if ((notes & AllErrors) != 0)
            {
                return(new IllegalMove(move, source, notes));
            }

            var positionCore = new PositionCore(
                cells, color.Invert(), castlings, enPassantFile,
                whiteKingSquare, blackKingSquare);
            var legalMove = new LegalMove(
                move, source, positionCore, notes);

            return(legalMove);
        }
Exemple #16
0
    static void Main()
    {
        string[] args = Environment.GetCommandLineArgs();

        // not obsolete for the migration to the new settings..
#pragma warning disable 618
        SettingsOld.FromOldSettings(Settings);
#pragma warning restore 618

        Settings.Load(Settings.SettingFileName);

        // wait for the possible install process to finnish..
        VPKSoft.WaitForProcessUtil.WaitForProcess.WaitForProcessArguments(args, 30);

        foreach (var arg in args)
        {
            if (arg.StartsWith("--restoreBackup"))
            {
                var restoreParameters = arg.Split('=');
                if (restoreParameters.Length == 2)
                {
                    if (File.Exists(restoreParameters[1]))
                    {
                        while (AppRunning.CheckIfRunningNoAdd("VPKSoft.amp.sharp#"))
                        {
                            Thread.Sleep(100);
                        }

                        try
                        {
                            using (ZipFile zip = ZipFile.Read(restoreParameters[1]))
                            {
                                zip.ExtractAll(Paths.GetAppSettingsFolder(Misc.AppType.Winforms),
                                               ExtractExistingFileAction.OverwriteSilently);
                            }
                        }
                        catch (Exception ex)
                        {
                            // log the exception..
                            ExceptionLogger.LogError(ex);
                        }
                    }
                }
            }
        }


        Process localizeProcess = Utils.CreateDBLocalizeProcess(Paths.AppInstallDir);
        // localizeProcess..

        if (localizeProcess != null)
        {
            localizeProcess.Start();
            return;
        }

        if (!Debugger.IsAttached)
        {
            ExceptionLogger.Bind(); // bind before any visual objects are created
        }

        ExceptionLogger.ApplicationCrashData += ExceptionLogger_ApplicationCrashData;


        // Save languages
        if (Utils.ShouldLocalize() != null)
        {
            // ReSharper disable once ObjectCreationAsStatement
            new FormMain();
            // ReSharper disable once ObjectCreationAsStatement
            new FormPsycho();
            // ReSharper disable once ObjectCreationAsStatement
            new FormProgressBackground();
            // ReSharper disable once ObjectCreationAsStatement
            new FormAddAlbum();
            // ReSharper disable once ObjectCreationAsStatement
            new FormRename();
            // ReSharper disable once ObjectCreationAsStatement
            new FormQueueSnapshotName();        // 16.10.17
            // ReSharper disable once ObjectCreationAsStatement
            new FormSavedQueues();              // 18.10.17
            // ReSharper disable once ObjectCreationAsStatement
            new FormModifySavedQueue();         // 19.10.17
            // ReSharper disable once ObjectCreationAsStatement
            new FormSettings();                 // 21.10.17
            // ReSharper disable once ObjectCreationAsStatement
            new FormTagInfo();                  // 11.02.18
            // ReSharper disable once ObjectCreationAsStatement
            new FormAlbumNaming();              // 27.10.18
            // ReSharper disable once ObjectCreationAsStatement
            new FormDatabaseUpdatingProgress(); // 27.10.18
            // ReSharper disable once ObjectCreationAsStatement
            new FormHelp();                     // 28.10.18
            // ReSharper disable once ObjectCreationAsStatement
            new FormRandomizePriority();        // 30.10.18
            // ReSharper disable once ObjectCreationAsStatement
            new FormDatabaseMigrate();          // 01.09.19
            // ReSharper disable once ObjectCreationAsStatement
            new FormThemeSettings();

            ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData;
            ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully
            return;
        }
        // End save languages

#pragma warning disable 618
        // required for history reasons..
        if (Settings.DbUpdateRequiredLevel < 1)
#pragma warning restore 618
        {
            if (AppRunning.CheckIfRunningNoAdd("VPKSoft.amp.DBUpdate.sharp#"))
            {
                ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData;
                ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully
                return;
            }
            DBLangEngine.UseCulture = Settings.Culture; // set the localization value..
            Application.Run(new FormDatabaseUpdatingProgress());
            ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData;
            ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully
#pragma warning disable 618
            // required for history reasons..
            Settings.DbUpdateRequiredLevel = 1;
#pragma warning restore 618
            Process.Start(new ProcessStartInfo(Path.Combine(Paths.AppInstallDir, "amp.exe"))); // the database is updated..
            return;
        }

        if (AppRunning.CheckIfRunningNoAdd("VPKSoft.amp.sharp#"))
        {
            ExceptionLogger.LogMessage($"Application is running. Checking for open file requests. The current directory is: '{Environment.CurrentDirectory}'.");
            try
            {
                RpcSelfClient <string> ipcClient = new RpcSelfClient <string>(50671);

                // only send the existing files to the running instance, don't send the executable
                // file name thus the start from 1..
                for (int i = 1; i < args.Length; i++)
                {
                    string file = args[i];

                    ExceptionLogger.LogMessage($"Request file open: '{file}'.");
                    bool exists;

                    if ((exists = File.Exists(file)) ||
                        file == ArgumentNext ||
                        file == ArgumentPrevious ||
                        file == ArgumentPlayPause)
                    {
                        if (exists)
                        {
                            ExceptionLogger.LogMessage($"File exists: '{file}'. Send open request.");
                        }
                        else
                        {
                            file = file.TrimStart('-');
                            file = file[0].ToString().ToUpperInvariant() + file.Substring(1);
                            ExceptionLogger.LogMessage($"Send playback request: '{file}'.");
                        }

                        ipcClient.SendData(file);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogger.LogError(ex);
                // just in case something fails with the IPC communication..
            }
            ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData;
            ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully..
            return;
        }

        AppRunning.CheckIfRunning("VPKSoft.amp.sharp#");

        // create an IPC server at localhost, the port was randomized in the development phase..
        IpcServer = new RpcSelfHost <string>(50671);

        // subscribe to the IPC event if the application receives a message from another instance of this application..
        IpcServer.MessageReceived += MessageReceived;

        PositionCore.Bind(ApplicationType.WinForms); // attach the PosLib to the application
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        DBLangEngine.UseCulture = Settings.Culture;    // set the localization value..
        Application.Run(new FormMain());
        FormHelp.DisposeSingleton();                   // release the help form if any..
        PositionCore.UnBind(ApplicationType.WinForms); // release the event handlers used by the PosLib and save the default data

        // unsubscribe the IpcClientServer MessageReceived event handler..
        IpcServer.MessageReceived -= MessageReceived;
        IpcServer.Dispose();

        ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData;
        ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully
        AppRunning.DisposeMutexByName("VPKSoft.amp.sharp#");

        // run a possible software (as of the time of the writing the software is this one.)..
        if (File.Exists(RunProgramOnExit))
        {
            Process.Start(RunProgramOnExit, RunProgramOnExitArguments);
        }
        else if (FormMain.RestartRequired)
        {
            Process.Start(Application.ExecutablePath);
        }
    }
Exemple #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormScript"/> class.
        /// </summary>
        public FormScript()
        {
            // Add this form to be positioned..
            PositionForms.Add(this);

            // add positioning..
            PositionCore.Bind(ApplicationType.WinForms);

            InitializeComponent();

            DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation..

            if (Utils.ShouldLocalize() != null)
            {
                DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false);
                return; // After localization don't do anything more..
            }

            suspendChangedEvent = true; // suspend the event handler as the contents of the script is about to change..

            // initialize the language/localization database..
            DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages");

            // localize the script type default names..
            defaultNameScriptTemplateText =
                DBLangEngine.GetMessage("msgDefaultScriptSnippetText", "A text script snippet|As in a script for manipulating Scintilla contents as text");

            defaultNameScriptTemplateLines =
                DBLangEngine.GetMessage("msgDefaultScriptSnippetLines", "A line script snippet|As in a script for manipulating Scintilla contents as lines");

            // localize the currently supported script types..
            tsbComboScriptType.Items.Clear();
            tsbComboScriptType.Items.Add(
                DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text")
                );

            tsbComboScriptType.Items.Add(
                DBLangEngine.GetMessage("msgScriptTypeLines", "Script lines|As in the C# script type should be handling the Scintilla's contents as lines")
                );

            tsbComboScriptType.SelectedItem =
                DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text");

            // set the default script for manipulating text..
            scintillaScript.Text = scriptRunnerText.CSharpScriptBase;

            // set the text for the default script snippet..
            tstScriptName.Text = defaultNameScriptTemplateText;

            CreateNewCodeSnippet(); // create a new CODE_SNIPPETS class instance..

            // set the lexer as C#..
            ScintillaLexers.CreateLexer(scintillaScript, LexerType.Cs);

            // highlight the braces..
            SetBraceHighlights();

            suspendChangedEvent = false; // "resume" the event handler..

            // track the instances of this form so the changes can be delegated to each other..
            FormScriptInstances.Add(this);
        }
Exemple #18
0
        public static AnalyzedMove Validate(this Position source, Move move)
        {
            var whiteKingSquare = source.Core.WhiteKing;
            var blackKingSquare = source.Core.BlackKing;

            var sourceCells = source.Core.Cells;
            var cells = source.Core.GetCopyOfCells();

            MoveAnnotations notes;
            // Piece in the from cell?
            var moveFrom = move.FromCell;
            var piece = (Piece)sourceCells[moveFrom];
            if (piece == Piece.EmptyCell)
            {
                notes = EmptyCell;
                return new IllegalMove(move, source, notes);
            }

            // Side to move?
            var color = piece.Color();
            if (color != source.Core.Turn)
            {
                notes = (MoveAnnotations)piece.PieceType() | WrongSideToMove;
                return new IllegalMove(move, source, notes);
            }

            // Move to occupied cell?
            var moveTo = move.ToCell;
            var toPiece = (Piece)sourceCells[moveTo];
            if (toPiece != Piece.EmptyCell && toPiece.Color() == color)
            {
                notes = (MoveAnnotations)piece.PieceType() | ToOccupiedCell;
                return new IllegalMove(move, source, notes);
            }
            notes = ValidateMove(cells, piece,
                moveFrom, moveTo, toPiece, source.Core.CastlingAvailability);
            if (toPiece != Piece.EmptyCell) notes |= Capture;
            // ---------------- SetupBoard ---------------------
            if ((notes & AllErrors) != 0)
                return new IllegalMove(move, source, notes);
            if ((notes & EnPassant) != 0)
            {
                if (source.Core.EnPassant != moveTo % 16)
                {
                    notes |= HasNoEnPassant;
                    return new IllegalMove(move, source, notes);
                }
            }
            else if ((notes & Promotion) != 0)
            {
                var proposedPromotion = move.PromoteTo;
                if (move.PromoteTo == PieceType.None)
                {
                    notes |= MissingPromotionHint;
                    proposedPromotion = PieceType.Queen;
                }
                piece = proposedPromotion.With(color);
            }
            else if (move.PromoteTo != PieceType.None)
            {
                notes |= PromotionHintIsNotNeeded;
            }

            cells[moveTo] = (byte)piece;

            switch (piece)
            {
                case Piece.WhiteKing:
                    whiteKingSquare = moveTo;
                    break;
                case Piece.BlackKing:
                    blackKingSquare = moveTo;
                    break;
            }

            cells[moveFrom] = 0;
            var enPassantFile = new int?();
            if ((notes & (DoublePush | EnPassant | AllCastlings)) != 0)
            {
                if ((notes & DoublePush) != 0)
                {
                    enPassantFile = moveFrom % 16;
                }
                else if ((notes & EnPassant) != 0)
                {
                    cells[moveTo + (color == Color.White ? -16 : +16)] = 0;
                }
                else
                    switch (notes)
                    {
                        case (King | WK):
                            cells[S.H1] = (byte)Piece.EmptyCell;
                            cells[S.F1] = (byte)Piece.WhiteRook;
                            break;
                        case (King | WQ):
                            cells[S.A1] = (byte)Piece.EmptyCell;
                            cells[S.D1] = (byte)Piece.WhiteRook;
                            break;
                        case (King | BK):
                            cells[S.H8] = (byte)Piece.EmptyCell;
                            cells[S.F8] = (byte)Piece.BlackRook;
                            break;
                        case (King | BQ):
                            cells[S.A8] = (byte)Piece.EmptyCell;
                            cells[S.D8] = (byte)Piece.BlackRook;
                            break;
                    }
            }
            var isUnderCheck = source.Core.Turn == Color.White
                ? cells.IsSquareAttackedByBlack(whiteKingSquare)
                : cells.IsSquareAttackedByWhite(blackKingSquare);

            if (isUnderCheck)
            {
                notes |= MoveToCheck;
            }
            var castlings = source.Core.CastlingAvailability
                            & ~KilledAvailability(moveTo)
                            & ~KilledAvailability(moveFrom);

            // ---------------- ---------- ---------------------
            if ((notes & AllErrors) != 0)
                return new IllegalMove(move, source, notes);

            var positionCore = new PositionCore(
                cells, color.Invert(), castlings, enPassantFile,
                whiteKingSquare, blackKingSquare);
            var legalMove = new LegalMove(
                move, source, positionCore, notes);
            return legalMove;
        }
Exemple #19
0
 public static bool IsInCheck(this PositionCore core, Color side)
 {
     return(side == Color.White
         ? IsSquareAttackedByBlack(core.Cells, core.WhiteKing)
         : IsSquareAttackedByWhite(core.Cells, core.BlackKing));
 }
Exemple #20
0
 internal LegalMove(Move move, Position originalPosition,
     PositionCore resultPosition, MoveAnnotations annotations)
     : base(annotations, originalPosition, move)
 {
     ResultPosition = resultPosition;
 }