Beispiel #1
0
        private static void Main(string[] args)
        {
            var numRegisters            = int.Parse(args[0]);
            var numStatements           = int.Parse(args[1]);
            var percentBranches         = double.Parse(args[2]);
            var maxInitialRegisterValue = int.Parse(args[3]);
            var secondsUntilForceQuit   = int.Parse(args[4]);
            var chunkSize = int.Parse(args[5]);

            var historyTable = new HistoryTable <SaturatingCounter>(() => new SaturatingCounter(), numStatements, chunkSize);
            var program      = new Program <SaturatingCounter>(historyTable, numRegisters, numStatements, percentBranches,
                                                               maxInitialRegisterValue, secondsUntilForceQuit);

            while (program.ExecuteNext())
            {
            }

            Console.WriteLine($"Statements Executed: {program.Statistics.StatementsExecuted}");
            Console.WriteLine($"Branches Executed: {program.Statistics.BranchesExecuted}");
            Console.WriteLine($"Accuracy: {program.Statistics.Accuracy}");
            Console.Write("Writing statistics to \"output/statistics.json\"...");
            var json = JsonConvert.SerializeObject(program.Statistics);

            File.WriteAllText("output/statistics.json", json);
            Console.WriteLine(" done!");
        }
 public override void ViewWillAppear(bool animated)
 {
     base.ViewWillAppear(animated);
     coreData.AddRange(data);
     HistoryTable.ReloadData();
     data.Clear(); // make sure to clear so it doesn't add same calculation next time
 }
Beispiel #3
0
    public void LoadUsersTable()
    {
        string               currentLanguage   = ConfigurationManager.AppSettings["language"];
        string               connectionString  = ConfigurationSettings.AppSettings["fleetnetbaseConnectionString"];
        DataBlock            dataBlock         = new DataBlock(connectionString, currentLanguage);
        HistoryTable         historyTable      = new HistoryTable(connectionString, currentLanguage, dataBlock.sqlDb);
        int                  orgId             = Convert.ToInt32(Session["CURRENT_ORG_ID"]);
        List <int>           usersIds          = new List <int>();
        List <UserFromTable> userFromTableList = new List <UserFromTable>();

        dataBlock.OpenConnection();//выборка по типам пользователей
        usersIds.AddRange(dataBlock.usersTable.Get_AllUsersId(orgId, dataBlock.usersTable.DriverUserTypeId));
        usersIds.AddRange(dataBlock.usersTable.Get_AllUsersId(orgId, dataBlock.usersTable.AdministratorUserTypeId));
        usersIds.AddRange(dataBlock.usersTable.Get_AllUsersId(orgId, dataBlock.usersTable.ManagerUserTypeId));
        DataTable data = historyTable.GetAllHistorysForUsers(usersIds);

        LogDataGrid.DataSource = data;
        LogDataGrid.DataBind();

        List <KeyValuePair <string, int> > actions = historyTable.GetAllActions();

        LogFilterTable_EventDropDown.Items.Clear();

        LogFilterTable_EventDropDown.Items.Add(new ListItem("Все", "-1", true));
        foreach (KeyValuePair <string, int> action in actions)
        {
            LogFilterTable_EventDropDown.Items.Add(new ListItem(action.Key, action.Value.ToString()));
        }

        dataBlock.CloseConnection();
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="RegularSearch"/> class.
 /// </summary>
 /// <param name="transpositionTable">The transposition table.</param>
 /// <param name="historyTable">The history table.</param>
 /// <param name="killerTable">The killer table.</param>
 public RegularSearch(TranspositionTable transpositionTable, HistoryTable historyTable, KillerTable killerTable)
 {
     _transpositionTable = transpositionTable;
     _historyTable       = historyTable;
     _killerTable        = killerTable;
     _quiescenceSearch   = new QuiescenceSearch();
     _patternsDetector   = new PatternsDetector();
 }
 public ActionResult Edit(HistoryTable historyTable)
 {
     if (ModelState.IsValid && historyTable != null)
     //if (ModelState.IsValid)
     {
         _db.Create(historyTable);
         return(RedirectToAction("ShowDataBaseForUser"));
     }
     return(View());
 }
Beispiel #6
0
        private void HelperTask(HelperTaskParameters param)
        {
            var historyTable = new HistoryTable();
            var killerTable  = new KillerTable();
            var helperSearch = new RegularSearch(_transpositionTable, historyTable, killerTable);

            killerTable.SetInitialDepth(param.InitialDepth);

            helperSearch.Do(param.Color, param.Bitboard, param.InitialDepth, AIConstants.InitialAlphaValue, AIConstants.InitialBetaValue, param.Deadline, true, new AIStats());
        }
        public void Create_CallTestFromEdit()
        {
            HistoryTable historyTable = new HistoryTable();

            var analyzer = new RegisterControllerTests();
            var sut      = analyzer.Edit(historyTable);

            analyzer.ClassStub
            .Received(1)
            .Create(historyTable);
        }
Beispiel #8
0
        public void Update()
        {
            // check if data-base is already up-to-date.
            if (HistoryTable.Rows.Count > 0 && GlobalTable.Rows.Count > 0 &&
                GlobalTable.Rows[0]["LastUpdate"] != DBNull.Value &&
                ((DateTime)GlobalTable.Rows[0]["LastUpdate"]).ToShortDateString() == DateTime.Now.ToShortDateString())
            {
                return;
            }

            // get stock's option list
            ArrayList list = null;

            // clear data-set
            Clear();

            list = Comm.Server.GetHistoricalData(symbol, DateTime.Now.AddYears(-2), DateTime.Now);
            if (list == null || list.Count == 0)
            {
                return;
            }

            // begin updating data
            HistoryTable.BeginLoadData();
            GlobalTable.BeginLoadData();

            // clear data-set
            Clear();

            foreach (History history in list)
            {
                // add option to table
                AddHistoryEntry(history);
            }

            // update time-stamp
            DataRow row = GlobalTable.NewRow();

            row["Symbol"]     = symbol;
            row["LastUpdate"] = DateTime.Now;
            GlobalTable.Rows.Add(row);

            // accept changes
            GlobalTable.AcceptChanges();
            HistoryTable.AcceptChanges();

            // end updating data
            GlobalTable.EndLoadData();
            HistoryTable.EndLoadData();

            // save history data-base
            Save();
        }
        public void Edit_Model_ShouldReturnView()
        {
            //arrange
            var controller   = new RegisterController(ClassStub);
            var historyTable = new HistoryTable();
            //act
            var result = controller.Edit(historyTable) as RedirectToRouteResult;

            //assert
            Assert.That(result, Is.TypeOf(typeof(RedirectToRouteResult)));
            Assert.IsNotNull(result);
        }
        public void Edit_NullModel_ShouldReturnView()
        {
            //arrange
            HistoryTable historyTable = null;
            var          controller   = new RegisterController(ClassStub);
            //int id = 1;
            //act
            var result = controller.Edit(historyTable);

            //assert
            Assert.That(result, Is.TypeOf(typeof(ViewResult)));
        }
Beispiel #11
0
        async void TimerButtonClicked(object sender, System.EventArgs e)
        {
            //IconRotation();
            TimerButton.IsEnabled = false;
            Button button = (Button)sender;
            await button.ScaleTo(0.8f, 80, Easing.BounceOut);

            await button.ScaleTo(1, 80, Easing.BounceOut);

            if (TimerButton.BackgroundColor == App.MC && Read == false)
            {
                var HT = new HistoryTable
                {
                    User    = App.LoggedinUser.ID,
                    Article = ArticleNR,
                    Readat  = DateTime.Now,
                    Header  = Rubrik.Text,
                    Image   = ArticleImage.Source.ToString()
                };
                App.database.InsertHistory(HT);
                TimerIcon.Source      = "Icon_Coin.png";
                TimerButton.Text      = "";
                TimerButton.IsVisible = false;
                TimerButton.TextColor = Color.White;
                var NG = (NewsGridPage)App.Mainpage.Children[1];
                foreach (NewsGridPage.Article A in NG.ArticleList)
                {
                    if (A.ID == ArticleNR)
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            //A.CheckImage.Source = "checkmark.png";

                            //A.CornerImage.Source = "plusBackground.png";

                            //A.Box.Color = Color.FromRgb(80, 210, 194);
                            //A.Image.Margin = 6;
                        });
                    }
                }
                App.database.Plustoken(App.LoggedinUser, 1);
                Read = true;
                TimerButton.IsEnabled = false;

                var variable = (ProfilePage)App.Mainpage.Children[2];
                variable.TokenNumber.Text = App.LoggedinUser.Plustokens.ToString();
            }
            else
            {
                TimerButton.IsEnabled = true;
            }
        }
 public void ExitProgram()
 {
     HistoryTable.SaveList();
     try
     {
         this._amaThread.Abort();
     }
     catch { }
     finally
     {
         Application.Current.Shutdown();
     }
 }
Beispiel #13
0
 private void PopulateGrid()
 {
     try
     {
         HistoryTable.update();
         this.labelHeader.Content = "Session history as of " + DateTime.Now.ToLongTimeString();
         var history = HistoryTable.getHistoryList();
         this.dataGridHistory.ItemsSource = history;
     }
     catch
     {
         this.labelHeader.Content = "Could not fetch history. Refreshed: " + DateTime.Now.ToLongTimeString();
     }
 }
Beispiel #14
0
    protected void InvoicesTab_PayInvoiceButton_Click(object sender, EventArgs e)
    {
        string    currentLanguage  = ConfigurationManager.AppSettings["language"];
        string    connectionString = ConfigurationSettings.AppSettings["fleetnetbaseConnectionString"];
        DataBlock dataBlock        = new DataBlock(connectionString, currentLanguage);

        try
        {
            dataBlock.OpenConnection();
            dataBlock.OpenTransaction();
            int curUserId = dataBlock.usersTable.Get_UserID_byName(Page.User.Identity.Name);
            int invoiceId = Convert.ToInt32(Selected_InvoicesDataGrid_Index.Value);

            //old version

            /*  dataBlock.invoiceTable.OpenConnection();
             * dataBlock.invoiceTable.OpenTransaction();
             * dataBlock.invoiceTable.PayABill(invoiceId);
             * string invoiceName = dataBlock.invoiceTable.GetInvoiceName(invoiceId);
             * dataBlock.invoiceTable.CommitTransaction();
             * dataBlock.invoiceTable.CloseConnection();*/

            //test version
            dataBlock.invoiceTable.PayABill(invoiceId);
            string invoiceName = dataBlock.invoiceTable.GetInvoiceName(invoiceId);
            dataBlock.CommitTransaction();
            dataBlock.CloseConnection();
            //

            LoadInvoicesTable();
            InvoicesDataGridUpdatePanel.Update();
            InvoicesTab_ButtonsUpdateTable.Update();
            ////    добавление записи в журнал. потом возможно перенести куда надо(в логику).
            DB.SQL.SQLDB sqlDb   = new DB.SQL.SQLDB(connectionString);
            HistoryTable history = new HistoryTable(connectionString, currentLanguage, sqlDb);
            sqlDb.OpenConnection();
            history.AddHistoryRecord("FN_INVOICE", "INVOICE_STATUS_ID", dataBlock.invoiceTable.Status_Paid, curUserId, history.invoicePaid, "#" + invoiceId + @" :""" + invoiceName + @"""", sqlDb);
            sqlDb.CloseConnection();
            ////
        }
        catch (Exception ex)
        {
            dataBlock.invoiceTable.RollbackConnection();
            dataBlock.invoiceTable.CloseConnection();
            RaiseException(ex);
        }
    }
        public Program(HistoryTable <T> historyTable, int numRegisters = 4, int numStatements = 1000,
                       double percentBranches = 0.15, int maxInitialRegisterValue             = 50, int secondsUntilForceQuit = 60)
        {
            _random       = new Random();
            _historyTable = historyTable;

            if (numRegisters < 4)
            {
                numRegisters = 4;
            }

            if (numStatements < 100)
            {
                numStatements = 100;
            }

            if (percentBranches > 1.0)
            {
                percentBranches = 1.0;
            }
            else if (percentBranches < 0.05)
            {
                percentBranches = 0.05;
            }

            _numRegisters            = numRegisters;
            _numStatements           = numStatements;
            _numBranches             = (int)(_numStatements * percentBranches);
            _numOperations           = _numStatements - _numBranches;
            _maxInitialRegisterValue = maxInitialRegisterValue;
            _secondsUntilForceQuit   = secondsUntilForceQuit;

            Statistics = new ProgramExecutionStatistics
            {
                NumStatements           = _numStatements,
                NumBranches             = _numBranches,
                NumRegisters            = _numRegisters,
                MaxInitialRegisterValue = _maxInitialRegisterValue
            };

            for (var i = 0; i < _numRegisters; i++)
            {
                _registers.Add(new Register(i, _random.Next(_maxInitialRegisterValue)));
            }
            Initialize();
        }
Beispiel #16
0
        async void TimerButtonClicked(object sender, System.EventArgs e) // When the Timer button is clicked, a history object for that user is sent to the server to be stored.
        {
            TimerButton.IsEnabled = false;
            Button button = (Button)sender;
            await button.ScaleTo(0.8f, 80, Easing.BounceOut);

            await button.ScaleTo(1, 80, Easing.BounceOut);

            if (TimerButton.BackgroundColor == App.MC && Read == false)
            {
                var HT = new HistoryTable
                {
                    User    = App.LoggedinUser.ID,
                    Article = ArticleNR,
                    Readat  = DateTime.Now,
                    Header  = Rubrik.Text,
                    Image   = ArticleImage.Source.ToString()
                };
                App.database.InsertHistory(HT);
                TimerIcon.Source      = "Icon_Coin.png";
                TimerButton.Text      = "";
                TimerButton.IsVisible = false;
                TimerButton.TextColor = Color.White;
                var NG = (NewsGridPage)App.Mainpage.Children[1];
                foreach (NewsGridPage.Article A in NG.ArticleList)
                {
                    if (A.ID == ArticleNR)
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            //Article is Locked.
                        });
                    }
                }
                App.database.Plustoken(App.LoggedinUser, 1);
                Read = true;
                TimerButton.IsEnabled = false;
                var variable = (ProfilePage)App.Mainpage.Children[2];
                variable.TokenNumber.Text = App.LoggedinUser.Plustokens.ToString();
            }
            else
            {
                TimerButton.IsEnabled = true;
            }
        }
Beispiel #17
0
    private void buildHistoryTable()
    {
        SqlDataReader        reader;
        SqlCommand           cmd;
        String               query;
        List <historyResult> historyTableList = new List <historyResult>();
        historyResult        tableEntry;

        try
        {
            connection.Open();

            query  = String.Format(@"SELECT        QuizzesTaken.dateTaken, QuizList.quizType, QuizzesTaken.numberOfQuestions, QuizzesTaken.percentageCorrect, QuizzesTaken.averageTime
                      FROM            QuizzesTaken INNER JOIN
                         QuizList ON QuizzesTaken.quizID = QuizList.quizID
                      WHERE        (QuizzesTaken.userID = '{0}')
                      ORDER BY QuizzesTaken.dateTaken DESC", userID);
            cmd    = new SqlCommand(query, connection);
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                tableEntry                   = new historyResult();
                tableEntry.time              = Convert.ToDateTime(reader[0]);
                tableEntry.quizType          = (String)reader[1];
                tableEntry.numberOfQuestions = (int)reader[2];
                tableEntry.percentage        = (float)Convert.ToDouble(reader[3]);
                tableEntry.averageTime       = (float)Convert.ToDouble(reader[4]);
                historyTableList.Add(tableEntry);
            }
            if (reader != null)
            {
                reader.Close();
            }
        }
        finally
        {
            if (connection != null)
            {
                connection.Close();
            }
        }

        HistoryTable.DataSource = historyTableList;
        HistoryTable.DataBind();
    }
Beispiel #18
0
        /// <summary>
        /// XmlElementからHistoryTable情報を取得する
        /// element例:
        /// <HistoryProject>
        ///   <List>
        ///     <string>D:\src\krkr\game\abyss\trial\trunk\abyss.krkrproj</string>
        ///      <string>C:\Users\mry\Desktop\AAA\AAA.krkrproj</string>
        ///   </List>
        ///   <MaxCount>8</MaxCount>
        /// </HistoryProject>
        /// </summary>
        /// <param name="historyTableElement"></param>
        /// <returns></returns>
        private static HistoryTable getHistoryTableFromXmlElement(XmlElement historyTableElement)
        {
            HistoryTable table = new HistoryTable();

            foreach (XmlElement element in historyTableElement.ChildNodes)
            {
                switch (element.Name)
                {
                case "List":
                    table.List = getStringListFromXmlElement(element);
                    break;

                case "MaxCount":
                    table.MaxCount = Int32.Parse(element.InnerText);
                    break;
                }
            }

            return(table);
        }
Beispiel #19
0
        private void AddHistoryEntry(History history)
        {
            bool    new_row = false;
            DataRow row;

            if (!HistoryTable.Rows.Contains(history.date))
            {
                row     = HistoryTable.NewRow();
                new_row = true;

                try
                {
                    row["Date"] = history.date;
                }
                catch { }
            }
            else
            {
                row = HistoryTable.Rows.Find(history.date);
                row.BeginEdit();
            }

            try
            {
                row["AdjClose"] = history.price.close_adj;
            }
            catch { }
            try
            {
                row["Close"] = history.price.close;
            }
            catch { }
            try
            {
                row["Open"] = history.price.open;
            }
            catch { }
            try
            {
                row["High"] = history.price.high;
            }
            catch { }
            try
            {
                row["Low"] = history.price.low;
            }
            catch { }
            try
            {
                row["Volume"] = history.volume.total;
            }
            catch { }

            try
            {
                // add row to table (if new)
                if (new_row)
                {
                    HistoryTable.Rows.Add(row);
                }
            }
            catch { }
        }
Beispiel #20
0
        public static void InitializeTable()
        {
            SiteTable = getTable("sites1");
            if (SiteTable != null)
            {
                SiteTable.CreateIfNotExists();
            }
            //
            TemporalTable = getTable("temporal1");
            if (TemporalTable != null)
            {
                TemporalTable.CreateIfNotExists();
            }

            RevisionTable = getTable("revision1");
            if (RevisionTable != null)
            {
                RevisionTable.CreateIfNotExists();
            }

            ImagesContainer = getContainer("images1");

            SelectionListTable = getTable("selectionlist1");
            if (SelectionListTable != null)
            {
                SelectionListTable.CreateIfNotExists();
                SelectionInfoStore.CreateSkeleton();
            }

            HistoryTable = getTable("history1");
            if (HistoryTable != null)
            {
                HistoryTable.CreateIfNotExists();
            }

            BoardListTable = getTable("boardlist1");
            if (BoardListTable != null)
            {
                BoardListTable.CreateIfNotExists();
                BoardInfoStore.CreateSkeleton();
            }

            DiscussionListTable = getTable("discussionlist1");
            if (DiscussionListTable != null)
            {
                DiscussionListTable.CreateIfNotExists();
            }

            KeyStoreTable = getTable("keystore1");
            if (KeyStoreTable != null)
            {
                KeyStoreTable.CreateIfNotExists();
            }

            ActivityTable = getTable("activity1");
            if (ActivityTable != null)
            {
                ActivityTable.CreateIfNotExists();
            }

            DiscussionLoadTable = getTable("discussionload1");
            if (DiscussionLoadTable != null)
            {
                DiscussionLoadTable.CreateIfNotExists();
            }

            VoteBookTable = getTable("votebook1");
            if (VoteBookTable != null)
            {
                VoteBookTable.CreateIfNotExists();
            }
        }
Beispiel #21
0
        /// <summary>
        /// Calculates the best possible move for the specified parameters.
        /// </summary>
        /// <param name="color">The initial player.</param>
        /// <param name="bitboard">The bitboard.</param>
        /// <param name="preferredTime">Time allocated for AI.</param>
        /// <param name="helperTasks">The helper tasks count (0 for single thread).</param>
        /// <returns>The result of AI calculating.</returns>
        public AIResult Calculate(Color color, Bitboard bitboard, float preferredTime, int helperTasks)
        {
            var result    = new AIResult();
            var colorSign = ColorOperations.ToSign(color);
            var stopwatch = new Stopwatch();
            int estimatedTimeForNextIteration;

            var historyTable  = new HistoryTable();
            var killerTable   = new KillerTable();
            var regularSearch = new RegularSearch(_transpositionTable, historyTable, killerTable);

            result.Color         = color;
            result.PreferredTime = preferredTime;

            var deadline = preferredTime != 0 ? DateTime.Now.AddSeconds(preferredTime * 2).Ticks : DateTime.Now.AddSeconds(1).Ticks;

            historyTable.Clear();
            killerTable.Clear();

            if (bitboard.ReversibleMoves == 0 && preferredTime > 0)
            {
                _transpositionTable.Clear();
            }

            stopwatch.Start();
            do
            {
                result.Depth++;

                killerTable.SetInitialDepth(result.Depth);

                if (result.Depth >= AIConstants.MinimalDepthToStartHelperThreads)
                {
                    for (var i = 0; i < helperTasks; i++)
                    {
                        var param = new HelperTaskParameters
                        {
                            Bitboard     = new Bitboard(bitboard),
                            Color        = color,
                            Deadline     = deadline,
                            InitialDepth = result.Depth
                        };

                        Task.Run(() => HelperTask(param));
                    }
                }

                var stats = new AIStats();
                var score = colorSign * regularSearch.Do(color, new Bitboard(bitboard), result.Depth, AIConstants.InitialAlphaValue, AIConstants.InitialBetaValue, deadline, false, stats);

                if (DateTime.Now.Ticks <= deadline)
                {
                    result.PVNodes = GetPVNodes(bitboard, color);
                    result.Score   = score;

                    OnThinkingOutput?.Invoke(this, new ThinkingOutputEventArgs(result));
                }
                else
                {
                    result.Depth--;
                    _transpositionTable.Clear();
                }

                result.Stats = stats;
                result.Ticks = stopwatch.Elapsed.Ticks;

                estimatedTimeForNextIteration = (int)stopwatch.Elapsed.TotalMilliseconds * result.Stats.BranchingFactor;
            }while (estimatedTimeForNextIteration < preferredTime * 1000 &&
                    result.Depth < AIConstants.MaxDepth &&
                    Math.Abs(result.Score) != AIConstants.MateValue);

            return(result);
        }
Beispiel #22
0
    //This function is called each time it is your turn
    //Return true to end your turn, return false to ask the server for updated information
    public override bool run()
    {
        // Print out the current board state
        Console.WriteLine("+---+---+---+---+---+---+---+---+");
        for (int rank = 8; rank > 0; rank--)
        {
            Console.Write("|");
            for (int file = 1; file <= 8; file++)
            {
                bool found = false;
                // Loops through all of the pieces
                for (int p = 0; !found && p < pieces.Length; p++)
                {
                    // determines if that piece is at the current rank and file
                    if (pieces[p].getRank() == rank && pieces[p].getFile() == file)
                    {
                        found = true;
                        // Checks if the piece is black
                        if (pieces[p].getOwner() == 1)
                        {
                            Console.Write("*");
                        }
                        else
                        {
                            Console.Write(" ");
                        }
                        // prints the piece's type
                        Console.Write((char)pieces[p].getType() + " ");
                    }
                }
                if (!found)
                {
                    Console.Write("   ");
                }
                Console.Write("|");
            }
            Console.WriteLine("\n+---+---+---+---+---+---+---+---+");
        }

        // Looks through information about the players
        for (int p = 0; p < players.Length; p++)
        {
            Console.Write(players[p].getPlayerName());
            // if playerID is 0, you're white, if its 1, you're black
            if (players[p].getId() == myID)
            {
                Console.Write(" (ME)");

                // update timeRemaining
                timeRemaining = players[p].getTime();
            }
            Console.WriteLine(" time remaining: " + players[p].getTime());
        }

        // if there has been a move, print the most recent move
        if (moves.Length > 0)
        {
            Console.Write("Last Move Was: ");
            Console.WriteLine(files[moves[0].getFromFile() - 1] + "" + moves[0].getFromRank() + "-" + files[moves[0].getToFile() - 1] + "" + moves[0].getToRank());
        }

        /////////////////////////////////////
        // <-- END OF STOCK AI.cs CODE --> //
        /////////////////////////////////////

        // print current move number
        Console.WriteLine("\nMove " + turnNumber().ToString("D3") + "\n========\n");

        // add to GameState List and update ChessBoard
        if (moves.Length <= 1)
        {
            board = new ChessBoard(ref pieces, myID);
            states.Add(new GameState(null, null));
        }
        else
        {
            ChessMove lastMove = ChessMove.GetChessMove(moves[0].getFromFile(), moves[0].getToFile(), moves[0].getFromRank(), moves[0].getToRank(),
                                                        moves[0].getPromoteType(), states[states.Count - 1].enPassant);
            board = new ChessBoard(ref pieces, myID);
            states.Add(new GameState(states[states.Count - 1], lastMove));
        }

        // display current score information for player
        Console.Write("Score for ");
        if (myID == ChessBoard.WHITE)
        {
            Console.WriteLine("WHITE:\n");
        }
        else if (myID == ChessBoard.BLACK)
        {
            Console.WriteLine("BLACK:\n");
        }
        int material = Score.GetMaterialScore(myID);
        int position = Score.GetPositionScore(myID);
        // int mobility = Score.GetPositionScore(myID);
        int pawn_structure = Score.GetPawnStructureScore(myID);
        int king_safety    = Score.GetKingSafetyScore(myID);

        Console.WriteLine("Net Material = " + material);
        Console.WriteLine("Net Position = " + position);
        //Console.WriteLine("Net Mobility = " + mobility);
        Console.WriteLine("Net Pawn Structure = " + pawn_structure);
        Console.WriteLine("Net King Safety = " + king_safety + "\n");
        Console.WriteLine("Overall Score = " + (material + position + /*mobility +*/ pawn_structure + king_safety) + "\n");

        // if playing as human, get move from console prompt
        while (HUMAN_PLAYER)
        {
            // get legal moves for this position
            List <ChessMove> legalMoves = MoveGen.GenerateMoves(myID, false);

            // prompt user for move
            Console.Write("Enter a move ([from] [to] <promotion type>): ");
            string[] humanMove = Console.ReadLine().Split(' ');

            // get origin square
            int humanFromFile = 0, humanFromRank = 0;
            for (int i = 0; i < 8; i++)
            {
                if (humanMove[0][0] == files[i])
                {
                    humanFromFile = i + 1;
                    break;
                }
            }
            humanFromRank = (int)Char.GetNumericValue(humanMove[0][1]);

            // get destination square
            int humanToFile = 0, humanToRank = 0;
            for (int i = 0; i < 8; i++)
            {
                if (humanMove[1][0] == files[i])
                {
                    humanToFile = i + 1;
                    break;
                }
            }
            humanToRank = (int)Char.GetNumericValue(humanMove[1][1]);

            // if promotion type is specified, get the promotion piece from move
            int humanPromote = 0;
            if (humanMove.Length > 2)
            {
                humanPromote = (int)humanMove[2][0];
            }

            // check for legality of human move
            bool isLegal = false;
            for (int i = 0; i < legalMoves.Count; i++)
            {
                ChessMove m = legalMoves[i];
                if ((ChessMove.GetFile(m.GetFromSq()) + 1) == (uint)humanFromFile &&
                    (ChessMove.GetRank(m.GetFromSq()) + 1) == (uint)humanFromRank &&
                    (ChessMove.GetFile(m.GetToSq()) + 1) == (uint)humanToFile &&
                    (ChessMove.GetRank(m.GetToSq()) + 1) == (uint)humanToRank)
                {
                    isLegal = true;
                    break;
                }
            }

            // if move is legal, make move
            if (isLegal)
            {
                // get Piece associated with move
                Piece humanPiece = pieces[FindPiece(humanFromFile, humanFromRank)];

                // make move
                humanPiece.move(humanToFile, humanToRank, humanPromote);
                return(true);
            }
            else if (!isLegal)
            {
                Console.WriteLine("ILLEGAL MOVE. Please input a legal move.\n");
            }
        }

        // reset TIME_EXPIRED and timer
        TIME_EXPIRED = false;
        timer.Reset();

        // reset history table
        history = new HistoryTable();

        // run ABMiniMax
        int  moveScore = 0, n = 0, toFile = -1, toRank = -1;
        uint fromSq = 0, toSq = 0, thePiece = 0;

        depth = 0;
        List <ChessMove> completeBestMoves = new List <ChessMove>(0);

        Search.UpdateTimePerMove(moves.Length);
        timer.Start();
        while (!TIME_EXPIRED)
        {
            depth                  += 1;
            nodes                   = 0;
            Search.MAX_DEPTH        = depth;
            Search.NULLMOVE_ALLOWED = true;
            Search.FOLLOW_PV        = true;
            Search.PV               = new List <ChessMove>(0);
            int score = Search.PVABMiniMax(0, Search.SMALL_NUM, Search.LARGE_NUM);
            if (score != Score.TIME_EXPIRED_SCORE)
            {
                moveScore         = score;
                completeBestMoves = new List <ChessMove>(Search.PV);
            }

            // select random move from bestMoves List
            if (completeBestMoves.Count > 0)
            {
                n = generator.Next(0, completeBestMoves.Count - 1);

                // get bestMove info
                fromSq   = completeBestMoves[n].GetFromSq();
                thePiece = completeBestMoves[n].GetPiece();
                toSq     = completeBestMoves[n].GetToSq();
                toFile   = (int)((toSq % 8) + 1);
                toRank   = (int)((toSq / 8) + 1);

                // print bestMove info
                Console.WriteLine("Best Move: " + completeBestMoves[n].GetMoveString() + ", Score: " + moveScore + ", Depth: " + depth + " (t = " +
                                  (timer.ElapsedMilliseconds / 1000.0).ToString("F3") + "s, nodes = " + nodes + ")");
            }

            // if checkmate is found, stop searching
            if (score == Score.CHECKMATE_WIN_SCORE)
            {
                break;
            }
        }
        timer.Stop();

        // output number of best moves
        Console.WriteLine("completeBestMoves = " + completeBestMoves.Count);

        // make bestMove
        pieces[FindPiece(fromSq, thePiece)].move(toFile, toRank, completeBestMoves[n].GetPromoteType());

        // update ChessBoard and GameState List
        completeBestMoves[n].DoMove(Search.MAKE);

        return(true);
    }
 public override void ViewWillAppear(bool animated)
 {
     base.ViewWillAppear(animated);
     coreData.AddRange(data);
     HistoryTable.ReloadData();
 }
Beispiel #24
0
    protected void ApplyLogFilterButton_Click(object sender, EventArgs e)
    {
        string       currentLanguage  = ConfigurationManager.AppSettings["language"];
        string       connectionString = ConfigurationSettings.AppSettings["fleetnetbaseConnectionString"];
        DataBlock    dataBlock        = new DataBlock(connectionString, currentLanguage);
        HistoryTable historyTable     = new HistoryTable(connectionString, currentLanguage, dataBlock.sqlDb);

        try
        {
            int                  orgId             = Convert.ToInt32(Session["CURRENT_ORG_ID"]);
            List <int>           usersIds          = new List <int>();
            List <UserFromTable> userFromTableList = new List <UserFromTable>();
            DateTime             from;
            DateTime             to;
            if (DateTime.TryParse(LogFilterTable_StartDateTextBox.Text, out from))
            {
                if (LogFilterTable_StartTimeTextBox.Text != "")
                {
                    from = from.Add(TimeSpan.Parse(LogFilterTable_StartTimeTextBox.Text));
                }
            }
            else
            {
                from = new DateTime();
            }
            if (DateTime.TryParse(LogFilterTable_EndDateTextBox.Text, out to))
            {
                if (LogFilterTable_EndTimeTextBox.Text != "")
                {
                    to = to.Add(TimeSpan.Parse(LogFilterTable_EndTimeTextBox.Text));
                }
                else
                {
                    to = to.AddHours(23);
                    to = to.AddMinutes(59);
                }
            }
            else
            {
                to = DateTime.Now;
            }

            int    actionId     = Convert.ToInt32(LogFilterTable_EventDropDown.SelectedValue);
            string searchString = LogFilterTable_NoteTextTextBox.Text.Trim();

            dataBlock.OpenConnection();//выборка по типам пользователей
            usersIds.AddRange(dataBlock.usersTable.Get_AllUsersId(orgId, dataBlock.usersTable.DriverUserTypeId));
            usersIds.AddRange(dataBlock.usersTable.Get_AllUsersId(orgId, dataBlock.usersTable.AdministratorUserTypeId));
            usersIds.AddRange(dataBlock.usersTable.Get_AllUsersId(orgId, dataBlock.usersTable.ManagerUserTypeId));
            DataTable data = historyTable.GetAllHistorysForUsers(usersIds, from, to, actionId, searchString);
            LogDataGrid.DataSource = data;
            LogDataGrid.DataBind();

            dataBlock.CloseConnection();
        }
        catch (Exception ex)
        {
        }
        finally
        {
            dataBlock.CloseConnection();
        }
    }
Beispiel #25
0
 private static void writeXmlHistoryTable(XmlTextWriter xw, HistoryTable historyTable)
 {
     //リスト書き込み
     writeXmlStringList(xw, historyTable.List);
     writeElement(xw, "MaxCount", historyTable.MaxCount);
 }