Example #1
0
        private static void CheckContent(CheckInfo c, BcfSource source, string version, List <string> contents, string filter)
        {
            var markupFiles = source.GetLocalNames(filter);

            foreach (var markupFile in markupFiles)
            {
                var locP           = Path.GetDirectoryName(markupFile);
                var validatingFile = c.CleanName(new FileInfo(Path.Combine(source.FullName, markupFile)));
                var docNav         = new XPathDocument(source.GetStream(markupFile));
                var nav            = docNav.CreateNavigator();
                foreach (var content in contents)
                {
                    var iterator1 = nav.Select(content);
                    while (iterator1.MoveNext())
                    {
                        string loc = "";
                        if (iterator1.Current is IXmlLineInfo li)
                        {
                            loc = $", Line: {li.LinePosition}, Position: {li.LinePosition}";
                        }
                        var name       = iterator1.Current.Value;
                        var mappedName = Path.Combine(locP, name);
                        if (source.GetLocalNames(mappedName).Count() != 1)
                        {
                            Console.WriteLine($"CONTENT ERROR\t{validatingFile}\tMissing {mappedName}{loc}.");
                            c.Status |= Status.ContentError;
                        }
                    }
                }
            }
        }
            private void RefreshCheckInfoStatus()
            {
                if (!m_VersionListReady || !m_ReadOnlyListReady || !m_ReadWriteListReady)
                {
                    return;
                }

                int  removedCount         = 0;
                int  updateCount          = 0;
                long updateTotalLength    = 0L;
                long updateTotalZipLength = 0L;

                foreach (KeyValuePair <ResourceName, CheckInfo> checkInfo in m_CheckInfos)
                {
                    CheckInfo ci = checkInfo.Value;
                    ci.RefreshStatus(m_CurrentVariant);

                    if (ci.Status == CheckInfo.CheckStatus.StorageInReadOnly)
                    {
                        ProcessResourceInfo(ci.ResourceName, ci.LoadType, ci.Length, ci.HashCode, true);
                    }
                    else if (ci.Status == CheckInfo.CheckStatus.StorageInReadWrite)
                    {
                        ProcessResourceInfo(ci.ResourceName, ci.LoadType, ci.Length, ci.HashCode, false);
                    }
                    else if (ci.Status == CheckInfo.CheckStatus.NeedUpdate)
                    {
                        updateCount++;
                        updateTotalLength    += ci.Length;
                        updateTotalZipLength += ci.ZipLength;

                        ResourceNeedUpdate(ci.ResourceName, ci.LoadType, ci.Length, ci.HashCode, ci.ZipLength, ci.ZipHashCode);
                    }
                    else if (ci.Status == CheckInfo.CheckStatus.Disuse || ci.Status == CheckInfo.CheckStatus.Unavailable)
                    {
                        // Do nothing.
                    }
                    else
                    {
                        throw new GameFrameworkException(Utility.Text.Format("Check resources '{0}' error with unknown status.", ci.ResourceName.FullName));
                    }

                    if (ci.NeedRemove)
                    {
                        removedCount++;

                        string path = Utility.Path.GetCombinePath(m_ResourceManager.m_ReadWritePath, Utility.Path.GetResourceNameWithSuffix(ci.ResourceName.FullName));
                        File.Delete(path);

                        if (!m_ResourceManager.m_ReadWriteResourceInfos.ContainsKey(ci.ResourceName))
                        {
                            throw new GameFrameworkException(Utility.Text.Format("Resource '{0}' is not exist in read-write list.", ci.ResourceName.FullName));
                        }

                        m_ResourceManager.m_ReadWriteResourceInfos.Remove(ci.ResourceName);
                    }
                }

                ResourceCheckComplete(removedCount, updateCount, updateTotalLength, updateTotalZipLength);
            }
Example #3
0
        /// <summary>
        /// 保存检查对象
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel SaveCheckInfo(CheckInfo info)
        {
            try
            {
                info.Id             = Guid.NewGuid();
                info.CreateTime     = DateTime.Now;
                info.DistributeTime = DateTime.MinValue;
                info.DealTime       = DateTime.MinValue;
                info.Status         = 0;

                _context.CheckInfoes.Add(info);
                info.CheckItems.ForEach(x =>
                {
                    x.CheckInfoId = info.Id;
                    x.Id          = Guid.NewGuid();
                    x.Pics.ForEach(c =>
                    {
                        c.Id          = Guid.NewGuid();
                        c.CheckItemId = x.Id;
                    });
                    _context.PicInfoes.AddRange(x.Pics);
                });
                _context.CheckItems.AddRange(info.CheckItems);

                _response.Stutas = _context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                LogsHelper.WriteErrorLog(ex, "保存检查对象");
                _response.Msg = ex.Message;
            }
            return(_response);
        }
Example #4
0
 internal static void init()
 {
     for (int i = 0; i < Constants.BROKER_SLOTS; i++)
     {
         _pool[i] = new CheckInfo[0];
     }
 }
Example #5
0
    internal static ExtMoveArrayWrapper make_promotions(
        GenType Type,
        SquareT Delta,
        ExtMoveArrayWrapper moveList,
        SquareT to,
        CheckInfo ci)
    {
        if (Type == GenType.CAPTURES || Type == GenType.EVASIONS || Type == GenType.NON_EVASIONS)
        {
            (moveList).Add(Move.make(MoveType.PROMOTION, to - Delta, to, PieceType.QUEEN));
        }

        if (Type == GenType.QUIETS || Type == GenType.EVASIONS || Type == GenType.NON_EVASIONS)
        {
            (moveList).Add(Move.make(MoveType.PROMOTION, to - Delta, to, PieceType.ROOK));

            (moveList).Add(Move.make(MoveType.PROMOTION, to - Delta, to, PieceType.BISHOP));

            (moveList).Add(Move.make(MoveType.PROMOTION, to - Delta, to, PieceType.KNIGHT));
        }

        // Knight promotion is the only promotion that can give a direct check
        // that's not already included in the queen promotion.
        if (Type == GenType.QUIET_CHECKS && Bitboard.AndWithSquare(Utils.StepAttacksBB[Piece.W_KNIGHT, to], ci.ksq)!=0)
        {
            (moveList).Add(Move.make(MoveType.PROMOTION, to - Delta, to, PieceType.KNIGHT));
        }

        return moveList;
    }
Example #6
0
        /// generate<QUIET_CHECKS> generates all pseudo-legal non-captures and knight
        /// underpromotions that give check. Returns a pointer to the end of the move list.
        public static int generate_quiet_checks(Position pos, ExtMove[] mlist, int mPos)
        {
            Debug.Assert(0 == pos.checkers());

            Color     us = pos.side_to_move();
            CheckInfo ci = new CheckInfo(pos);
            Bitboard  dc = ci.dcCandidates;

            while (dc != 0)
            {
                Square    from = BitBoard.pop_lsb(ref dc);
                PieceType pt   = Types.type_of_piece(pos.piece_on(from));

                if (pt == PieceTypeS.PAWN)
                {
                    continue; // Will be generated togheter with direct checks
                }
                Bitboard b = pos.attacks_from_piece_square((Piece)pt, from) & ~pos.pieces();

                if (pt == PieceTypeS.KING)
                {
                    b &= ~BitBoard.PseudoAttacks[PieceTypeS.QUEEN][ci.ksq];
                }

                while (b != 0)
                {
                    mlist[mPos++].move = Types.make_move(from, BitBoard.pop_lsb(ref b));
                }
            }

            return(us == ColorS.WHITE ? generate_all(pos, mlist, mPos, ~pos.pieces(), ColorS.WHITE, GenTypeS.QUIET_CHECKS, ci) :
                   generate_all(pos, mlist, mPos, ~pos.pieces(), ColorS.BLACK, GenTypeS.QUIET_CHECKS, ci));
        }
Example #7
0
        private void FrmCheck_Load(object sender, EventArgs e)
        {
            this.BindData();
            this.LoadState();
            Task task = new Task(delegate
            {
                CheckInfo msg = new CheckInfo
                {
                    BeginTime = this._time,
                    UserName  = LoginInfo.UserName,
                    State     = 1
                };
                SocketInfo sI = new SocketInfo
                {
                    Type = SocketInfoType.BeginCheck,
                    Name = LoginInfo.UserName,
                    Time = DateTime.Now,
                    Msg  = msg
                };
                int num = 3;
                do
                {
                    num--;
                }while (!TcpClient.SendMessage(sI) && num > 0);
                if (num == 0)
                {
                    MessageBox.Show("与服务器断开连接,加载答题失败");
                }
            });

            task.Start();
        }
Example #8
0
        private void DoneCheck()
        {
            if (!Common.Common_Func.CheckDgvOper(dgvList))
            {
                return;
            }
            CheckInfo check = GetListRowModel(dgvList.CurrentCell.RowIndex);

            if (check == null)
            {
                return;
            }
            switch (check.CheckStatus)
            {
            case 3:
                Common.Common_Func.ErrorMessage("该盘点单已经取消盘点", "操作失败", 2);
                return;

            case 4:
                Common.Common_Func.ErrorMessage("该盘点单已经完成盘点", "操作失败", 2);
                return;

            case 5:
                Common.Common_Func.ErrorMessage("该盘点单已经盈亏处理", "操作失败", 2);
                return;
            }

            if (!Common.Common_Func.DialogMessage(string.Format("是否确认完成盘点【{0}】?", check.CheckNo), "确认完成"))
            {
                return;
            }

            check.CheckStatus = 4;
            UpdateCheckStatus(check);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="checkInfo"></param>
        /// <returns></returns>
        public static DbContextSqlQueryCommand Select(CheckInfo checkInfo)
        {
            string TsqlStr = string.Empty;

            //select * from PaasOLT_OrderCarClean order by Id offset((2 - 1) * 20) rows fetch next 20 rows only;
            //查询
            TsqlStr = "select * from " + checkInfo.tableName + " ";
            if (checkInfo.tableType == 0)
            {
                TsqlStr = "select *,(select TrueName from SysUser where ObjectId = " + checkInfo.tableName + ".CreateUserName) as CreateUserNameStr,(select TrueName from SysUser where ObjectId = " + checkInfo.tableName + ".ModificationUserName) as ModificationUserNameStr from " + checkInfo.tableName + " ";
            }
            //条件
            string strWhere = string.IsNullOrEmpty(checkInfo.strWhere) ? null : " where " + checkInfo.strWhere;
            //排序
            string orderByStr = " order by " + checkInfo.orderByStr.Substring(1);
            //分页和排序
            string pageRecordStr = string.Empty;

            if (checkInfo.pageNum != 0)
            {
                pageRecordStr = " offset((" + checkInfo.pageNum + " - 1) * " + checkInfo.recordNum + ") rows fetch next " + checkInfo.recordNum + " rows only ";
            }
            //序列化json
            string forJsonStr = checkInfo.jsonFlag ? " for json path,INCLUDE_NULL_VALUES " : string.Empty;
            //创建返回
            DbContextSqlQueryCommand dbContextSqlQueryCommand = new DbContextSqlQueryCommand();

            dbContextSqlQueryCommand.QueryType = "text";
            //返回
            dbContextSqlQueryCommand.Query = TsqlStr + strWhere + orderByStr + pageRecordStr + forJsonStr;
            return(dbContextSqlQueryCommand);
        }
Example #10
0
        /// <summary>
        /// Gets the list of checks for given target servers or databases.
        /// </summary>
        /// <param name="target">
        /// A sequence of target servers or databases.
        /// </param>
        /// <returns>
        /// Returns an <see cref="IEnumerable{SqlObjectLocator}"/>
        /// containing checks available for given <paramref name="target"/>.
        /// </returns>
        internal Task <List <CheckInfo> > GetAssessmentItems(SqlObjectLocator target)
        {
            var result = new List <CheckInfo>();

            var resultsList = Engine.GetChecks(target).ToList();

            Logger.Write(TraceEventType.Verbose, $"SQL Assessment: got {resultsList.Count} items.");

            foreach (var r in resultsList)
            {
                var targetName = target.Type != SqlObjectType.Server
                                     ? $"{target.ServerName}:{target.Name}"
                                     : target.Name;

                var item = new CheckInfo()
                {
                    CheckId        = r.Id,
                    Description    = r.Description,
                    DisplayName    = r.DisplayName,
                    HelpLink       = r.HelpLink,
                    Level          = r.Level.ToString(),
                    TargetName     = targetName,
                    Tags           = r.Tags.ToArray(),
                    TargetType     = target.Type,
                    RulesetName    = Engine.Configuration.DefaultRuleset.Name,
                    RulesetVersion = Engine.Configuration.DefaultRuleset.Version.ToString()
                };

                result.Add(item);
            }

            return(Task.FromResult(result));
        }
Example #11
0
                /// <summary>
                /// 檢查 XmlDocument 是否為錯誤訊息
                /// </summary>
                /// <param name="XmlDoc"></param>
                /// <returns></returns>
                public CheckInfo IsError(XmlDocument XmlDoc)
                {
                    CheckInfo info = new CheckInfo();

                    try
                    {
                        XmlNodeList xmlNodeList = XmlDoc.SelectNodes("Return");

                        if (xmlNodeList.Count == 0)
                        {
                            info.Check = true; info.Message = string.Empty;
                        }
                        else
                        {
                            info.ReturnCode = xmlNodeList.Item(0).Attributes["ReCode"].Value.Trim();

                            info.Check = info.ReturnCode == "0000";

                            if (!info.Check)
                            {
                                info.Message = xmlNodeList.Item(0).Attributes["ErrMsg"].Value.Trim();
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        info.Check = false;

                        info.Message = ex.Message;
                    }
                    return(info);
                }
Example #12
0
        public FrmCheckAnalyse()
        {
            InitializeComponent();

            Common.Common_Func.DelDataGridViewSortable(dgvList);
            this._check = new CheckInfo();
        }
Example #13
0
 public FrmCheckAnalyse(CheckInfo check)
 {
     InitializeComponent();
     Common.Common_Func.DelDataGridViewSortable(dgvList);
     // TODO: Complete member initialization
     this._check = check;
 }
Example #14
0
        private static Status ProcessSingleFile(FileInfo zippedFileInfo, CheckInfo c)
        {
            Status ret = Status.Ok;

            ret |= CheckSchemaCompliance(c, zippedFileInfo);
            return(ret);
        }
Example #15
0
    public CheckInfo SelectByID(int checkID)
    {
        CheckDataProvider objCon       = new CheckDataProvider();
        CheckInfo         objCheckInfo = objCon.SelectByID(checkID);

        return(objCheckInfo);
    }
Example #16
0
        //Setup BankDraft/Check Autopay --Autopay Update
        public static PaymentResponse SetupACHAutoPay(CheckInfo chkRequest)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var resp = new PaymentResponse();

            try
            {
                if (chkRequest.CustomerNumber != null && chkRequest.CustomerNumber != string.Empty)
                {
                    resp = ManageACHPaymentProfile(chkRequest);
                }
                else
                {
                    resp.ResultCode    = -1;
                    resp.ResultMessage = "Invalid Request";
                }
                return(resp);
            }
            catch (Exception ex)
            {
                resp.ResultCode    = -3; //Exception
                resp.ResultMessage = ex.Message;
                InsertClientErrorLog(chkRequest.CustomerNumber, "", chkRequest.Source, ex, "Common_SetupACHAutoPay");
                return(resp);
            }
        }
Example #17
0
        public EditFreq(CheckInfo src)
        {
            Result = null;
            tmp    = src;
            InitializeComponent();

            checkBoxes = new List <CheckBox>();
            for (int i = 0; Frequency.ToString((Freqs)i) != ""; i++)
            {
                checkBoxes.Add(new CheckBox()
                {
                    Content = Frequency.ToString((Freqs)i)
                });
                Grid.SetRow(checkBoxes.Last(), i / 2);
                Grid.SetColumn(checkBoxes.Last(), i % 2);
                GdFreqs.Children.Add(checkBoxes.Last());
            }

            var fqs = Frequency.Split(src.Data);

            for (int i = 0; i < checkBoxes.Count / 2 + (checkBoxes.Count % 2); i++)
            {
                GdFreqs.RowDefinitions.Add(new RowDefinition());
            }

            foreach (var f in fqs)
            {
                checkBoxes[(int)f].IsChecked = true;
            }
        }
Example #18
0
        public void MakeMove(PieceMove move)
        {
            ChessColor oppositeColor = move.piece.color == ChessColor.White ? ChessColor.Black : ChessColor.White;
            Piece      piece         = move.piece;

            if (piece.color != turn)
            {
                return;
            }
            if (move.moveType == MoveType.Evolve)
            {
                ApplyMove(move);
                PieceEvolve?.Invoke(move.newPos, piece.color);
                //send a evolve event and ask for the piece to evolve
            }
            else if (move.moveType == MoveType.Switch)
            {
                //switch with king
            }
            else if (move.moveType == MoveType.Eat)
            {
                Piece deadPiece = chessBoard.Board[move.newPos.row, move.newPos.column];
                chessBoard.AddToGrave(deadPiece);
                PieceEaten?.Invoke(move.newPos);
                ApplyMove(move);
            }
            else if (move.moveType == MoveType.Normal)
            {
                ApplyMove(move);
            }
            check = IsCheckMate(move.newPos);
            ChangeTurn();
            CheckGame();
        }
Example #19
0
        public static bool CheckInfoOp(CheckInfo objinfo, string OpType)
        {
            string sqlString = "";

            if (OpType == "Insert")
            {
                sqlString = string.Concat(new object[] {
                    "Insert into Prj_ItemInspect(PrjCode,ExamineUnit,AcceptCheckUnit,AcceptCheckContent,AcceptCheckGist,AcceptCheckSort,AcceptCheckAnswerForPerson,AcceptCheckDate,AcceptCheckResult,CompleteApplyContent,Remark,Flags,requestfinishtime,planfinishtime,factfinishtime,factresult,prjplan,CheckResult,CertifiResult,checkResults,filesType,mark,rectifyMarkID) values('", objinfo.PrjCode, "','", objinfo.ExamineUnit, "','", objinfo.AcceptCheckUnit, "','", objinfo.AcceptCheckContent, "','", objinfo.AcceptCheckGist, "',", objinfo.AcceptCheckSort, ",'", objinfo.AcceptCheckAnswerForPerson, "','", objinfo.AcceptCheckDate,
                    "','", objinfo.AcceptCheckResult, "','", objinfo.CompleteApplyContent, "','", objinfo.Remark, "',", objinfo.Flags, ",'", objinfo.requestfinishtime, "','", objinfo.planfinishtime, "','", objinfo.factfinishtime, "','", objinfo.factresult,
                    "','", objinfo.prjplan, "',", objinfo.CheckResult.ToString(), ",", objinfo.CertifiResult.ToString(), ",", objinfo.checkResults.ToString(), ",", objinfo.FilesType.ToString(), ",", objinfo.Mark.ToString(), ",'", objinfo.RectifyMarkID, "')"
                });
            }
            else if (OpType == "Update")
            {
                sqlString = string.Concat(new object[] {
                    "update Prj_ItemInspect set ExamineUnit='", objinfo.ExamineUnit, "',AcceptCheckUnit='", objinfo.AcceptCheckUnit, "',AcceptCheckContent='", objinfo.AcceptCheckContent, "',AcceptCheckGist='", objinfo.AcceptCheckGist, "',AcceptCheckSort=", objinfo.AcceptCheckSort, ",AcceptCheckAnswerForPerson='", objinfo.AcceptCheckAnswerForPerson, "',AcceptCheckDate='", objinfo.AcceptCheckDate, "',CompleteApplyContent='", objinfo.CompleteApplyContent,
                    "',AcceptCheckResult='", objinfo.AcceptCheckResult, "',Remark='", objinfo.Remark, "',requestfinishtime='", objinfo.requestfinishtime, "',planfinishtime='", objinfo.planfinishtime, "',factfinishtime='", objinfo.factfinishtime, "',factresult='", objinfo.factresult, "',prjplan='", objinfo.prjplan, "',CheckResult=", objinfo.CheckResult.ToString(),
                    ",CertifiResult = ", objinfo.CertifiResult.ToString(), ",IsRectified=", objinfo.IsRectified ? "1" : "0", ",checkResults =", objinfo.checkResults.ToString(), ",filesType =", objinfo.FilesType.ToString(), ",mark =", objinfo.Mark.ToString(), ",rectifyMarkID ='", objinfo.RectifyMarkID.ToString(), "'  where ID=", objinfo.ID
                });
            }
            else if (OpType == "Sp")
            {
                sqlString = string.Concat(new object[] { "update Prj_ItemInspect set ExamineApprovePerson='", objinfo.ExamineApprovePerson, "',ExamineApproveResult=", objinfo.ExamineApproveResult, ",ExamineApproveDate='", objinfo.ExamineApproveDate, "',ExamineApproveIdea='", objinfo.ExamineApproveIdea, "' where ID=", objinfo.ID });
            }
            return(publicDbOpClass.NonQuerySqlString(sqlString));
        }
Example #20
0
        private static Status ProcessExamplesFolder(DirectoryInfo directoryInfo, CheckInfo c)
        {
            if (c.Options.CheckSchemaDefinition)
            {
                CheckRelativePathSchemas(directoryInfo, c);
            }
            var eop = new EnumerationOptions()
            {
                RecurseSubdirectories = true, MatchCasing = MatchCasing.CaseInsensitive
            };
            var allBcfs = directoryInfo.GetFiles("*.bcf", eop)
                          .Where(x =>
                                 !x.FullName.Contains("unzipped", StringComparison.InvariantCultureIgnoreCase)
                                 &&
                                 !x.FullName.EndsWith("markup.bcf")
                                 )
                          .ToList();

            allBcfs.AddRange(
                directoryInfo.GetFiles("*.bcfzip", eop)
                .Where(x => !x.FullName.Contains("unzipped", StringComparison.InvariantCultureIgnoreCase))
                .ToList()
                );
            foreach (var bcf in allBcfs.OrderBy(x => x.FullName))
            {
                ProcessSingleFile(bcf, c);
            }
            return(c.Status);
        }
Example #21
0
    private void bind(string pk)
    {
        CheckInfo checkInfo = CheckAction.GetCheckInfo(pk);

        this.TextBox_jcdw.Text             = checkInfo.ExamineUnit;
        this.TextBox_sjdw.Text             = checkInfo.AcceptCheckUnit;
        this.TextBox_jcnr.Text             = checkInfo.AcceptCheckContent;
        this.TextBox_jcyj.Text             = checkInfo.AcceptCheckGist;
        this.DropDownList_lb.SelectedValue = checkInfo.AcceptCheckSort.ToString();
        this.TextBox_jcfzr.Text            = checkInfo.AcceptCheckAnswerForPerson;
        this.DateBox_jcrq.Text             = checkInfo.AcceptCheckDate.ToString("d");
        this.Textbox_jcjg.Text             = checkInfo.AcceptCheckResult;
        this.Textbox_zgnr.Text             = checkInfo.CompleteApplyContent;
        this.Textbox_bz.Text                = checkInfo.Remark;
        this.DateBox_yqwcsj.Text            = checkInfo.requestfinishtime.ToString("d");
        this.DateBox_jhwcsj.Text            = checkInfo.planfinishtime.ToString("d");
        this.DateBox_sjwcsj.Text            = checkInfo.factfinishtime.ToString("d");
        this.TextBox_sjjg.Text              = checkInfo.factresult;
        this.TextBox_xmjh.Text              = checkInfo.prjplan;
        this.ddlCheckResult.SelectedValue   = checkInfo.CheckResult.ToString();
        this.ddlCertifiResult.SelectedValue = checkInfo.CertifiResult.ToString();
        this.ddlCheckResults.SelectedValue  = checkInfo.checkResults.ToString();
        this.DDTClass.SelectedValue         = checkInfo.FilesType.ToString();
        this.ViewState["Mark"]              = checkInfo.Mark.ToString();
        if (checkInfo.Mark.ToString() != "2")
        {
            this.cbkmark.Checked = true;
        }
        else
        {
            this.cbkmark.Checked = false;
        }
        this.rectifyMarkID = checkInfo.RectifyMarkID;
    }
Example #22
0
		public EditTerms(CheckInfo src) {
			Result = null;
			tmp = src;
			InitializeComponent();
			DpDate.Text = DateTime.Now.ToString("yyyy/MM/dd");
			for(int i = 1;i <= 12; i++) {
				CbMonth.Items.Add(i + "月");
				if(i <= 5) {
					CbCount.Items.Add("第" + i);
				}
			}
			CbCount.Items.Add("最終");
			foreach(var w in weeks) {
				CbWeekday.Items.Add(w + "曜日");
			}
			for(int i = 0;i < 24; i++) {
				CbHour.Items.Add(i + "時");
			}
			for(int i = 0;i < 60; i++) {
				CbMinute.Items.Add(i + "分");
			}

			var dt = Date.FromTerm(src.Data, DateTime.Now.Year);
			if(dt == null) return;
			if(dt[2] == DateTime.MinValue) {
				RbDatePick.IsChecked = true;
				DpDate.Text = dt[0].ToString("yyyy/MM/dd");
			} else {
				RbDatePoint.IsChecked = true;
				var p = Regex.Match(src.Data, @"@\[(\s?[A-Za-z0-9]+)*\]");
				var weekNumber = int.TryParse(p.Groups[1].Captures[0].ToString(), out int res) ? res : 6;
				var weekDay = new System.Globalization.DateTimeFormatInfo().DayNames.ToList()
					.FindIndex(x => x == p.Groups[1].Captures[1].ToString().Trim());
				var monthNumber = new System.Globalization.DateTimeFormatInfo().MonthNames.ToList()
					.FindIndex(x => x == p.Groups[1].Captures[2].ToString().Trim());

				CbCount.SelectedIndex = weekNumber;
				CbWeekday.SelectedIndex = weekDay + 1;
				CbMonth.SelectedIndex = monthNumber + 1;

				var startDate = Date.FromWeekNumber(DateTime.Now.Year, monthNumber + 1, weekNumber, (DayOfWeek)weekDay);
				LbExample.Content = startDate.ToString("yyyy/MM/dd");
			}
			CbHour.SelectedIndex = dt[0].Hour + 1;
			CbMinute.SelectedIndex = dt[0].Minute + 1;
			var m = Regex.Match(src.Data, @"(\d{1,3})(Ds|Hs|Ms)$");
			TbTime.Text = m.Groups[1].ToString();
			switch(m.Groups[2].ToString()) {
				case "Ms":
					CbTimeKind.SelectedIndex = 0;
					break;
				case "Hs":
					CbTimeKind.SelectedIndex = 1;
					break;
				case "Ds":
					CbTimeKind.SelectedIndex = 2;
					break;
			}
		}
Example #23
0
 public EditString(CheckInfo src)
 {
     Result = null;
     tmp    = src;
     InitializeComponent();
     LbName.Content = src.Name + ": ";
     TbString.Text  = src.Data;
 }
Example #24
0
            private void RefreshCheckInfoStatus()
            {
                if (!m_UpdatableVersionListReady || !m_ReadOnlyVersionListReady || !m_ReadWriteVersionListReady)
                {
                    return;
                }

                int  removedCount         = 0;
                int  updateCount          = 0;
                long updateTotalLength    = 0L;
                long updateTotalZipLength = 0L;

                foreach (KeyValuePair <ResourceName, CheckInfo> checkInfo in m_CheckInfos)
                {
                    CheckInfo ci = checkInfo.Value;
                    ci.RefreshStatus(m_CurrentVariant);

                    if (ci.Status == CheckInfo.CheckStatus.StorageInReadOnly)
                    {
                        m_ResourceManager.m_ResourceInfos.Add(ci.ResourceName, new ResourceInfo(ci.ResourceName, ci.LoadType, ci.Length, ci.HashCode, true));
                    }
                    else if (ci.Status == CheckInfo.CheckStatus.StorageInReadWrite)
                    {
                        m_ResourceManager.m_ResourceInfos.Add(ci.ResourceName, new ResourceInfo(ci.ResourceName, ci.LoadType, ci.Length, ci.HashCode, false));
                    }
                    else if (ci.Status == CheckInfo.CheckStatus.NeedUpdate)
                    {
                        updateCount++;
                        updateTotalLength    += ci.Length;
                        updateTotalZipLength += ci.ZipLength;

                        ResourceNeedUpdate(ci.ResourceName, ci.LoadType, ci.Length, ci.HashCode, ci.ZipLength, ci.ZipHashCode);
                    }
                    else if (ci.Status == CheckInfo.CheckStatus.Disuse || ci.Status == CheckInfo.CheckStatus.Unavailable)
                    {
                        // Do nothing.
                    }
                    else
                    {
                        throw new GameFrameworkException(Utility.Text.Format("Check resources '{0}' error with unknown status.", ci.ResourceName.FullName));
                    }

                    if (ci.NeedRemove)
                    {
                        removedCount++;
                        File.Delete(Utility.Path.GetRegularPath(Path.Combine(m_ResourceManager.m_ReadWritePath, ci.ResourceName.FullName)));
                        m_ResourceManager.m_ReadWriteResourceInfos.Remove(ci.ResourceName);
                    }
                }

                if (removedCount > 0)
                {
                    Utility.Path.RemoveEmptyDirectory(m_ResourceManager.m_ReadWritePath);
                }

                ResourceCheckComplete(removedCount, updateCount, updateTotalLength, updateTotalZipLength);
            }
            private CheckInfo GetOrAddCheckInfo(ResourceName resourceName)
            {
                CheckInfo checkInfo = null;

                if (m_CheckInfos.TryGetValue(resourceName, out checkInfo))
                {
                    return
                }
            }
Example #26
0
        private void AddCheck()
        {
            CheckInfo check = new CheckInfo()
            {
                ID = 0, CheckStyle = 1
            };

            ShowFileForm(check);
        }
Example #27
0
        private void InitMainQuery()
        {
            _serverMainPage = new DividPage();
            queryMain       = new CheckInfo();
            lstMain         = new List <CheckInfo>();

            pageList.GetShowCountsByDGV(dgvList);
            bsMain.DataSource = queryMain;
        }
Example #28
0
    public void NewMethod(string fileName, bool check)
    {
        CheckController objChk    = new CheckController();
        CheckInfo       checkInfo = new CheckInfo();

        checkInfo.FileName = fileName;
        checkInfo.Checked  = check;
        objChk.CheckAdd(checkInfo);
    }
Example #29
0
        private void ClearForm()
        {
            _check = new CheckInfo();
            SetNewModel();

            bsMain.DataSource = _check;
            bsMain.EndEdit();

            cbbCheckType.Focus();
        }
Example #30
0
    internal static ExtMoveArrayWrapper generate_castling(
        CastlingRight Cr,
        bool Checks,
        bool Chess960,
        Position pos,
        ExtMoveArrayWrapper moveList,
        ColorT us,
        CheckInfo ci)
    {
        var KingSide = (Cr == CastlingRight.WHITE_OO || Cr == CastlingRight.BLACK_OO);

        if (pos.castling_impeded(Cr) || !pos.can_castle(Cr))
        {
            return moveList;
        }

        // After castling, the rook and king final positions are the same in Chess960
        // as they would be in standard chess.
        var kfrom = pos.square(PieceType.KING, us);
        var rfrom = pos.castling_rook_square(Cr);
        var kto = Square.relative_square(us, KingSide ? Square.SQ_G1 : Square.SQ_C1);
        var enemies = pos.pieces_Ct(Color.opposite(us));

        Debug.Assert(pos.checkers() == 0);

        var K = Chess960 ? kto > kfrom ? Square.DELTA_W : Square.DELTA_E : KingSide ? Square.DELTA_W : Square.DELTA_E;

        for (var s = kto; s != kfrom; s += K)
        {
            if ((pos.attackers_to(s) & enemies) != 0)
            {
                return moveList;
            }
        }

        // Because we generate only legal castling moves we need to verify that
        // when moving the castling rook we do not discover some hidden checker.
        // For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
        if (Chess960
            && ((Utils.attacks_bb_PtSBb(PieceType.ROOK, kto, Bitboard.XorWithSquare(pos.pieces(), rfrom))
                & pos.pieces_CtPtPt(Color.opposite(us), PieceType.ROOK, PieceType.QUEEN)))!= 0)
        {
            return moveList;
        }

        var m = Move.make(MoveType.CASTLING, kfrom, rfrom);

        if (Checks && !pos.gives_check(m, ci))
        {
            return moveList;
        }

        moveList.Add(m);
        return moveList;
    }
    public void CheckAdd(CheckInfo checkInfo)
    {
        List <KeyValuePair <string, object> > Param = new List <KeyValuePair <string, object> >();

        Param.Add(new KeyValuePair <string, object>("@FileName", checkInfo.FileName));
        Param.Add(new KeyValuePair <string, object>("@Checked", checkInfo.Checked));

        SQLHandler objSQL = new SQLHandler();

        objSQL.ExecuteNonQuery("usp_AddFileCheck", Param);
    }
Example #32
0
 public void CheckMoney(int x)
 {
     if (x <= Hesab)
     {
         Console.WriteLine("Succesfull");
     }
     else
     {
         CheckInfo?.Invoke(Hesab, x);
     }
 }
Example #33
0
        public void ConstructorTests()
        {
            Bitboards.init();
            Position.init();

            var pos = new Position("4rrk1/pp1n3p/3q2pQ/2p2b2/2PPp3/2P3N1/P2B2PP/4RRK1 w - - 0 20", false, null);

            CheckInfo ci = new CheckInfo(pos);

            Assert.AreEqual(Square.SQ_G8, ci.ksq);
            Assert.AreEqual(0ul, ci.checkSquares[0]);
            Assert.AreEqual(45035996273704960ul, ci.checkSquares[1]);
            Assert.AreEqual(4679521487814656ul, ci.checkSquares[2]);
            Assert.AreEqual(45053622886596608ul, ci.checkSquares[3]);
            Assert.AreEqual(11547299813322129408ul, ci.checkSquares[4]);
            Assert.AreEqual(11592353436208726016ul, ci.checkSquares[5]);
            Assert.AreEqual(0ul, ci.checkSquares[6]);
            Assert.AreEqual(0ul, ci.checkSquares[7]);
        }
Example #34
0
    // search<>() is the main search function for both PV and non-PV nodes and for
    // normal and SplitPoint nodes. When called just after a split point the search
    // is simpler because we have already probed the hash table, done a null move
    // search, and searched the first move before splitting, so we don't have to
    // repeat all this work again. We also don't need to store anything to the hash
    // table here: This is taken care of after we return from the split point.

    private static ValueT search(NodeType NT, bool SpNode, Position pos, StackArrayWrapper ss, ValueT alpha, ValueT beta,
        Depth depth, bool cutNode)
    {
        Utils.WriteToLog($"search(NT={(int) NT}, SpNode={(SpNode ? 1 : 0)}, pos={pos.key()}, ss, alpha={alpha}, beta={beta}, depth={(int) depth}, cutNode={(cutNode ? 1 : 0)})");
        var RootNode = NT == NodeType.Root;
        var PvNode = RootNode || NT == NodeType.PV;

        Debug.Assert(-Value.VALUE_INFINITE <= alpha && alpha < beta && beta <= Value.VALUE_INFINITE);
        Debug.Assert(PvNode || (alpha == beta - 1));
        Debug.Assert(depth > Depth.DEPTH_ZERO);

        var st = new StateInfo();
        TTEntry tte;
        SplitPoint splitPoint = null;
        ulong posKey = 0;
        MoveT ttMove, move, excludedMove, bestMove;
        ValueT bestValue, value, ttValue, eval;
        bool ttHit;
        int moveCount = 0;
        int quietCount = 0;

        var stack = ss[ss.current];
        var stackPlus1 = ss[ss.current + 1];
        var stackPlus2 = ss[ss.current + 2];
        var stackMinus1 = ss[ss.current - 1];
        var stackMinus2 = ss[ss.current - 2];

        // Step 1. Initialize node
        var thisThread = pos.this_thread();
        bool inCheck = pos.checkers() != 0;

        if (SpNode)
        {
            splitPoint = stack.splitPoint;
            bestMove = Move.Create(splitPoint.bestMove);
            bestValue = Value.Create(splitPoint.bestValue);
            tte = new TTEntry();
            ttMove = excludedMove = Move.MOVE_NONE;
            ttValue = Value.VALUE_NONE;

            Debug.Assert(splitPoint.bestValue > -Value.VALUE_INFINITE && splitPoint.moveCount > 0);

            goto moves_loop;
        }

        moveCount = quietCount = stack.moveCount = 0;
        bestValue = -Value.VALUE_INFINITE;
        stack.ply = stackMinus1.ply + 1;

        // Used to send selDepth info to GUI
        if (PvNode && thisThread.maxPly < stack.ply)
            thisThread.maxPly = stack.ply;

        if (!RootNode)
        {
            // Step 2. Check for aborted search and immediate draw
            if (Signals.stop || pos.is_draw() || stack.ply >= _.MAX_PLY)
                return stack.ply >= _.MAX_PLY && !inCheck
                    ? Eval.evaluate(false, pos)
                    : DrawValue[pos.side_to_move()];

            // Step 3. Mate distance pruning. Even if we mate at the next move our score
            // would be at best mate_in(ss.ply+1), but if alpha is already bigger because
            // a shorter mate was found upward in the tree then there is no need to search
            // because we will never beat the current alpha. Same logic but with reversed
            // signs applies also in the opposite condition of being mated instead of giving
            // mate. In this case return a fail-high score.
            alpha = Value.Create(Math.Max(Value.mated_in(stack.ply), alpha));
            beta = Value.Create(Math.Min(Value.mate_in(stack.ply + 1), beta));
            if (alpha >= beta)
                return alpha;
        }

        Debug.Assert(0 <= stack.ply && stack.ply < _.MAX_PLY);

        stack.currentMove = stack.ttMove = stackPlus1.excludedMove = bestMove = Move.MOVE_NONE;
        stackPlus1.skipEarlyPruning = false;
        stackPlus1.reduction = Depth.DEPTH_ZERO;
        stackPlus2.killers0 = stackPlus2.killers1 = Move.MOVE_NONE;

        // Step 4. Transposition table lookup
        // We don't want the score of a partial search to overwrite a previous full search
        // TT value, so we use a different position key in case of an excluded move.
        excludedMove = stack.excludedMove;
        posKey = excludedMove != 0 ? pos.exclusion_key() : pos.key();
        tte = TranspositionTable.probe(posKey, out ttHit);
        stack.ttMove = ttMove = RootNode ? RootMoves[(int) PVIdx].pv[0] : ttHit ? tte.move() : Move.MOVE_NONE;
        ttValue = ttHit ? value_from_tt(tte.value(), stack.ply) : Value.VALUE_NONE;

        // At non-PV nodes we check for a fail high/low. We don't prune at PV nodes
        if (!PvNode
            && ttHit
            && tte.depth() >= depth
            && ttValue != Value.VALUE_NONE // Only in case of TT access race
            && (ttValue >= beta
                ? (tte.bound() & Bound.BOUND_LOWER) != 0
                : (tte.bound() & Bound.BOUND_UPPER) != 0))
        {
            stack.currentMove = ttMove; // Can be Move.MOVE_NONE

            // If ttMove is quiet, update killers, history, counter move on TT hit
            if (ttValue >= beta && ttMove != 0 && !pos.capture_or_promotion(ttMove))
                update_stats(pos, ss, ttMove, depth, null, 0);

            return ttValue;
        }

        // Step 4a. Tablebase probe
        if (!RootNode && Tablebases.Cardinality != 0)
        {
            var piecesCnt = pos.count(PieceType.ALL_PIECES, Color.WHITE) + pos.count(PieceType.ALL_PIECES, Color.BLACK);

            if (piecesCnt <= Tablebases.Cardinality
                && (piecesCnt < Tablebases.Cardinality || depth >= Tablebases.ProbeDepth)
                && pos.rule50_count() == 0)
            {
                var found = 0;
                var v = Tablebases.probe_wdl(pos, ref found);

                if (found != 0)
                {
                    Tablebases.Hits++;

                    var drawScore = Tablebases.UseRule50 ? 1 : 0;

                    value = v < -drawScore
                        ? -Value.VALUE_MATE + _.MAX_PLY + stack.ply
                        : v > drawScore
                            ? Value.VALUE_MATE - _.MAX_PLY - stack.ply
                            : Value.VALUE_DRAW + 2*v*drawScore;

                    tte.save(posKey, value_to_tt(value, stack.ply), Bound.BOUND_EXACT,
                        new Depth(Math.Min(_.MAX_PLY - Depth.ONE_PLY_C, (int)depth + 6*Depth.ONE_PLY_C)),
                        Move.MOVE_NONE, Value.VALUE_NONE, TranspositionTable.generation());

                    return value;
                }
            }
        }

        // Step 5. Evaluate the position statically
        if (inCheck)
        {
            stack.staticEval = Value.VALUE_NONE;
            goto moves_loop;
        }

        if (ttHit)
        {
            // Never assume anything on values stored in TT
            if ((stack.staticEval = eval = tte.eval()) == Value.VALUE_NONE)
                eval = stack.staticEval = Eval.evaluate(false, pos);

            // Can ttValue be used as a better position evaluation?
            if (ttValue != Value.VALUE_NONE)
                if ((tte.bound() & (ttValue > eval ? Bound.BOUND_LOWER : Bound.BOUND_UPPER)) != 0)
                    eval = ttValue;
        }
        else
        {
            eval = stack.staticEval =
                stackMinus1.currentMove != Move.MOVE_NULL
                    ? Eval.evaluate(false, pos)
                    : -stackMinus1.staticEval + 2*Eval.Tempo;

            tte.save(posKey, Value.VALUE_NONE, Bound.BOUND_NONE, Depth.DEPTH_NONE, Move.MOVE_NONE,
                stack.staticEval, TranspositionTable.generation());
        }

        if (stack.skipEarlyPruning)
            goto moves_loop;

        // Step 6. Razoring (skipped when in check)
        if (!PvNode
            && depth < 4*Depth.ONE_PLY
            && eval + razor_margin(depth) <= alpha
            && ttMove == Move.MOVE_NONE)
        {
            if (depth <= Depth.ONE_PLY_C
                && eval + razor_margin(3*Depth.ONE_PLY) <= alpha)
                return qsearch(NodeType.NonPV, false, pos, ss, alpha, beta, Depth.DEPTH_ZERO);

            var ralpha = alpha - razor_margin(depth);
            var v = qsearch(NodeType.NonPV, false, pos, ss, ralpha, ralpha + 1, Depth.DEPTH_ZERO);
            if (v <= ralpha)
                return v;
        }

        // Step 7. Futility pruning: child node (skipped when in check)
        if (!RootNode
            && depth < 7*Depth.ONE_PLY
            && eval - futility_margin(depth) >= beta
            && eval < Value.VALUE_KNOWN_WIN // Do not return unproven wins
            && pos.non_pawn_material(pos.side_to_move())!=0)
            return eval - futility_margin(depth);

        // Step 8. Null move search with verification search (is omitted in PV nodes)
        if (!PvNode
            && depth >= 2*Depth.ONE_PLY_C
            && eval >= beta
            && pos.non_pawn_material(pos.side_to_move())!=0)
        {
            stack.currentMove = Move.MOVE_NULL;

            Debug.Assert(eval - beta >= 0);

            // Null move dynamic reduction based on depth and value
            var R = ((823 + 67*depth)/256 + Math.Min((eval - beta)/Value.PawnValueMg, 3))*(int) Depth.ONE_PLY;

            pos.do_null_move(st);
            stackPlus1.skipEarlyPruning = true;
            var nullValue = depth - R < Depth.ONE_PLY
                ? -qsearch(NodeType.NonPV, false, pos, new StackArrayWrapper(ss.table, ss.current + 1), -beta, -beta + 1,
                    Depth.DEPTH_ZERO)
                : -search(NodeType.NonPV, false, pos, new StackArrayWrapper(ss.table, ss.current + 1), -beta, -beta + 1,
                    depth - R, !cutNode);
            stackPlus1.skipEarlyPruning = false;
            pos.undo_null_move();

            if (nullValue >= beta)
            {
                // Do not return unproven mate scores
                if (nullValue >= Value.VALUE_MATE_IN_MAX_PLY)
                    nullValue = beta;

                if (depth < 12*Depth.ONE_PLY && Math.Abs(beta) < Value.VALUE_KNOWN_WIN)
                    return nullValue;

                // Do verification search at high depths
                stack.skipEarlyPruning = true;
                var v = depth - R < Depth.ONE_PLY
                    ? qsearch(NodeType.NonPV, false, pos, ss, beta - 1, beta, Depth.DEPTH_ZERO)
                    : search(NodeType.NonPV, false, pos, ss, beta - 1, beta, depth - R, false);
                stack.skipEarlyPruning = false;

                if (v >= beta)
                    return nullValue;
            }
        }

        // Step 9. ProbCut (skipped when in check)
        // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
        // and a reduced search returns a value much above beta, we can (almost) safely
        // prune the previous move.
        if (!PvNode
            && depth >= 5*Depth.ONE_PLY_C
            && Math.Abs(beta) < Value.VALUE_MATE_IN_MAX_PLY)
        {
            var rbeta = Value.Create(Math.Min(beta + 200, Value.VALUE_INFINITE));
            var rdepth = depth - 4*Depth.ONE_PLY;

            Debug.Assert(rdepth >= Depth.ONE_PLY_C);
            Debug.Assert(stackMinus1.currentMove != Move.MOVE_NONE);
            Debug.Assert(stackMinus1.currentMove != Move.MOVE_NULL);

            var mp2 = new MovePicker(pos, ttMove, History, CounterMovesHistory,
                Value.PieceValue[(int) Phase.MG][pos.captured_piece_type()]);
            var ci2 = new CheckInfo(pos);

            while ((move = mp2.next_move(false)) != Move.MOVE_NONE)
                if (pos.legal(move, ci2.pinned))
                {
                    stack.currentMove = move;
                    pos.do_move(move, st, pos.gives_check(move, ci2));
                    value =
                        -search(NodeType.NonPV, false, pos, new StackArrayWrapper(ss.table, ss.current + 1), -rbeta,
                            -rbeta + 1, rdepth, !cutNode);
                    pos.undo_move(move);
                    if (value >= rbeta)
                        return value;
                }
        }

        // Step 10. Internal iterative deepening (skipped when in check)
        if (depth >= (PvNode ? 5*Depth.ONE_PLY_C : 8*Depth.ONE_PLY_C)
            && ttMove == 0
            && (PvNode || stack.staticEval + 256 >= beta))
        {
            var d = depth - 2*Depth.ONE_PLY - (PvNode ? Depth.DEPTH_ZERO : depth/4);
            stack.skipEarlyPruning = true;
            search(PvNode ? NodeType.PV : NodeType.NonPV, false, pos, ss, alpha, beta, d, true);
            stack.skipEarlyPruning = false;

            tte = TranspositionTable.probe(posKey, out ttHit);
            ttMove = ttHit ? tte.move() : Move.MOVE_NONE;
        }

 moves_loop: // When in check and at SpNode search starts from here

        var prevMoveSq = Move.to_sq(stackMinus1.currentMove);
        var countermove = Countermoves.table[pos.piece_on(prevMoveSq), prevMoveSq];

        var mp = new MovePicker(pos, ttMove, depth, History, CounterMovesHistory, countermove, ss);
        var ci = new CheckInfo(pos);
        value = bestValue; // Workaround a bogus 'uninitialized' warning under gcc
        var improving = stack.staticEval >= stackMinus2.staticEval
                         || stack.staticEval == Value.VALUE_NONE
                         || stackMinus2.staticEval == Value.VALUE_NONE;

        var singularExtensionNode = !RootNode
                                     && !SpNode
                                     && depth >= 8*Depth.ONE_PLY_C
                                     && ttMove != Move.MOVE_NONE
            /*  &&  ttValue != Value.VALUE_NONE Already implicit in the next condition */
                                     && Math.Abs(ttValue) < Value.VALUE_KNOWN_WIN
                                     && excludedMove == 0// Recursive singular search is not allowed
                                     && ((tte.bound() & Bound.BOUND_LOWER) != 0)
                                     && tte.depth() >= depth - 3*Depth.ONE_PLY_C;

        var quietsSearched = new MoveT[64];
        // Step 11. Loop through moves
        // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
        while ((move = mp.next_move(SpNode)) != Move.MOVE_NONE)
        {
            Utils.WriteToLog($"mp.next_move = {(int) move}");
            Debug.Assert(Move.is_ok(move));

            if (move == excludedMove)
                continue;

            // At root obey the "searchmoves" option and skip moves not listed in Root
            // Move List. As a consequence any illegal move is also skipped. In MultiPV
            // mode we also skip PV moves which have been already searched.
            if (RootNode && RootMoves.All(rootMove => rootMove.pv[0] != move))
                continue;
            
            if (SpNode)
            {
                // Shared counter cannot be decremented later if the move turns out to be illegal
                if (!pos.legal(move, ci.pinned))
                    continue;

                stack.moveCount = moveCount = ++splitPoint.moveCount;
                ThreadHelper.lock_release(splitPoint.spinLock);
            }
            else
                stack.moveCount = ++moveCount;

            if (RootNode)
            {
                Signals.firstRootMove = (moveCount == 1);

                if (thisThread == ThreadPool.main() && TimeManagement.elapsed() > 3000)
                    Output.WriteLine(
                        $"info depth {depth/Depth.ONE_PLY} currmove {UCI.move(move, pos.is_chess960())} currmovenumber {moveCount + PVIdx}");
            }

            if (PvNode)
                stackPlus1.pv = new List<MoveT>();

            var extension = Depth.DEPTH_ZERO;
            var captureOrPromotion = pos.capture_or_promotion(move);

            var givesCheck = Move.type_of(move) == MoveType.NORMAL && ci.dcCandidates == 0
                ? Bitboard.AndWithSquare(ci.checkSquares[Piece.type_of(pos.piece_on(Move.from_sq(move)))], Move.to_sq(move))!=0
                : pos.gives_check(move, ci);

            // Step 12. Extend checks
            if (givesCheck && pos.see_sign(move) >= Value.VALUE_ZERO)
                extension = Depth.ONE_PLY;

            // Singular extension search. If all moves but one fail low on a search of
            // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
            // is singular and should be extended. To verify this we do a reduced search
            // on all the other moves but the ttMove and if the result is lower than
            // ttValue minus a margin then we extend the ttMove.
            if (singularExtensionNode
                && move == ttMove
                && extension == 0
                && pos.legal(move, ci.pinned))
            {
                var rBeta = ttValue - 2*depth/Depth.ONE_PLY;
                stack.excludedMove = move;
                stack.skipEarlyPruning = true;
                value = search(NodeType.NonPV, false, pos, ss, rBeta - 1, rBeta, depth/2, cutNode);
                stack.skipEarlyPruning = false;
                stack.excludedMove = Move.MOVE_NONE;

                if (value < rBeta)
                    extension = Depth.ONE_PLY;
            }

            // Update the current move (this must be done after singular extension search)
            var newDepth = depth - Depth.ONE_PLY + extension;

            // Step 13. Pruning at shallow depth
            if (!RootNode
                && !captureOrPromotion
                && !inCheck
                && !givesCheck
                && !pos.advanced_pawn_push(move)
                && bestValue > Value.VALUE_MATED_IN_MAX_PLY)
            {
                // Move count based pruning
                if (depth < 16*Depth.ONE_PLY
                    && moveCount >= FutilityMoveCounts[improving ? 1 : 0, depth])
                {
                    if (SpNode)
                        ThreadHelper.lock_grab(splitPoint.spinLock);

                    continue;
                }

                var predictedDepth = newDepth - reduction(PvNode, improving, depth, moveCount);

                // Futility pruning: parent node
                if (predictedDepth < 7*Depth.ONE_PLY)
                {
                    var futilityValue = stack.staticEval + futility_margin(predictedDepth) + 256;

                    if (futilityValue <= alpha)
                    {
                        bestValue = Value.Create(Math.Max(bestValue, futilityValue));

                        if (SpNode)
                        {
                            ThreadHelper.lock_grab(splitPoint.spinLock);
                            if (bestValue > splitPoint.bestValue)
                                splitPoint.bestValue = bestValue;
                        }
                        continue;
                    }
                }

                // Prune moves with negative SEE at low depths
                if (predictedDepth < 4*Depth.ONE_PLY && pos.see_sign(move) < Value.VALUE_ZERO)
                {
                    if (SpNode)
                        ThreadHelper.lock_grab(splitPoint.spinLock);

                    continue;
                }
            }

            // Speculative prefetch as early as possible
            //prefetch(TT.first_entry(pos.key_after(move)));

            // Check for legality just before making the move
            if (!RootNode && !SpNode && !pos.legal(move, ci.pinned))
            {
                stack.moveCount = --moveCount;
                continue;
            }

            stack.currentMove = move;

            // Step 14. Make the move
            pos.do_move(move, st, givesCheck);

            // Step 15. Reduced depth search (LMR). If the move fails high it will be
            // re-searched at full depth.
            bool doFullDepthSearch;
            if (depth >= 3*Depth.ONE_PLY_C
                && moveCount > 1
                && !captureOrPromotion
                && move != stack.killers0
                && move != stack.killers1)
            {
                stack.reduction = reduction(PvNode, improving, depth, moveCount);

                if ((!PvNode && cutNode)
                    || (History.table[pos.piece_on(Move.to_sq(move)), Move.to_sq(move)] < Value.VALUE_ZERO
                        &&
                        CounterMovesHistory.table[pos.piece_on(prevMoveSq), prevMoveSq].table[
                            pos.piece_on(Move.to_sq(move)), Move.to_sq(move)] <= Value.VALUE_ZERO))
                    stack.reduction += Depth.ONE_PLY;

                if (History.table[pos.piece_on(Move.to_sq(move)), Move.to_sq(move)] > Value.VALUE_ZERO
                    &&
                    CounterMovesHistory.table[pos.piece_on(prevMoveSq), prevMoveSq].table[
                        pos.piece_on(Move.to_sq(move)), Move.to_sq(move)] > Value.VALUE_ZERO)
                    stack.reduction =
                        new Depth(Math.Max(Depth.DEPTH_ZERO_C, stack.reduction - Depth.ONE_PLY_C));

                // Decrease reduction for moves that escape a capture
                if (stack.reduction > 0
                    && Move.type_of(move) == MoveType.NORMAL
                    && Piece.type_of(pos.piece_on(Move.to_sq(move))) != PieceType.PAWN
                    && pos.see(Move.make_move(Move.to_sq(move), Move.from_sq(move))) < Value.VALUE_ZERO)
                    stack.reduction =
                        new Depth(Math.Max(Depth.DEPTH_ZERO_C, stack.reduction - Depth.ONE_PLY_C));

                var d = new Depth(Math.Max(newDepth - (int)stack.reduction, Depth.ONE_PLY_C));
                if (SpNode)
                    alpha = Value.Create(splitPoint.alpha);

                value =
                    -search(NodeType.NonPV, false, pos, new StackArrayWrapper(ss.table, ss.current + 1), -(alpha + 1),
                        -alpha, d, true);

                doFullDepthSearch = (value > alpha && stack.reduction != Depth.DEPTH_ZERO);
                stack.reduction = Depth.DEPTH_ZERO;
            }
            else
                doFullDepthSearch = !PvNode || moveCount > 1;

            // Step 16. Full depth search, when LMR is skipped or fails high
            if (doFullDepthSearch)
            {
                if (SpNode)
                    alpha = Value.Create(splitPoint.alpha);

                value = newDepth < Depth.ONE_PLY
                    ? givesCheck
                        ? -qsearch(NodeType.NonPV, true, pos, new StackArrayWrapper(ss.table, ss.current + 1),
                            -(alpha + 1), -alpha, Depth.DEPTH_ZERO)
                        : -qsearch(NodeType.NonPV, false, pos, new StackArrayWrapper(ss.table, ss.current + 1),
                            -(alpha + 1), -alpha, Depth.DEPTH_ZERO)
                    : -search(NodeType.NonPV, false, pos, new StackArrayWrapper(ss.table, ss.current + 1), -(alpha + 1),
                        -alpha, newDepth, !cutNode);
            }

            // For PV nodes only, do a full PV search on the first move or after a fail
            // high (in the latter case search only if value < beta), otherwise let the
            // parent node fail low with value <= alpha and to try another move.
            if (PvNode && (moveCount == 1 || (value > alpha && (RootNode || value < beta))))
            {
                stackPlus1.pv = new List<MoveT>() { Move.MOVE_NONE };
                stackPlus1.pv[0] = Move.MOVE_NONE;

                value = newDepth < Depth.ONE_PLY
                    ? givesCheck
                        ? -qsearch(NodeType.PV, true, pos, new StackArrayWrapper(ss.table, ss.current + 1), -beta,
                            -alpha, Depth.DEPTH_ZERO)
                        : -qsearch(NodeType.PV, false, pos, new StackArrayWrapper(ss.table, ss.current + 1), -beta,
                            -alpha, Depth.DEPTH_ZERO)
                    : -search(NodeType.PV, false, pos, new StackArrayWrapper(ss.table, ss.current + 1), -beta, -alpha,
                        newDepth, false);
            }

            // Step 17. Undo move
            pos.undo_move(move);

            Debug.Assert(value > -Value.VALUE_INFINITE && value < Value.VALUE_INFINITE);

            // Step 18. Check for new best move
            if (SpNode)
            {
                ThreadHelper.lock_grab(splitPoint.spinLock);
                bestValue = Value.Create(splitPoint.bestValue);
                alpha = Value.Create(splitPoint.alpha);
            }

            // Finished searching the move. If a stop or a cutoff occurred, the return
            // value of the search cannot be trusted, and we return immediately without
            // updating best move, PV and TT.
            if (Signals.stop || thisThread.cutoff_occurred())
                return Value.VALUE_ZERO;

            if (RootNode)
            {
                var rm = RootMoves.Find(rootmove => rootmove.pv[0] == move);

                // PV move or new best move ?
                if (moveCount == 1 || value > alpha)
                {
                    rm.score = value;

                    var firstEntry = rm.pv[0];
                    rm.pv.Clear();
                    rm.pv.Add(firstEntry);

                    Debug.Assert(stackPlus1.pv != null);

                    foreach (var m in stackPlus1.pv.TakeWhile(m => m != Move.MOVE_NONE))
                    {
                        rm.pv.Add(m);
                    }

                    // We record how often the best move has been changed in each
                    // iteration. This information is used for time management: When
                    // the best move changes frequently, we allocate some more time.
                    if (moveCount > 1)
                        ++BestMoveChanges;
                }
                else
                // All other moves but the PV are set to the lowest value: this is
                // not a problem when sorting because the sort is stable and the
                // move position in the list is preserved - just the PV is pushed up.
                    rm.score = -Value.VALUE_INFINITE;
            }

            if (value > bestValue)
            {
                bestValue = Value.Create(SpNode ? splitPoint.bestValue = value : value);

                if (value > alpha)
                {
                    // If there is an easy move for this position, clear it if unstable
                    if (PvNode
                        && EasyMove.get(pos.key()) != 0
                        && (move != EasyMove.get(pos.key()) || moveCount > 1))
                        EasyMove.clear();

                    bestMove = Move.Create(SpNode ? splitPoint.bestMove = move : move);

                    if (PvNode && !RootNode) // Update pv even in fail-high case
                        update_pv(SpNode ? splitPoint.ss[ss.current].pv : stack.pv, move, stackPlus1.pv);

                    if (PvNode && value < beta) // Update alpha! Always alpha < beta
                        alpha = Value.Create(SpNode ? splitPoint.alpha = value : value);
                    else
                    {
                        Debug.Assert(value >= beta); // Fail high

                        if (SpNode)
                            splitPoint.cutoff = true;

                        break;
                    }
                }
            }

            if (!SpNode && !captureOrPromotion && move != bestMove && quietCount < 64)
                quietsSearched[quietCount++] = move;

            // Step 19. Check for splitting the search
            if (!SpNode
                && ThreadPool.threads.Count >= 2
                && depth >= ThreadPool.minimumSplitDepth
                && (thisThread.activeSplitPoint == null
                    || !thisThread.activeSplitPoint.allSlavesSearching
                    || (ThreadPool.threads.Count > _.MAX_SLAVES_PER_SPLITPOINT
                        && Bitcount.popcount_Full(thisThread.activeSplitPoint.slavesMask) == _.MAX_SLAVES_PER_SPLITPOINT))
                && thisThread.splitPointsSize < _.MAX_SPLITPOINTS_PER_THREAD)
            {
                Debug.Assert(bestValue > -Value.VALUE_INFINITE && bestValue < beta);

                thisThread.split(pos, ss, alpha, beta, ref bestValue, ref bestMove,
                    depth, moveCount, mp, NT, cutNode);

                if (Signals.stop || thisThread.cutoff_occurred())
                    return Value.VALUE_ZERO;

                if (bestValue >= beta)
                    break;
            }
        }

        if (SpNode)
            return bestValue;

        // Following condition would detect a stop or a cutoff set only after move
        // loop has been completed. But in this case bestValue is valid because we
        // have fully searched our subtree, and we can anyhow save the result in TT.
        /*
           if (Signals.stop || thisThread.cutoff_occurred())
            return VALUE_DRAW;
        */

        // Step 20. Check for mate and stalemate
        // All legal moves have been searched and if there are no legal moves, it
        // must be mate or stalemate. If we are in a singular extension search then
        // return a fail low score.
        if (moveCount == 0)
            bestValue = excludedMove != 0
                ? alpha
                : inCheck ? Value.mated_in(stack.ply) : DrawValue[pos.side_to_move()];

        // Quiet best move: update killers, history and countermoves
        else if (bestMove != 0 && !pos.capture_or_promotion(bestMove))
            update_stats(pos, ss, bestMove, depth, quietsSearched, quietCount);

        // Bonus for prior countermove that caused the fail low
        else if (bestMove==0)
        {
            if (Move.is_ok(stackMinus2.currentMove) && Move.is_ok(stackMinus1.currentMove) &&
                pos.captured_piece_type()==0 && !inCheck && depth >= 3*Depth.ONE_PLY_C)
            {
                var bonus = Value.Create((depth/Depth.ONE_PLY)*(depth/Depth.ONE_PLY));
                var prevSq = Move.to_sq(stackMinus1.currentMove);
                var prevPrevSq = Move.to_sq(stackMinus2.currentMove);
                var flMoveCmh = CounterMovesHistory.table[pos.piece_on(prevPrevSq), prevPrevSq];
                flMoveCmh.updateCMH(pos.piece_on(prevSq), prevSq, bonus);
            }
        }

        tte.save(posKey, value_to_tt(bestValue, stack.ply),
            bestValue >= beta
                ? Bound.BOUND_LOWER
                : PvNode && bestMove!=0 ? Bound.BOUND_EXACT : Bound.BOUND_UPPER,
            depth, bestMove, stack.staticEval, TranspositionTable.generation());

        Debug.Assert(bestValue > -Value.VALUE_INFINITE && bestValue < Value.VALUE_INFINITE);

        return bestValue;
    }
Example #35
0
    internal static ExtMoveArrayWrapper generate_pawn_moves(
        ColorT Us,
        GenType Type,
        Position pos,
        ExtMoveArrayWrapper moveList,
        BitboardT target,
        CheckInfo ci)
    {
        // Compute our parametrized parameters at compile time, named according to
        // the point of view of white side.
        var Them = (Us == Color.WHITE ? Color.BLACK : Color.WHITE);
        var TRank8BB = (Us == Color.WHITE ? Bitboard.Rank8BB : Bitboard.Rank1BB);
        var TRank7BB = (Us == Color.WHITE ? Bitboard.Rank7BB : Bitboard.Rank2BB);
        var TRank3BB = (Us == Color.WHITE ? Bitboard.Rank3BB : Bitboard.Rank6BB);
        var Up = (Us == Color.WHITE ? Square.DELTA_N : Square.DELTA_S);
        var Right = (Us == Color.WHITE ? Square.DELTA_NE : Square.DELTA_SW);
        var Left = (Us == Color.WHITE ? Square.DELTA_NW : Square.DELTA_SE);

        var emptySquares = Bitboard.Create(0);

        var pawnsOn7 = pos.pieces_CtPt(Us, PieceType.PAWN) & TRank7BB;
        var pawnsNotOn7 = pos.pieces_CtPt(Us, PieceType.PAWN) & ~TRank7BB;

        var enemies = (Type == GenType.EVASIONS
            ? pos.pieces_Ct(Them) & target
            : Type == GenType.CAPTURES ? target : pos.pieces_Ct(Them));

        // Single and double pawn pushes, no promotions
        if (Type != GenType.CAPTURES)
        {
            emptySquares = (Type == GenType.QUIETS || Type == GenType.QUIET_CHECKS ? target : ~pos.pieces());

            var b1 = Bitboard.shift_bb(Up, pawnsNotOn7) & emptySquares;
            var b2 = Bitboard.shift_bb(Up, b1 & TRank3BB) & emptySquares;

            if (Type == GenType.EVASIONS) // Consider only blocking squares
            {
                b1 &= target;
                b2 &= target;
            }

            if (Type == GenType.QUIET_CHECKS)
            {
                b1 &= pos.attacks_from_PS(PieceType.PAWN, ci.ksq, Them);
                b2 &= pos.attacks_from_PS(PieceType.PAWN, ci.ksq, Them);

                // Add pawn pushes which give discovered check. This is possible only
                // if the pawn is not on the same file as the enemy king, because we
                // don't generate captures. Note that a possible discovery check
                // promotion has been already generated amongst the captures.
                if ((pawnsNotOn7 & ci.dcCandidates) != 0)
                {
                    var dc1 = Bitboard.shift_bb(Up, pawnsNotOn7 & ci.dcCandidates) & emptySquares
                              & ~Utils.file_bb_St(ci.ksq);
                    var dc2 = Bitboard.shift_bb(Up, dc1 & TRank3BB) & emptySquares;

                    b1 |= dc1;
                    b2 |= dc2;
                }
            }

            while (b1 != 0)
            {
                var to = Utils.pop_lsb(ref b1);
                (moveList).Add(Move.make_move(to - Up, to));
            }

            while (b2 != 0)
            {
                var to = Utils.pop_lsb(ref b2);
                (moveList).Add(Move.make_move(to - Up - Up, to));
            }
        }

        // Promotions and underpromotions
        if (pawnsOn7 != 0 && (Type != GenType.EVASIONS || ((target & TRank8BB) != 0)))
        {
            if (Type == GenType.CAPTURES)
            {
                emptySquares = ~pos.pieces();
            }

            if (Type == GenType.EVASIONS)
            {
                emptySquares &= target;
            }

            var b1 = Bitboard.shift_bb(Right, pawnsOn7) & enemies;
            var b2 = Bitboard.shift_bb(Left, pawnsOn7) & enemies;
            var b3 = Bitboard.shift_bb(Up, pawnsOn7) & emptySquares;

            while (b1 != 0)
            {
                moveList = make_promotions(Type, Right, moveList, Utils.pop_lsb(ref b1), ci);
            }

            while (b2 != 0)
            {
                moveList = make_promotions(Type, Left, moveList, Utils.pop_lsb(ref b2), ci);
            }

            while (b3 != 0)
            {
                moveList = make_promotions(Type, Up, moveList, Utils.pop_lsb(ref b3), ci);
            }
        }

        // Standard and en-passant captures
        if (Type == GenType.CAPTURES || Type == GenType.EVASIONS || Type == GenType.NON_EVASIONS)
        {
            var b1 = Bitboard.shift_bb(Right, pawnsNotOn7) & enemies;
            var b2 = Bitboard.shift_bb(Left, pawnsNotOn7) & enemies;

            while (b1 != 0)
            {
                var to = Utils.pop_lsb(ref b1);
                (moveList).Add(Move.make_move(to - Right, to));
            }

            while (b2 != 0)
            {
                var to = Utils.pop_lsb(ref b2);
                (moveList).Add(Move.make_move(to - Left, to));
            }

            if (pos.ep_square() != Square.SQ_NONE)
            {
                Debug.Assert(Square.rank_of(pos.ep_square()) == Rank.relative_rank_CtRt(Us, Rank.RANK_6));

                // An en passant capture can be an evasion only if the checking piece
                // is the double pushed pawn and so is in the target. Otherwise this
                // is a discovery check and we are forced to do otherwise.
                if (Type == GenType.EVASIONS && Bitboard.AndWithSquare(target, (pos.ep_square() - Up))==0)
                {
                    return moveList;
                }

                b1 = pawnsNotOn7 & pos.attacks_from_PS(PieceType.PAWN, pos.ep_square(), Them);

                Debug.Assert(b1 != 0);

                while (b1 != 0)
                {
                    (moveList).Add(Move.make(MoveType.ENPASSANT, Utils.pop_lsb(ref b1), pos.ep_square()));
                }
            }
        }

        return moveList;
    }
Example #36
0
    private static ValueT qsearch(NodeType NT, bool InCheck, Position pos, StackArrayWrapper ss, ValueT alpha, ValueT beta,
        Depth depth)
    {
        Utils.WriteToLog($"qsearch(NT={(int) NT}, InCheck={(InCheck ? 1 : 0)}, pos={pos.key()}, ss, alpha={alpha}, beta={beta}, depth={(int) depth})");
        var PvNode = NT == NodeType.PV;

        Debug.Assert(NT == NodeType.PV || NT == NodeType.NonPV);
        Debug.Assert(InCheck == (pos.checkers() != 0));
        Debug.Assert(alpha >= -Value.VALUE_INFINITE && alpha < beta && beta <= Value.VALUE_INFINITE);
        Debug.Assert(PvNode || (alpha == beta - 1));
        Debug.Assert(depth <= Depth.DEPTH_ZERO_C);

        var currentStack = ss[ss.current];
        var nextStack = ss[ss.current+1];
        var previousStack = ss[ss.current - 1];
        var oldAlpha = 0;
        if (PvNode)
        {
            oldAlpha = alpha; // To flag BOUND_EXACT when eval above alpha and no available moves
            nextStack.pv = new List<MoveT>() { Move.MOVE_NONE };
            currentStack.pv[0] = Move.MOVE_NONE;
        }

        currentStack.currentMove = Move.MOVE_NONE;
        currentStack.ply = previousStack.ply + 1;
        var currentPly = currentStack.ply;
        // Check for an instant draw or if the maximum ply has been reached
        if (pos.is_draw() || currentPly >= _.MAX_PLY)
            return currentPly >= _.MAX_PLY && !InCheck
                ? Eval.evaluate(false, pos)
                : DrawValue[pos.side_to_move()];

        Debug.Assert(0 <= currentPly && currentPly < _.MAX_PLY);

        // Decide whether or not to include checks: this fixes also the type of
        // TT entry depth that we are going to use. Note that in qsearch we use
        // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
        var ttDepth = InCheck || (int)depth >= Depth.DEPTH_QS_CHECKS_C
            ? Depth.DEPTH_QS_CHECKS
            : Depth.DEPTH_QS_NO_CHECKS;

        // Transposition table lookup
        bool ttHit;
        var posKey = pos.key();
        var tte = TranspositionTable.probe(posKey, out ttHit);
        var ttMove = ttHit ? tte.move() : Move.MOVE_NONE;
        var ttValue = ttHit ? value_from_tt(tte.value(), currentPly) : Value.VALUE_NONE;

        if (!PvNode
            && ttHit
            && tte.depth() >= ttDepth
            && ttValue != Value.VALUE_NONE // Only in case of TT access race
            && ((ttValue >= beta ? (tte.bound() & Bound.BOUND_LOWER) : (tte.bound() & Bound.BOUND_UPPER))) != 0)
        {
            currentStack.currentMove = ttMove; // Can be MOVE_NONE
            return ttValue;
        }

        ValueT bestValue;
        ValueT futilityBase;
        // Evaluate the position statically
        if (InCheck)
        {
            currentStack.staticEval = Value.VALUE_NONE;
            bestValue = futilityBase = -Value.VALUE_INFINITE;
        }
        else
        {
            if (ttHit)
            {
                // Never assume anything on values stored in TT
                if ((currentStack.staticEval = bestValue = tte.eval()) == Value.VALUE_NONE)
                    currentStack.staticEval = bestValue = Eval.evaluate(false, pos);

                // Can ttValue be used as a better position evaluation?
                if (ttValue != Value.VALUE_NONE)
                    if ((tte.bound() & (ttValue > bestValue ? Bound.BOUND_LOWER : Bound.BOUND_UPPER)) != 0)
                        bestValue = ttValue;
            }
            else
                currentStack.staticEval = bestValue =
                    previousStack.currentMove != Move.MOVE_NULL
                        ? Eval.evaluate(false, pos)
                        : -previousStack.staticEval + 2*Eval.Tempo;

            // Stand pat. Return immediately if static value is at least beta
            if (bestValue >= beta)
            {
                if (!ttHit)
                    tte.save(pos.key(), value_to_tt(bestValue, currentPly), Bound.BOUND_LOWER,
                        Depth.DEPTH_NONE, Move.MOVE_NONE, currentStack.staticEval, TranspositionTable.generation());

                return bestValue;
            }

            if (PvNode && bestValue > alpha)
                alpha = bestValue;

            futilityBase = bestValue + 128;
        }

        // Initialize a MovePicker object for the current position, and prepare
        // to search the moves. Because the depth is <= 0 here, only captures,
        // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
        // be generated.
        var mp = new MovePicker(pos, ttMove, depth, History, CounterMovesHistory,
            Move.to_sq(previousStack.currentMove));
        var ci = new CheckInfo(pos);

        // Loop through the moves until no moves remain or a beta cutoff occurs
        MoveT move;
        MoveT bestMove = Move.MOVE_NONE;
        while ((move = mp.next_move(false)) != Move.MOVE_NONE)
        {
            Debug.Assert(Move.is_ok(move));

            var givesCheck = Move.type_of(move) == MoveType.NORMAL && ci.dcCandidates == 0
                ? Bitboard.AndWithSquare(ci.checkSquares[Piece.type_of(pos.piece_on(Move.from_sq(move)))], Move.to_sq(move))!=0
                : pos.gives_check(move, ci);

            // Futility pruning
            if (!InCheck
                && !givesCheck
                && futilityBase > -Value.VALUE_KNOWN_WIN
                && !pos.advanced_pawn_push(move))
            {
                Debug.Assert(Move.type_of(move) != MoveType.ENPASSANT); // Due to !pos.advanced_pawn_push

                var futilityValue = futilityBase + Value.PieceValue[(int) Phase.EG][pos.piece_on(Move.to_sq(move))];

                if (futilityValue <= alpha)
                {
                    bestValue = Value.Create(Math.Max(bestValue, futilityValue));
                    continue;
                }

                if (futilityBase <= alpha && pos.see(move) <= Value.VALUE_ZERO)
                {
                    bestValue = Value.Create(Math.Max(bestValue, futilityBase));
                    continue;
                }
            }

            // Detect non-capture evasions that are candidates to be pruned
            var evasionPrunable = InCheck
                                   && bestValue > Value.VALUE_MATED_IN_MAX_PLY
                                   && !pos.capture(move);

            // Don't search moves with negative SEE values
            if ((!InCheck || evasionPrunable)
                && Move.type_of(move) != MoveType.PROMOTION
                && pos.see_sign(move) < Value.VALUE_ZERO)
                continue;

            // Speculative prefetch as early as possible
            //prefetch(TT.first_entry(pos.key_after(move)));

            // Check for legality just before making the move
            if (!pos.legal(move, ci.pinned))
                continue;

            ss[ss.current].currentMove = move;

            // Make and search the move
            pos.do_move(move, new StateInfo(), givesCheck);
            var value = givesCheck
                ? -qsearch(NT, true, pos, new StackArrayWrapper(ss.table, ss.current + 1), -beta, -alpha,
                    depth - Depth.ONE_PLY)
                : -qsearch(NT, false, pos, new StackArrayWrapper(ss.table, ss.current + 1), -beta, -alpha,
                    depth - Depth.ONE_PLY);
            pos.undo_move(move);

            Debug.Assert(value > -Value.VALUE_INFINITE && value < Value.VALUE_INFINITE);

            // Check for new best move
            if (value <= bestValue) continue;

            bestValue = value;

            if (value > alpha)
            {
                if (PvNode) // Update pv even in fail-high case
                    update_pv(currentStack.pv, move, nextStack.pv);

                if (PvNode && value < beta) // Update alpha here! Always alpha < beta
                {
                    alpha = value;
                    bestMove = move;
                }
                else // Fail high
                {
                    tte.save(posKey, value_to_tt(value, currentPly), Bound.BOUND_LOWER,
                        ttDepth, move, currentStack.staticEval, TranspositionTable.generation());

                    return value;
                }
            }
        }

        // All legal moves have been searched. A special case: If we're in check
        // and no legal moves were found, it is checkmate.
        if (InCheck && bestValue == -Value.VALUE_INFINITE)
            return Value.mated_in(currentPly); // Plies to mate from the root

        tte.save(posKey, value_to_tt(bestValue, currentPly),
            PvNode && bestValue > oldAlpha ? Bound.BOUND_EXACT : Bound.BOUND_UPPER,
            ttDepth, bestMove, ss[ss.current].staticEval, TranspositionTable.generation());

        Debug.Assert(bestValue > -Value.VALUE_INFINITE && bestValue < Value.VALUE_INFINITE);

        return bestValue;
    }
Example #37
0
    /// generate
    /// QUIET_CHECKS
    ///     generates all pseudo-legal non-captures and knight
    ///     underpromotions that give check. Returns a pointer to the end of the move list.
    private static ExtMoveArrayWrapper generate_QUIET_CHECKS(Position pos, ExtMoveArrayWrapper moveList)
    {
        Debug.Assert(pos.checkers() == 0);

        var us = pos.side_to_move();
        var ci = new CheckInfo(pos);
        var dc = ci.dcCandidates;

        while (dc != 0)
        {
            var from = Utils.pop_lsb(ref dc);
            var pt = Piece.type_of(pos.piece_on(from));

            if (pt == PieceType.PAWN)
            {
                continue; // Will be generated together with direct checks
            }

            var b = pos.attacks_from_PtS(pt, from) & ~pos.pieces();

            if (pt == PieceType.KING)
            {
                b &= ~Utils.PseudoAttacks[PieceType.QUEEN, ci.ksq];
            }

            while (b != 0)
            {
                (moveList).Add(Move.make_move(from, Utils.pop_lsb(ref b)));
            }
        }

        return us == Color.WHITE
            ? generate_all(Color.WHITE, GenType.QUIET_CHECKS, pos, moveList, ~pos.pieces(), ci)
            : generate_all(Color.BLACK, GenType.QUIET_CHECKS, pos, moveList, ~pos.pieces(), ci);
    }
Example #38
0
    internal static ExtMoveArrayWrapper generate_all(
        ColorT Us,
        GenType Type,
        Position pos,
        ExtMoveArrayWrapper moveList,
        BitboardT target,
        CheckInfo ci = null)
    {
        var Checks = Type == GenType.QUIET_CHECKS;

        moveList = generate_pawn_moves(Us, Type, pos, moveList, target, ci);
        moveList = generate_moves(PieceType.KNIGHT, Checks, pos, moveList, Us, target, ci);
        moveList = generate_moves(PieceType.BISHOP, Checks, pos, moveList, Us, target, ci);
        moveList = generate_moves(PieceType.ROOK, Checks, pos, moveList, Us, target, ci);
        moveList = generate_moves(PieceType.QUEEN, Checks, pos, moveList, Us, target, ci);

        if (Type != GenType.QUIET_CHECKS && Type != GenType.EVASIONS)
        {
            var ksq = pos.square(PieceType.KING, Us);
            var b = pos.attacks_from_PtS(PieceType.KING, ksq) & target;
            while (b != 0)
            {
                (moveList).Add(Move.make_move(ksq, Utils.pop_lsb(ref b)));
            }
        }

        if (Type != GenType.CAPTURES && Type != GenType.EVASIONS && pos.can_castle(Us) != 0)
        {
            if (pos.is_chess960())
            {
                moveList = generate_castling(
                    MakeCastling(Us, CastlingSide.KING_SIDE),
                    Checks,
                    true,
                    pos,
                    moveList,
                    Us,
                    ci);
                moveList = generate_castling(
                    MakeCastling(Us, CastlingSide.QUEEN_SIDE),
                    Checks,
                    true,
                    pos,
                    moveList,
                    Us,
                    ci);
            }
            else
            {
                moveList = generate_castling(
                    MakeCastling(Us, CastlingSide.KING_SIDE),
                    Checks,
                    false,
                    pos,
                    moveList,
                    Us,
                    ci);
                moveList = generate_castling(
                    MakeCastling(Us, CastlingSide.QUEEN_SIDE),
                    Checks,
                    false,
                    pos,
                    moveList,
                    Us,
                    ci);
            }
        }

        return moveList;
    }
Example #39
0
    /// Search::perft() is our utility to verify move generation. All the leaf nodes
    /// up to the given depth are generated and counted and the sum returned.
    internal static long perft(bool Root, Position pos, Depth depth)
    {
        var st = new StateInfo();
        long nodes = 0;
        var ci = new CheckInfo(pos);
        var leaf = (depth == 2*Depth.ONE_PLY);

        var ml = new MoveList(GenType.LEGAL, pos);
        for (var index = ml.begin(); index < ml.end(); index++)
        {
            var m = ml.moveList.table[index];
            long cnt;
            if (Root && depth <= Depth.ONE_PLY_C)
            {
                cnt = 1;
                nodes++;
            }
            else
            {
                pos.do_move(m, st, pos.gives_check(m, ci));
                cnt = leaf ? new MoveList(GenType.LEGAL, pos).size() : perft(false, pos, depth - Depth.ONE_PLY);
                nodes += cnt;
                pos.undo_move(m);
            }
            if (Root)
            {
                Output.WriteLine($"{UCI.move(m, pos.is_chess960())}: {cnt}");
            }
        }
        return nodes;
    }
Example #40
0
    /// Position::gives_check() tests whether a pseudo-legal move gives a check
    internal bool gives_check(MoveT m, CheckInfo ci)
    {
        Debug.Assert(Move.is_ok(m));
        Debug.Assert(ci.dcCandidates == discovered_check_candidates());
        Debug.Assert(Piece.color_of(moved_piece(m)) == sideToMove);

        var from = Move.from_sq(m);
        var to = Move.to_sq(m);

        // Is there a direct check?
        if (Bitboard.AndWithSquare(ci.checkSquares[Piece.type_of(piece_on(from))], to)!=0)
        {
            return true;
        }

        // Is there a discovered check?
        if (ci.dcCandidates != 0 && Bitboard.AndWithSquare(ci.dcCandidates, from)!=0 && !Utils.aligned(from, to, ci.ksq))
        {
            return true;
        }

        switch (Move.type_of(m))
        {
            case MoveType.NORMAL:
                return false;

            case MoveType.PROMOTION:
                return Bitboard.AndWithSquare(Utils.attacks_bb_PSBb(Piece.Create(Move.promotion_type(m)), to, Bitboard.XorWithSquare(pieces(), from)), ci.ksq) != 0;

            // En passant capture with check? We have already handled the case
            // of direct checks and ordinary discovered check, so the only case we
            // need to handle is the unusual case of a discovered check through
            // the captured pawn.
            case MoveType.ENPASSANT:
            {
                var capsq = Square.make_square(Square.file_of(to), Square.rank_of(from));
                var b = Bitboard.OrWithSquare(Bitboard.XorWithSquare(Bitboard.XorWithSquare(pieces(), from), capsq), to);

                return ((Utils.attacks_bb_PtSBb(PieceType.ROOK, ci.ksq, b)
                        & pieces_CtPtPt(sideToMove, PieceType.QUEEN, PieceType.ROOK))
                       | (Utils.attacks_bb_PtSBb(PieceType.BISHOP, ci.ksq, b)
                          & pieces_CtPtPt(sideToMove, PieceType.QUEEN, PieceType.BISHOP))) != 0;
            }
            case MoveType.CASTLING:
            {
                var kfrom = from;
                var rfrom = to; // Castling is encoded as 'King captures the rook'
                var kto = Square.relative_square(sideToMove, rfrom > kfrom ? Square.SQ_G1 : Square.SQ_C1);
                var rto = Square.relative_square(sideToMove, rfrom > kfrom ? Square.SQ_F1 : Square.SQ_D1);

                var occupied = Bitboard.OrWithSquare(Bitboard.OrWithSquare(Bitboard.XorWithSquare(Bitboard.XorWithSquare(pieces(), kfrom), rfrom), rto), kto);
                return Bitboard.AndWithSquare(Utils.PseudoAttacks[PieceType.ROOK, rto], ci.ksq)!=0
                       && Bitboard.AndWithSquare(Utils.attacks_bb_PtSBb(PieceType.ROOK, rto, occupied), ci.ksq) !=0;
            }
            default:
                Debug.Assert(false);
                return false;
        }
    }
Example #41
0
    internal static ExtMoveArrayWrapper generate_moves(
        PieceTypeT pieceType,
        bool Checks,
        Position pos,
        ExtMoveArrayWrapper moveList,
        ColorT us,
        BitboardT target,
        CheckInfo ci)
    {
        var Pt = (int) pieceType;
        Debug.Assert(Pt != PieceType.KING && Pt != PieceType.PAWN);

        for(var idx=0; idx<16;idx++)
        {
            var square = pos.square(pieceType, us, idx);
            if (square == Square.SQ_NONE)
            {
                break;
            }

            if (Checks)
            {
                if ((Pt == PieceType.BISHOP || Pt == PieceType.ROOK || Pt == PieceType.QUEEN)
                    && (Utils.PseudoAttacks[Pt, square] & target & ci.checkSquares[Pt]) == 0)
                {
                    continue;
                }

                if (ci.dcCandidates != 0 && Bitboard.AndWithSquare(ci.dcCandidates, square)!=0)
                {
                    continue;
                }
            }

            var b = pos.attacks_from_PtS(pieceType, square) & target;

            if (Checks)
            {
                b &= ci.checkSquares[Pt];
            }

            while (b != 0)
            {
                (moveList).Add(Move.make_move(square, Utils.pop_lsb(ref b)));
            }
        }

        return moveList;
    }