Esempio n. 1
0
        private void openButton_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog()
            {
                Filter = "REVファイル|*.rev|すべてのファイル|*.*"
            };

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    record = MatchRecord.FromFile(dialog.FileName);
                    var source = new BindingSource();
                    source.DataSource = record.Boards;
                    bindingNavigator1.BindingSource = source;
                    turnNum = Convert.ToInt32(bindingNavigatorPositionItem.Text);
                    board   = record.Boards[turnNum - 1];
                    RefreshTurnLabel();
                    RefreshPanel();
                    inPlayback = true;
                }
                catch
                {
                    MessageBox.Show("ファイルが不正です。");
                }
            }
        }
        public double GetMatchWinOdds(MatchRecord match)
        {
            double winnerSalt = match.WinnerSalt;
            double loserSalt  = match.LoserSalt;

            return(winnerSalt / loserSalt);
        }
Esempio n. 3
0
        public void OnSave_WhenNoMatchesExist_CreatesNewMatch_AsAWin_AndDifferenceAsCR()
        {
            // Arrange
            RecordMatchViewModel vm = new RecordMatchViewModel(_profileManager, _mockDialogService.Object);

            _profileManager.OpenProfile(_emptyProfile.Name);

            string map = vm.Maps[1];

            vm.SelectedMap = map;

            int newCR = 2000;

            vm.CR = newCR;

            // Act
            vm.SaveCommand.Execute(null);

            // Assert
            Assert.AreEqual(1, _emptyProfile.MatchHistory.Count());

            MatchRecord newRecord = _emptyProfile.MatchHistory.LastMatch;

            Assert.AreEqual(newCR, newRecord.CR);
            Assert.AreEqual(newCR, newRecord.Diff);
            Assert.AreEqual(MatchResult.WIN, newRecord.Result);
            Assert.AreEqual(map, newRecord.Map);
        }
Esempio n. 4
0
        public void OnSave_WhenAtLeastOneMatchExists_CreatesNewMatch_WithResultRelativeToLastResult()
        {
            // Arrange
            RecordMatchViewModel vm = new RecordMatchViewModel(_profileManager, _mockDialogService.Object);
            string map = vm.Maps[1];

            vm.SelectedMap = map;

            int newCR = 2000;

            vm.CR = newCR;

            int previousCR   = _defaultProfile.MatchHistory.LastMatch.CR;
            int currentCount = _defaultProfile.MatchHistory.Count();

            // Act
            vm.SaveCommand.Execute(null);

            // Assert
            Assert.AreEqual(currentCount + 1, _defaultProfile.MatchHistory.Count());

            MatchRecord newRecord = _defaultProfile.MatchHistory.LastMatch;

            Assert.AreEqual(newCR, newRecord.CR);
            Assert.AreEqual(newCR - previousCR, newRecord.Diff);
            Assert.AreEqual(MatchResult.WIN, newRecord.Result);
            Assert.AreEqual(map, newRecord.Map);
        }
        private static IEnumerable <MatchRecord> GetRecords()
        {
            TimeSpan           interval = TimeSpan.FromMinutes(18);
            List <MatchRecord> records  = new List <MatchRecord>();

            Random      rand           = new Random();
            int         SR             = rand.Next(1500, 2500);
            MatchRecord previousRecord = new MatchRecord()
            {
                CR     = SR,
                Date   = DateTime.Now,
                Diff   = SR,
                Map    = RandomMap(rand),
                Result = MatchResult.WIN
            };

            records.Add(previousRecord);

            for (int i = 0; i <= 499; i++)
            {
                int         newSR     = previousRecord.CR + (rand.Next(15, 30) * SRChangeModifier(rand));
                MatchRecord newRecord = previousRecord.NewRelativeRecord(newSR, previousRecord.Date.Add(interval), RandomMap(rand));
                records.Add(newRecord);
                previousRecord = newRecord;
            }

            return(records);
        }
        private async void Save()
        {
            var lastMatch = MatchHistory.LastMatch;

            MatchRecord newMatch;

            if (lastMatch != null)
            {
                newMatch = lastMatch.NewRelativeRecord(CR.Value, DateTime.Now, SelectedMap);
            }
            else
            {
                await _dialogService.ShowMessage("Recording first game as a win, because there are no previous records to base it on", "Recording new match");

                newMatch = new MatchRecord()
                {
                    CR     = CR.Value,
                    Diff   = CR.Value,
                    Date   = DateTime.Now,
                    Map    = SelectedMap,
                    Result = MatchResult.WIN
                };
            }


            MatchHistory.Add(newMatch);
            MessengerInstance.Send(new Messages.NewMatchRecord(newMatch));

            CR          = null;
            SelectedMap = Maps.First();
        }
        public void AddMatchOutcome(Outcome _outcome, int _gameScore, int _pointsScore, bool _isAddition)
        {
            int add = (_isAddition) ? 1 : -1;

            MatchRecord.AddOutcome(_outcome, _isAddition);
            GameScore   += (_gameScore * add);
            PointsScore += (_pointsScore * add);
        }
Esempio n. 8
0
 public void Add(MatchRecord record)
 {
     using (var writer = Writer())
     {
         writer.WriteRecord(record);
         writer.NextRecord();
         Records.Add(record);
     }
 }
Esempio n. 9
0
 public void Insert(MatchRecord match)
 {
     using (LiteDatabase db = new LiteDatabase(DBConnectionString))
     {
         LiteCollection<MatchRecord> matchColl = db.GetCollection<MatchRecord>(MatchHeader);
         matchColl.EnsureIndex(nameof(MatchRecord.ID));
         matchColl.Insert(match);
     }
 }
Esempio n. 10
0
        public void NewRelativeRecord_CreatesANewMatchRecord_WitLoseResult_WhenNewRankIsLessThanOldRank()
        {
            // Arrange
            MatchRecord original = MatchRecordFaker.CreateRecord(cr: 2000);

            // Act
            MatchRecord relative = original.NewRelativeRecord(1900, DateTime.Now, MapFaker.Random());

            // Assert
            Assert.AreEqual(relative.Result, MatchResult.LOSE);
        }
Esempio n. 11
0
        public void NewRelativeRecord_CreatesANewMatchRecord_WithTheDifferencealculated_RelativeToTheOriginal()
        {
            // Arrange
            MatchRecord original = MatchRecordFaker.CreateRecord(cr: 2000);

            // Act
            MatchRecord relative = original.NewRelativeRecord(2100, DateTime.Now, MapFaker.Random());

            // Assert
            Assert.AreEqual(relative.Diff, 100);
        }
Esempio n. 12
0
        private void EndMatch()
        {
            List <Player> sortedPlayers = Players.OrderByDescending(x => x.Score).ToList();

            MatchRecord record = new MatchRecord(sortedPlayers, AIPlayer.Name);

            FileHandler.SaveMatchRecord(record);

            ActivePlayer = sortedPlayers.First();
            MainWindow.ShowMatchEndPopup();
        }
        public void OnNewMatchRecord_RecalculatesTotalPlayed()
        {
            // Arrange
            MatchRecord          newRecord = MatchRecordFaker.CreateRecord();
            MapWinRatesViewModel vm        = new MapWinRatesViewModel(_profileManager);

            // Act
            NewMatchRecord(newRecord);

            // Assert
            Assert.AreEqual(_profileManager.ActiveProfile.MatchHistory.Count(), vm.TotalPlayed);
        }
Esempio n. 14
0
        // *** HELPER FUNCTIONS *** //

        private void nextGame()
        {
            //	find next unfinished game to start
            MatchRecord nextMatch = null;

            foreach (MatchRecord match in MatchSet)
            {
                if (match.Result == null)
                {
                    nextMatch = match;
                    break;
                }
            }
            if (nextMatch != null)
            {
                StreamReader reader      = new StreamReader(nextMatch.SavedGameFile);
                Game         currentGame = Program.Manager.LoadGame(reader);
                currentGame.StartMatch();
                TimeControl timeControl = new TimeControl(nextMatch.TimeControl);
                currentGame.ComputerControlled[0] = true;
                currentGame.ComputerControlled[1] = true;
                if (nextMatch.Engines[0] == Program.Manager.InternalEngine)
                {
                    currentGame.AddInternalEngine(0);
                }
                else
                {
                    currentGame.AddEngine(Program.Manager.EngineLibrary.AdaptEngine(currentGame, nextMatch.Engines[0]), 0);
                }
                if (nextMatch.Engines[1] == Program.Manager.InternalEngine)
                {
                    currentGame.AddInternalEngine(1);
                }
                else
                {
                    currentGame.AddEngine(Program.Manager.EngineLibrary.AdaptEngine(currentGame, nextMatch.Engines[1]), 1);
                }
                currentGame.Match.SetTimeControl(timeControl);
                currentGame.IsAutomatedMatch = true;
                nextMatch.PlayerNames[0]     = currentGame.PerformSymbolExpansion(nextMatch.PlayerNames[0]);
                nextMatch.PlayerNames[1]     = currentGame.PerformSymbolExpansion(nextMatch.PlayerNames[1]);
                nextMatch.Game = currentGame;
                currentMatches.Add(nextMatch);
                GameForm gameForm = new GameForm(currentGame);
                gameForm.Show();
            }
            else
            {
                timer.Stop();
                outputFile.Close();
            }
        }
        public void OnNewMatchRecord_RecalculatesTotalDrawn()
        {
            // Arrange
            MatchRecord          newRecord = MatchRecordFaker.CreateRecord(result: MatchResult.DRAW);
            MapWinRatesViewModel vm        = new MapWinRatesViewModel(_profileManager);
            int drawn = vm.TotalDrawn;

            // Act
            NewMatchRecord(newRecord);

            // Assert
            Assert.AreEqual(drawn + 1, vm.TotalDrawn);
        }
        public void OnNewMatchRecord_RecalculatesTotalLost()
        {
            // Arrange
            MatchRecord          newRecord = MatchRecordFaker.CreateRecord(result: MatchResult.LOSE);
            MapWinRatesViewModel vm        = new MapWinRatesViewModel(_profileManager);
            int lost = vm.TotalLost;

            // Act
            NewMatchRecord(newRecord);

            // Assert
            Assert.AreEqual(lost + 1, vm.TotalLost);
        }
Esempio n. 17
0
    public void GetMyMatchRecord(int index, Action <MatchRecord, bool> func)
    {
        var inDate = BackEndServerManager.instance.myIndate;

        SendQueue.Enqueue(Backend.Match.GetMatchRecord, inDate, matchInfos[index].matchType, matchInfos[index].matchModeType, matchInfos[index].inDate, callback =>
        {
            MatchRecord record = new MatchRecord();
            record.matchTitle  = matchInfos[index].title;
            record.matchType   = matchInfos[index].matchType;
            record.modeType    = matchInfos[index].matchModeType;

            if (!callback.IsSuccess())
            {
                Debug.LogError("매칭 기록 조회 실패\n" + callback);
                func?.Invoke(record, false);
                return;
            }

            if (callback.Rows().Count <= 0)
            {
                Debug.Log("매칭 기록이 존재하지 않습니다.\n" + callback);
                func?.Invoke(record, true);
                return;
            }
            var data       = callback.Rows()[0];
            var win        = Convert.ToInt32(data["victory"]["N"].ToString());
            var draw       = Convert.ToInt32(data["draw"]["N"].ToString());
            var defeat     = Convert.ToInt32(data["defeat"]["N"].ToString());
            var numOfMatch = win + draw + defeat;
            string point   = string.Empty;
            if (matchInfos[index].matchType == MatchType.MMR)
            {
                point = data["mmr"]["N"].ToString();
            }
            else if (matchInfos[index].matchType == MatchType.Point)
            {
                point = data["point"]["N"].ToString() + " P";
            }
            else
            {
                point = "-";
            }

            record.win        = win;
            record.numOfMatch = numOfMatch;
            record.winRate    = Math.Round(((float)win / numOfMatch) * 100 * 100) / 100;
            record.score      = point;

            func?.Invoke(record, true);
        });
    }
Esempio n. 18
0
        private async void Init()
        {
            turnNum = 0;
            passNum = 0;
            board   = ReversiBoard.InitBoard();
            record  = MatchRecord.Empty();

            //先手と後手で別の思考エンジンを使える
            senteEngine = new ThinkingEngine.RandomThinking();
            goteEngine  = new ThinkingEngine.CountingEngine();

            RefreshTurnLabel();
            RefreshPanel();
            inGame     = true;
            inPlayback = false;
            await Next();
        }
Esempio n. 19
0
        public void CheckScore()
        {
            if (Directory.Exists(Config.StatFolderName))
            {
                List <string> files = Directory.GetFiles(Config.StatFolderName, "match_*.json").ToList();
                if (files.Count == 0)
                {
                    this.SetScore(0, 0, 0);
                    return;
                }
                files.Reverse();

                int wins, loses, rating;
                wins = loses = rating = 0;

                foreach (string filePath in files)
                {
                    MatchRecord tokenMatch = MatchRecord.Load(filePath);

                    if (tokenMatch.MatchEnd.ToLocalTime().Date < DateTime.Today)
                    {
                        break;
                    }

                    if (tokenMatch.RatingGain > 0)
                    {
                        wins++;
                    }
                    else
                    {
                        loses++;
                    }

                    rating += tokenMatch.RatingGain;
                }

                this.SetScore(wins, loses, rating);
            }
            else
            {
                this.SetScore(0, 0, 0);
                return;
            }
        }
Esempio n. 20
0
        public void CRChange_CalculatesTheDifferenceBetweenTheInitialCR_AndTheFinalMatchCR()
        {
            // Arrange
            var initialCr = 1945;
            IEnumerable <MatchRecord> matches = Fakers.MatchRecordFaker.NMatchesBetweenDates(
                10,
                start: new DateTime(2018, 01, 01, 21, 00, 00),
                initialCR: initialCr
                );

            MatchRecord lastMatch = matches.Last();

            GameSession session = new GameSession(initialCr, matches);

            // Act
            int change = session.CRChange;

            // Assert
            Assert.AreEqual(lastMatch.CR - initialCr, change);
        }
        public void WriteMatch(MatchRecord match)
        {
            string output = _formatString.Replace("%F", match.FileName);

            output = output.Replace("%l", match.LanguageInfo.Name);
            output = output.Replace("%t", match.LanguageInfo.Type.ToString());
            output = output.Replace("%L", match.StartLocationLine.ToString());
            output = output.Replace("%C", match.StartLocationColumn.ToString());
            output = output.Replace("%l", match.EndLocationLine.ToString());
            output = output.Replace("%c", match.EndLocationColumn.ToString());
            output = output.Replace("%R", match.RuleId);
            output = output.Replace("%N", match.RuleName);
            output = output.Replace("%S", match.Severity.ToString());
            output = output.Replace("%X", match.Confidence.ToString());
            output = output.Replace("%D", match.RuleDescription);
            output = output.Replace("%m", match.Sample);
            output = output.Replace("%T", string.Join(',', match.Tags ?? System.Array.Empty <string>()));

            WriteOnce.General(output);
        }
Esempio n. 22
0
        public static IEnumerable <MatchRecord> NMatchesBetweenDates(
            int n,
            DateTime start,
            int initialCR       = 1000,
            int crMaxDifference = 500)
        {
            var valueFaker = new Faker();

            IEnumerable <DateTime> orderedDates = GenerateRealisticMatchTimes(n, start);

            List <MatchRecord> matches = new List <MatchRecord>();
            var i          = 0;
            var firstCR    = valueFaker.Random.Number(initialCR - crMaxDifference, initialCR + crMaxDifference);
            var firstMatch = new MatchRecord()
            {
                CR     = firstCR,
                Date   = orderedDates.ElementAt(i),
                Diff   = firstCR - initialCR,
                Map    = MapFaker.Random(),
                Result = MatchRecord.ComparerCR(firstCR, initialCR)
            };

            matches.Add(firstMatch);
            i++;


            MatchRecord lastMatch = firstMatch;

            while (i < n)
            {
                var newMatch = lastMatch.NewRelativeRecord(
                    valueFaker.Random.Number(initialCR - crMaxDifference, initialCR + crMaxDifference),
                    orderedDates.ElementAt(i),
                    MapFaker.Random()
                    );
                matches.Add(newMatch);
                i++;
            }

            return(matches);
        }
Esempio n. 23
0
        public bool Set(MatchRecord matchRecord)
        {
            this.MatchRecord = matchRecord;

            if (this.MatchRecord.Games == null)
            {
                return(false);
            }
            else if (this.MatchRecord.Games.Count == 0)
            {
                return(false);
            }

            this.GameListView.ItemsSource = null;
            List <int> list = new List <int>(Enumerable.Range(1, this.MatchRecord.Games.Count));

            this.GameListView.ItemsSource   = list;
            this.GameListView.SelectedIndex = 0;

            return(PlotGameScore(this.MatchRecord, 0));
        }
Esempio n. 24
0
        private bool PlotGameScore(MatchRecord matchRecord, int gameIndex)
        {
            GameRecord gameRecord = matchRecord.Games[gameIndex];

            if (gameRecord == null)
            {
                return(false);
            }

            this.GameScorePlotView.Model = null;
            this.GameScorePlotModel.Series.Clear();

            for (int playerIndex = 0; playerIndex < matchRecord.Players.Count; playerIndex++)
            {
                PlayerInfo            playerInfo   = matchRecord.Players[playerIndex];
                PlayerRecord          playerRecord = gameRecord.PlayerRecords[playerIndex];
                List <oxy::DataPoint> points       = new List <oxy::DataPoint>(gameRecord.Ticks.Zip(playerRecord.Scores, (t, s) =>
                {
                    return(new oxy::DataPoint(t / 60, s));
                }));

                bool myFlag = playerInfo.ID32 == Core.PPTMemory.MyID32;

                string colorHex = Config.ScorePlotColorHexes[playerIndex];

                oxy::Series.LineSeries series = new oxy::Series.LineSeries()
                {
                    ItemsSource = points,
                    Title       = $"{playerInfo.Name} ({((myFlag) ? "Me, " : "")}{playerRecord.Scores.Last()})",
                    Color       = oxy::OxyColor.Parse(colorHex),
                    LineStyle   = (myFlag) ? oxy::LineStyle.Dash : oxy::LineStyle.Solid,
                };

                this.GameScorePlotModel.Title = $"Game {gameIndex+1}, {gameRecord.GameEnd.ToLocalTime().ToSimpleString()}";
                this.GameScorePlotModel.Series.Add(series);
            }

            this.GameScorePlotView.Model = this.GameScorePlotModel;
            return(true);
        }
Esempio n. 25
0
        private static IEnumerable <MatchRecord> GetRecords()
        {
            DateTime now      = new DateTime();
            var      matchOne = new MatchRecord()
            {
                CR     = 1000,
                Date   = new DateTime(),
                Diff   = 1000,
                Map    = Maps.All.First(),
                Result = MatchResult.WIN
            };

            var matchTwo   = matchOne.NewRelativeRecord(1025, now.AddMinutes(30), Maps.All.ElementAt(1));
            var matchThree = matchTwo.NewRelativeRecord(1061, now.AddMinutes(60), Maps.All.ElementAt(2));

            return(new List <MatchRecord>()
            {
                matchOne,
                matchTwo,
                matchThree
            });
        }
Esempio n. 26
0
        public void WriteMatch(MatchRecord match)
        {
            if (TextWriter is null)
            {
                throw new ArgumentNullException(nameof(TextWriter));
            }
            string output = _formatString.Replace("%F", match.FileName);

            output = output.Replace("%l", match.LanguageInfo.Name);
            output = output.Replace("%t", match.LanguageInfo.Type.ToString());
            output = output.Replace("%L", match.StartLocationLine.ToString());
            output = output.Replace("%C", match.StartLocationColumn.ToString());
            output = output.Replace("%l", match.EndLocationLine.ToString());
            output = output.Replace("%c", match.EndLocationColumn.ToString());
            output = output.Replace("%R", match.RuleId);
            output = output.Replace("%N", match.RuleName);
            output = output.Replace("%S", match.Severity.ToString());
            output = output.Replace("%X", match.Confidence.ToString());
            output = output.Replace("%D", match.RuleDescription);
            output = output.Replace("%m", match.Sample);
            output = output.Replace("%T", string.Join(',', match.Tags ?? System.Array.Empty <string>()));

            TextWriter.WriteLine(output);
        }
 public void Remove(MatchRecord matchRecord)
 {
     _context.MatchRecords.Remove(matchRecord);
 }
 public void Add(MatchRecord matchRecord)
 {
     _context.MatchRecords.Add(matchRecord);
 }
		public bool GreaterThan( MatchRecord b )
		{
			if ( Full == b.Full )
			{
				if ( Partial > b.Partial )
					return true;
				else
					return false;
			}
			else
			{
				if ( Full > b.Full )
					return true;
				else
					return false;
			}
		}
Esempio n. 30
0
        // *** EVENT HANDLERS *** //

        private void AutomatedMatchesProgressForm_Load(object sender, EventArgs e)
        {
            foreach (MatchRecord match in MatchSet)
            {
                ListViewItem lvi = new ListViewItem(match.ID);
                lvi.SubItems.Add(
                    match.SavedGameFile.IndexOf(Path.DirectorySeparatorChar) >= 0
                                        ? match.SavedGameFile.Substring(match.SavedGameFile.LastIndexOf(Path.DirectorySeparatorChar) + 1)
                                        : match.SavedGameFile);
                lvi.SubItems.Add(match.TimeControl);
                if (match.Engines[0] == null)
                {
                    EngineConfiguration engine = Program.Manager.LookupEngineByPartialName(match.EngineNames[0]);
                    if (engine == null)
                    {
                        throw new Exception("Automated Matches: can't find an engine with a name containing '" + match.EngineNames[0] + "'");
                    }
                    match.Engines[0] = engine;
                }
                lvi.SubItems.Add(match.EngineNames[0]);
                if (match.Engines[1] == null)
                {
                    EngineConfiguration engine = Program.Manager.LookupEngineByPartialName(match.EngineNames[1]);
                    if (engine == null)
                    {
                        throw new Exception("Automated Matches: can't find an engine with a name containing '" + match.EngineNames[1] + "'");
                    }
                    match.Engines[1] = engine;
                }
                lvi.SubItems.Add(match.EngineNames[1]);
                lvi.SubItems.Add("(pending)");
                lvi.SubItems.Add("(pending)");
                lvi.Tag = match;
                listMatches.Items.Add(lvi);
            }
            if (File.Exists(OutputFileName))
            {
                //	we are resuming a previous run -
                //	load the results already completed
                TextReader log = new StreamReader(OutputFileName);
                //	skip header row
                string input = log.ReadLine();
                while ((input = log.ReadLine()) != null)
                {
                    string[] split = input.Split('\t');
                    string   id    = split[0];
                    foreach (ListViewItem lvi in listMatches.Items)
                    {
                        MatchRecord match = (MatchRecord)lvi.Tag;
                        if (match.ID == id)
                        {
                            match.EngineNames[0] = split[1];
                            match.EngineNames[1] = split[2];
                            match.PlayerNames[0] = split[3];
                            match.PlayerNames[1] = split[4];
                            match.Result         = split[5];
                            match.Winner         = split[6];
                            lvi.SubItems[5].Text = match.Result;
                            lvi.SubItems[6].Text = match.Winner;
                            updateResultCounts(match.Result, match.Winner);
                            break;
                        }
                    }
                }
                log.Close();
            }
        }
 private void NewMatchRecord(MatchRecord record)
 {
     _profileManager.ActiveProfile.MatchHistory.Add(record);
     _messenger.Send(new Messages.NewMatchRecord(record));
 }
void AddResult( List<CommandVariation> list, CommandVariation CV, MatchRecord record )
	{
		foreach( CommandVariation cv in list )
		{
			// check if already here
			if ( cv.Cmd == CV.Cmd )
			{
				if ( record.GreaterThan(cv.Record) )
				{
					// swap this record for the one that is better
					list.Remove (cv);
					CV.Record = record;
					list.Add (CV); // this is going to add the new, better variation at the end of the list
#if DEBUG_MATCH	
					UnityEngine.Debug.Log (">>>> Replacing " + CV.Cmd + "<" + record.Full + "," + cv.Record.Full + ">");
#endif
				}
				else
				{
#if DEBUG_MATCH
					UnityEngine.Debug.Log (">>>> Ignorning " + CV.Cmd + "<" + record.Full + "," + cv.Record.Full + ">");
#endif
				}
				return;
			}
		}

		// check if command is currently available
		if ( Dispatcher.GetInstance().IsCommandAvailable(CV.Cmd) == false )
			return;

#if DEBUG_MATCH
		UnityEngine.Debug.Log (">>>> Adding " + CV.Cmd + "<" + record.Full + ">");
#endif
		CV.Record = record;
		list.Add(CV);
	}