public static string Export(Replay replay)
 {
     Game game = new Game(replay);
     GameState oldState = null;
     List<GameAction> actions = new List<GameAction>();
     for (int i = 0; i < replay.Actions.Count; i++)
     {
         if (replay.Actions[i] is ReplayTimeAction)
             actions.Add(replay.Actions[i]);
         game.Seek(i);
         List<GameAction> newActions = StateDelta.Delta(oldState, game.State);
         actions.AddRange(newActions);
         if (game.State != null)
             oldState = game.State.Clone();
     }
     List<JObject> jActions = new List<JObject>();
     TimeSpan time = TimeSpan.Zero;
     foreach (var action in actions)
     {
         if (action is ReplayTimeAction)
             time = ((ReplayTimeAction)action).Time;
         else
             jActions.Add(SerializeAction(action, time));
     }
     JObject json = new JObject(new JProperty("changes", new JArray(jActions)));
     return json.ToString(Newtonsoft.Json.Formatting.None);
 }
示例#2
1
        public void Hero118()
        {
            Replay rep = new Replay(@"data\1.18.w3g");
            Assert.AreEqual(6, rep.Players.Count);

            Player player1 = null;
            Player player2 = null;

            foreach (Player p in rep.Players)
            {
                if (p.IsObserver)
                    continue;
                if (player1 == null)
                    player1 = p;
                else
                    player2 = p;
            }


            Assert.AreEqual(3, player1.Heroes.Count);

            Assert.AreEqual(5, player1.Heroes["Udea"].Level);

            Assert.AreEqual(2, player2.Heroes["Npbm"].Level);
        }
示例#3
0
        private static void CalculateAPM(Replay replay)
        {
            var events = replay.PlayerEvents;

            if (events == null)
            {
                // This is experimental. With older replays, it appears to return a close approximation.
                return;
            }

            var eventGroups = events.Where(r => r.Player != null)
                                    .Where(r => r.EventType != GameEventType.Inactive)
                                    .GroupBy(r => r.Player);

            foreach (var group in eventGroups)
            {
                var order = group.OrderBy((r) => r.Time);
                var last = order.Last();
                var count = group.Count();

                // Calculates APM per second.
                var apm = count / last.Time.TimeSpan.TotalSeconds;

                apm *= 60;

                Debug.WriteLine(last.Player.Name + "'s APM: " + apm);
            }
        }
示例#4
0
    protected void Page_Init(object sender, EventArgs e)
    {
        ctx = new AriClinicContext("AriClinicContext");
        // security control, it must be a user logged
        if (Session["User"] == null)
            Response.Redirect("Default.aspx");
        else
        {
            user = CntAriCli.GetUser((Session["User"] as User).UserId, ctx);
            Process proc = (from p in ctx.Processes
                            where p.Code == "request"
                            select p).FirstOrDefault<Process>();
            per = CntAriCli.GetPermission(user.UserGroup, proc, ctx);
            btnAccept.Visible = per.Modify;
        }
        //
        if (Request.QueryString["RequestId"] != null)
        {
            requestId = Int32.Parse(Request.QueryString["RequestId"]);
            request = CntAriCli.GetRequest(requestId, ctx);
            if (request != null)
            {
                string person = "";
                if (request.Patient != null) 
                    person = request.Patient.FullName;
                else 
                    person = request.FullName;
                lblRequestPerson.Text = String.Format("INTERESADO: {0}", person);
                string service = "";
                if (request.Service != null)
                {
                    service = request.Service.Name;
                    rdcService.Items.Clear();
                    rdcService.Items.Add(new RadComboBoxItem(request.Service.Name,request.Service.ServiceId.ToString()));
                    rdcService.SelectedValue = request.Service.ServiceId.ToString();
                }
                lblRequestService.Text = String.Format("SERVICIO: {0}", service);
                lblRequestComments.Text = String.Format("OBSERVACIONES: {0}", request.Comments);
            }
        }

        // 
        if (Request.QueryString["ReplayId"] != null)
        {
            replayId = Int32.Parse(Request.QueryString["ReplayId"]);
            replay = CntAriCli.GetReplay(replayId, ctx);
            LoadData(replay);
        }
        else
        {
            // default values for a new request
            rdtReplayDate.SelectedDate = DateTime.Now;
        }
        //
        if (Request.QueryString["Caller"] != null)
        {
            caller = Request.QueryString["Caller"];
        }
    }
示例#5
0
 void AddToReplay(int code)
 {
     Replay rp = new Replay();
     rp.ctrls = new Control[ctrls.Length];           
     rp.state = (GraphController<int,int>)CopyEverything.Copy(test);
     rp.opid = code;
     history.Add(rp);
 }
示例#6
0
        public int Start(Replay replay)
        {
            this.replay = replay;

            ClearField();
            InputReplayStep();

            return Score;
        }
示例#7
0
        private void ParseDir()
        {
            string[] files = Directory.GetFiles(path, "*.w3g");

            foreach (string file in files)
            {
                Replay replay = new Replay(file);
                Console.WriteLine(file + ":" + replay.Hash);
                count++;
            }
        }
示例#8
0
        private static IReplay ParseReplay(UnpackResult result)
        {
            HeaderParser headerParser = new HeaderParser(result.Header);
            Header header = headerParser.ParseHeader();

            ActionParser actionsParser = new ActionParser(result.Actions, header.Players.ToList<IPlayer>());
            List<IAction> actions = actionsParser.ParseActions();

            IReplay replay = new Replay(header, actions);

            return replay;
        }
示例#9
0
        public void Rep118Ladder()
        {
            Replay rep = new Replay(@"data\1.18-ladder.w3g");
            Assert.AreEqual(2, rep.Players.Count);

            Assert.AreEqual("MKpowa", rep.Players[0].Name);
            Assert.AreEqual(1, rep.Players[0].TeamNo);
            Assert.AreSame(rep.Host, rep.Players[0]);
            Assert.AreEqual(Race.Random, rep.Players[0].Race);

            Assert.AreEqual("KrawieC.", rep.Players[1].Name);
            Assert.AreEqual(2, rep.Players[1].TeamNo);
            Assert.AreEqual(Race.NightElf, rep.Players[1].Race);
        }
示例#10
0
        public void Rep121FFA()
        {
            Replay rep = new Replay(@"data\1.21-ffa.w3g");

            Assert.AreEqual(4, rep.Players.Count);

            Assert.AreEqual("", rep.Players[0].Name);
            Assert.AreEqual(Race.Undead, rep.Players[0].Race);

            Assert.AreEqual("", rep.Players[1].Name);
            Assert.AreEqual(Race.Random, rep.Players[1].Race);

            Assert.AreEqual("", rep.Players[2].Name);
            Assert.AreEqual(Race.NightElf, rep.Players[2].Race);

            Assert.AreEqual("KoD-EleMenTaL", rep.Players[3].Name);
            Assert.AreEqual(Race.NightElf, rep.Players[3].Race);
        }
示例#11
0
        public void Rep118()
        {
            Replay rep = new Replay(@"data\1.18.w3g");
            Assert.AreEqual(6, rep.Players.Count);

            Assert.AreEqual("a-L.MSI.SeeK", rep.Players[0].Name);
            //Observer
            Assert.AreEqual(13, rep.Players[0].TeamNo);

            Assert.AreEqual("a-L.MSI.BrO", rep.Players[1].Name);
            //Observer
            Assert.AreEqual(13, rep.Players[1].TeamNo);

            Assert.AreEqual("omg_hi2u_asl", rep.Players[2].Name);
            //Observer
            Assert.AreEqual(13, rep.Players[2].TeamNo);

            Assert.AreEqual("a-L.MSI.ChuaEr", rep.Players[3].Name);
            //Player 1
            Assert.AreEqual(1, rep.Players[3].TeamNo);
            Assert.AreEqual(Race.Undead, rep.Players[3].Race);

            Assert.AreEqual("FoH)Bluedragoon", rep.Players[4].Name);
            //Player 2
            Assert.AreEqual(2, rep.Players[4].TeamNo);
            Assert.AreEqual(Race.Human, rep.Players[4].Race);

            Assert.AreEqual("FoH)Monocle-", rep.Players[5].Name);
            //Observer
            Assert.AreEqual(13, rep.Players[5].TeamNo);

            Assert.AreEqual(5792, rep.Players[3].Actions);
            Assert.AreEqual(4213, rep.Players[4].Actions);
            Assert.AreEqual(0, rep.Players[0].Actions);

            Assert.AreEqual(160.0f, rep.Players[3].Apm);
        }
示例#12
0
 protected virtual FramedReplayInputHandler CreateReplayInputHandler(Replay replay) => null;
示例#13
0
 protected override ReplayInputHandler CreateReplayInputHandler(Replay replay) => new OsuFramedReplayInputHandler(replay);
示例#14
0
    void FixedUpdate()
    {
        timer += Time.deltaTime;
        List <double> states = new List <double>();
        List <double> qs     = new List <double>();

        states.Add(Vector3.Distance(this.transform.position, topBeam.transform.position));
        states.Add(Vector3.Distance(this.transform.position, bottomBeam.transform.position));

        qs = SoftMax(ann.CalcOutput(states));
        double maxQ      = qs.Max();
        int    maxQIndex = qs.ToList().IndexOf(maxQ);

        exploreRate = Mathf.Clamp(exploreRate - exploreDecay, minExploreRate, maxExploreRate);

        //if(Random.Range(0,100) < exploreRate)
        //	maxQIndex = Random.Range(0,2);

        if (maxQIndex == 0)
        {
            rb.AddForce(Vector3.up * moveForce * (float)qs[maxQIndex]);
        }
        else if (maxQIndex == 1)
        {
            rb.AddForce(Vector3.up * -moveForce * (float)qs[maxQIndex]);
        }

        if (crashed)
        {
            reward = -1.0f;
        }
        else
        {
            reward = 0.1f;
        }

        Replay lastMemory = new Replay(Vector3.Distance(this.transform.position, topBeam.transform.position),
                                       Vector3.Distance(this.transform.position, bottomBeam.transform.position),
                                       reward);

        if (replayMemory.Count > mCapacity)
        {
            replayMemory.RemoveAt(0);
        }

        replayMemory.Add(lastMemory);

        if (crashed)
        {
            for (int i = replayMemory.Count - 1; i >= 0; i--)
            {
                List <double> toutputsOld = new List <double>();
                List <double> toutputsNew = new List <double>();
                toutputsOld = SoftMax(ann.CalcOutput(replayMemory[i].states));

                double maxQOld = toutputsOld.Max();
                int    action  = toutputsOld.ToList().IndexOf(maxQOld);

                double feedback;
                if (i == replayMemory.Count - 1 || replayMemory[i].reward == -1)
                {
                    feedback = replayMemory[i].reward;
                }
                else
                {
                    toutputsNew = SoftMax(ann.CalcOutput(replayMemory[i + 1].states));
                    maxQ        = toutputsNew.Max();
                    feedback    = (replayMemory[i].reward +
                                   discount * maxQ);
                }

                toutputsOld[action] = feedback;
                ann.Train(replayMemory[i].states, toutputsOld);
            }

            if (timer > maxBalanceTime)
            {
                maxBalanceTime = timer;
            }

            timer = 0;

            crashed = false;
            ResetBird();
            replayMemory.Clear();
            failCount++;
        }
    }
示例#15
0
 protected override FramedReplayInputHandler CreateReplayInputHandler(Replay replay) => new ManiaFramedReplayInputHandler(replay, this);
 void game_OnActionAdded(Replay replay, int actionIndex)
 {
     //game.Save(@"C:\Dokumente und Einstellungen\W\Desktop\GoReplay.gor");
     //Game.Replay.Save("Current.Replay.gor");
     //Game.Seek(Game.Replay.Actions.Count - 1);
     /*if (view.ActiveAction.Action == null || view.ActiveAction == new ActionReference(Game.Replay, Game.Replay.Actions.Count - 2))
     {
         view.ActiveAction = actionReference;
         //view.State = view.ActiveAction.State;
     }*/
 }
示例#17
0
        static void ReplayMethod()
        {
            Replay replay = new Replay(@"C:\Users\Master\AppData\Local\TslGame\Saved\Demos\old\match.bro.custom.1cePrime.na.normal.2018.02.02.feef46c6-0c69-49ea-a0fe-3853d41aacb1__USER__3f2737e1fcd7d5e0444298f528c41675");

            Console.WriteLine("CustomName = " + replay.CustomName);
            Console.WriteLine("Path = " + replay.Path);
            Console.WriteLine("Info - AllDeadOrWin = " + replay.Info.AllDeadOrWin);
            Console.WriteLine("Info - Changelist = " + replay.Info.Changelist);
            Console.WriteLine("Info - CustomHost = " + replay.Info.CustomHost);
            Console.WriteLine("Info - DemoFileLastOffset = " + replay.Info.DemoFileLastOffset);
            Console.WriteLine("Info - FriendlyName = " + replay.Info.FriendlyName);
            Console.WriteLine("Info - IsIncomplete = " + replay.Info.IsIncomplete);
            Console.WriteLine("Info - IsLive = " + replay.Info.IsLive);
            Console.WriteLine("Info - IsServerRecording = " + replay.Info.IsServerRecording);
            Console.WriteLine("Info - LengthInMs = " + replay.Info.LengthInMs);
            Console.WriteLine("Info - MapName = " + replay.Info.MapName);
            Console.WriteLine("Info - Mode = " + replay.Info.Mode);
            Console.WriteLine("Info - NetworkVersion = " + replay.Info.NetworkVersion);
            Console.WriteLine("Info - RecordUserId = " + replay.Info.RecordUserId);
            Console.WriteLine("Info - RecordUserNickName = " + replay.Info.RecordUserNickName);
            Console.WriteLine("Info - ServerID = " + replay.Info.ServerID);
            Console.WriteLine("Info - ServerType = " + replay.Info.ServerType);
            Console.WriteLine("Info - ShouldKeep = " + replay.Info.ShouldKeep);
            Console.WriteLine("Info - SizeInBytes = " + replay.Info.SizeInBytes);
            Console.WriteLine("Info - TimeStampISO = " + replay.Info.TimeStampISO);
            Console.WriteLine("Info - TimeStamp = " + replay.Info.TimeStamp);
            Console.WriteLine("Info - HasReplayReportToken = " + replay.Info.HasReplayToken);
            Console.WriteLine("Summary - MatchID = " + replay.Summary.MatchID);
            Console.WriteLine("Summary - IsServerRecording = " + replay.Summary.IsServerRecording);
            Console.WriteLine("Summary - PlayerCount = " + replay.Summary.PlayerCount);
            Console.WriteLine("Summary - TeamsCount = " + replay.Summary.TeamsCount);
            Console.WriteLine("Summary - AvgPlayerPerTeam = " + replay.Summary.AvgPlayersPerTeam);
            Console.WriteLine("Summary - NumTeammates = " + replay.Summary.NumTeammates);
            Console.WriteLine("Summary - District = " + replay.Summary.District);
            Console.WriteLine("Summary - KnownRegion = " + replay.Summary.KnownRegion);
            Console.WriteLine("Summary - KnownWeather = " + replay.Summary.KnownWeather);
            Console.WriteLine("Summary - Climate = " + replay.Summary.Climate);
            for (int i = 0; i < replay.Summary.NumTeammates; i++)
            {
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - Player Name = " + replay.Summary.Teammates[i].PlayerName);
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - Player ID = " + replay.Summary.Teammates[i].PlayerID);
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - TeamID = " + replay.Summary.Teammates[i].PlayerTeamID);
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - IsRecordingPlayer = " + replay.Summary.Teammates[i].IsRecordingUser);
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - Kills = " + replay.Summary.Teammates[i].Kills);
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - Headshots = " + replay.Summary.Teammates[i].Headshots);
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - Ranking = " + replay.Summary.Teammates[i].Ranking);
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - Longest Distance Kill In CM = " + replay.Summary.Teammates[i].LongestDistanceKillInCM);
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - Longest Distance Kill In M = " + replay.Summary.Teammates[i].LongestDistanceKillInM);
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - Total Damage = " + replay.Summary.Teammates[i].TotalGivenDamages);
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - Total Distance Moved in M = " + replay.Summary.Teammates[i].TotalMovedDistanceInM);
                Console.WriteLine("Summary - Teammate " + (i + 1) + " - Total Distance Moved (in M or KM) = " + replay.Summary.Teammates[i].TotalMovedDistanceHumanReadable);
            }
            if (replay.Info.HasReplayToken)
            {
                Console.WriteLine("Info - ReplayReportToken - Token = " + replay.Info.ReplayReportToken.Token);
                Console.WriteLine("Info - ReplayReportToken - Algorithm = " + replay.Info.ReplayReportToken.Algorithm);
                Console.WriteLine("Info - ReplayReportToken - Type = " + replay.Info.ReplayReportToken.Type);
                Console.WriteLine("Info - ReplayReportToken - AccountID = " + replay.Info.ReplayReportToken.AccountID);
                Console.WriteLine("Info - ReplayReportToken - MatchID = " + replay.Info.ReplayReportToken.MatchID);
                Console.WriteLine("Info - ReplayReportToken - JWT_ID = " + replay.Info.ReplayReportToken.JWT_ID);
                Console.WriteLine("Info - ReplayReportToken - NotBefore = " + replay.Info.ReplayReportToken.NotBefore);
                Console.WriteLine("Info - ReplayReportToken - NotBeforePrecise = " + replay.Info.ReplayReportToken.NotBeforePrecise);
                Console.WriteLine("Info - ReplayReportToken - Expires = " + replay.Info.ReplayReportToken.Expires);
                Console.WriteLine("Info - ReplayReportToken - ExpiresPercise = " + replay.Info.ReplayReportToken.ExpiresPrecise);
                Console.WriteLine("Info - ReplayReportToken - Issuer = " + replay.Info.ReplayReportToken.Issuer);
                Console.WriteLine("Info - ReplayReportToken - Signature = " + replay.Info.ReplayReportToken.Signature);
            }
            Console.WriteLine("--- Events ---");
            foreach (IReplayEvent Event in replay.Events())
            {
                switch (Event.GetType().Name)
                {
                case "ReplayKnockEvent":
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine(Event.ToString());
                    Console.ForegroundColor = ConsoleColor.White;
                    break;

                case "ReplayKillEvent":
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(Event.ToString());
                    Console.ForegroundColor = ConsoleColor.White;
                    break;

                default:
                    Console.WriteLine(Event.ToString());
                    break;
                }
            }
            Console.WriteLine("---- All Replays ----");
            foreach (Replay singlereplay in Utils.ListReplays(Utils.default_replay_dir))
            {
                Console.WriteLine(singlereplay.Info.FriendlyName);
            }
            Console.WriteLine("---- End Replays ----");
        }
示例#18
0
 private bool Any(Replay replay)
 {
     foreach (Player a in listOfPlayers)
         if (a.replay == replay) return true;
     return false;
 }
示例#19
0
 protected void UnloadData(Replay chn)
 {
     // creating / editing reply
     replay.ReplayDate = (DateTime)rdtReplayDate.SelectedDate;
     if (rdcChannel.SelectedValue != "")
     {
         replay.Channel = CntAriCli.GetChannel(int.Parse(rdcChannel.SelectedValue), ctx);
     }
     if (rdcService.SelectedValue != "")
     {
         replay.Service = CntAriCli.GetService(int.Parse(rdcService.SelectedValue), ctx);
     }
     replay.Comments = txtComments.Text;
     replay.User = user;
     // changing request accordingly
     request.Status = "CONTESTADA";
     replay.Request = request;
 }
        public void TestHeaderDeserialization(string filePath)
        {
            var replay = Replay.DeserializeHeader(filePath);

            Assert.IsTrue(replay.Properties.Any());
        }
示例#21
0
        private static void ReadInput()
        {
            string input = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(input))
            {
                return;
            }

            if (input == "start")
            {
                Task.Run(() => Game.Start());
                return;
            }

            if (input == "end")
            {
                Game.End();
                return;
            }

            if (input == "pause")
            {
                Game.Pause(true);
                return;
            }
            if (input == "resume")
            {
                Game.Pause(false);
                return;
            }
            if (input == "save")
            {
                var replay = Game.CreateReplay();
                using (FileStream fileStream = new FileStream(@"C:\Users\Steve\Desktop\Replays\" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss-tt") + ".txt", FileMode.Create))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(fileStream, replay);
                }
                return;
            }
            if (input == "snapshot")
            {
                var snapshot = Game.CreateSnapshot();
                File.WriteAllText(@"C:\Users\Steve\Desktop\Snapshots\" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss-tt") + ".txt", snapshot);
                return;
            }

            if (input.StartsWith("replay"))
            {
                string path   = input.Split(' ')[1];
                Replay replay = Replay.Load(path);
                Game.Replay(replay);
                return;
            }

            if (input.StartsWith("load"))
            {
                string path = input.Split(' ')[1];
                string data = File.ReadAllText(path);
                Game.PlaySnapshot(data);
                return;
            }

            if (input == "l")
            {
                isListening       = true;
                Game.UpdateEvent += OnUpdate;
                return;
            }

            if (input == "p")
            {
                isListening       = false;
                Game.UpdateEvent += OnUpdate;
                return;
            }

            if (input == "u1")
            {
                Game.SpawnUnit(0, 0, 0, 0);
                return;
            }
            if (input == "u2")
            {
                Game.SpawnUnit(0, 1, 100, 57);
                return;
            }

            try
            {
                string[] args         = input.Split(' ');
                int      unitId       = int.Parse(args[0]);
                int      playerNumber = int.Parse(args[1]);
                int      positionX    = int.Parse(args[2]);
                int      positionY    = int.Parse(args[3]);
                Game.SpawnUnit(unitId, playerNumber, positionX, positionY);
            }
            catch (Exception)
            {
                // ignored
            }
        }
示例#22
0
 protected override ReplayInputHandler CreateReplayInputHandler(Replay replay)
 => new HitokoriReplayInputHandler(replay);
示例#23
0
 public iRacingConnection()
 {
     this.Replay = new Replay(this);
     this.PitCommand = new PitCommand();
     this.iRacingMemory = new iRacingMemory();
 }
示例#24
0
 public static Replay load_replay(string name)
 {
     Debug.Log("load_replay " + Application.persistentDataPath);
     if (File.Exists(Application.persistentDataPath + "/replay/" + name))
     {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Open(Application.persistentDataPath + "/replay/" + name, FileMode.Open);
         try
         {
             SaveLoad.replay = (Replay)bf.Deserialize(file);
         }
         catch (System.Exception)
         {
             Debug.LogError("Erreur lors de la désérialisation");
             return null;
         }
         file.Close();
         return SaveLoad.replay;
     }
     return null;
 }
 public static ViewModel CreateNew()
 {
     Replay replay = new Replay();
     replay.AddAction(new CreateBoardAction(19, 19));
     ViewModel view = OpenReplayInternal(replay);
     view.Name = "New Replay " + replayCounter;
     replayCounter++;
     view.SetUnmodified();
     return view;
 }
示例#26
0
 public static string Base64EncodeStandaloneBattlelobby(Replay replay)
 {
     return(Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(",", replay.Players.Select(i => i.BattleNetRegionId + "#" + i.Name + "#" + i.BattleTag + "#" + i.Team)))));
 }
示例#27
0
        public void Heroes()
        {
            Replay rep = new Replay(@"data\1.18-ladder.w3g");
            Player p1 = rep.Players[0];
            Assert.AreEqual(2, p1.Heroes.Count);

            Assert.AreEqual(3, p1.Heroes["Ofar"].GetAbilityLevel("AOsf"));
            Assert.AreEqual(2, p1.Heroes["Ofar"].GetAbilityLevel("AOcl"));
            Assert.AreEqual(5, p1.Heroes["Ofar"].Level);

            Player p2 = rep.Players[1];

            Assert.AreEqual(3, p2.Heroes["Edem"].GetAbilityLevel("AEmb"));
            Assert.AreEqual(2, p2.Heroes["Edem"].GetAbilityLevel("AEev"));
            Assert.AreEqual(5, p2.Heroes["Edem"].Level);

            Assert.AreEqual(3, p2.Heroes["Nngs"].GetAbilityLevel("ANfa"));
            Assert.AreEqual(1, p2.Heroes["Nngs"].GetAbilityLevel("ANto"));
            //todo: watch replay to find out
            Assert.AreEqual(7, p2.Heroes["Nngs"].Level);

        }
示例#28
0
 public ReplayPlayer(Replay replay, Commands commands)
 {
     _replay   = replay;
     _commands = commands;
 }
示例#29
0
        private void extractDataB_Click(object sender, EventArgs e)
        {
            if (!chatlogCB.Checked && !killLogCB.Checked && !statisticsCB.Checked)
            {
                return;
            }

            string filename;
            string directory  = pathTextBox.Text;
            string commonName = "Found Replays";
            string output     = "The following files:" + Environment.NewLine + Environment.NewLine;

            if (chatlogCB.Checked)
            {
                filename = commonName + " Chatlog.txt";

                List <string> lines = new List <string>();
                foreach (ListViewItem lvi in resultsLV.Items)
                {
                    Replay replay = lvi.Tag as Replay;
                    lines.Add(@"\\");
                    lines.Add(@"\\ " + lvi.Text);
                    lines.Add(@"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
                    lines.AddRange(Replay_Parser.ReplayDataExtractForm.ChatsToLines(replay.Chats));
                    lines.Add("");
                }

                File.WriteAllLines(directory + "\\" + filename, lines.ToArray(), Encoding.UTF8);

                output += filename + Environment.NewLine;
            }

            if (killLogCB.Checked)
            {
                filename = commonName + " KillLog.txt";

                List <string> lines = new List <string>();
                foreach (ListViewItem lvi in resultsLV.Items)
                {
                    Replay replay = lvi.Tag as Replay;
                    lines.Add(@"\\");
                    lines.Add(@"\\ " + lvi.Text);
                    lines.Add(@"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
                    lines.AddRange(Replay_Parser.ReplayDataExtractForm.KillsToLines(replay.Kills));
                    lines.Add("");
                }

                File.WriteAllLines(directory + "\\" + filename, lines.ToArray(), Encoding.UTF8);

                output += filename + Environment.NewLine;
            }

            if (statisticsCB.Checked)
            {
                filename = commonName + " Stats.txt";

                List <string> lines = new List <string>();
                foreach (ListViewItem lvi in resultsLV.Items)
                {
                    Replay replay = lvi.Tag as Replay;
                    lines.Add(@"\\");
                    lines.Add(@"\\ " + lvi.Text);
                    lines.Add(@"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
                    lines.AddRange(Replay_Parser.ReplayDataExtractForm.PlayerStatsToLines(replay.Players));
                    lines.Add("");
                }

                File.WriteAllLines(directory + "\\" + filename, lines.ToArray(), Encoding.UTF8);

                output += filename + Environment.NewLine;
            }

            output += Environment.NewLine + "are saved to '" + directory + "'";
            MessageBox.Show(output, "Replay Data Extraction Complete");
        }
示例#30
0
 public Chromosome(Replay replay, FitnessCalculator fitnessCalculator)
 {
     Replay = replay;
     Fitness = fitnessCalculator.CalculateFitness(this);
 }
示例#31
0
 protected void LoadData(Replay replay)
 {
     txtReplayId.Text = replay.ReplayId.ToString();
     rdtReplayDate.SelectedDate = replay.ReplayDate;
     if (replay.Channel != null)
     {
         rdcChannel.Items.Clear();
         rdcChannel.Items.Add(new RadComboBoxItem(replay.Channel.Name, replay.Channel.ChannelId.ToString()));
         rdcChannel.SelectedValue = replay.Channel.ChannelId.ToString();
     }
     if (replay.Service != null)
     {
         rdcService.Items.Clear();
         rdcService.Items.Add(new RadComboBoxItem(replay.Service.Name, replay.Service.ServiceId.ToString()));
         rdcService.SelectedValue = replay.Service.ServiceId.ToString();
     }
     txtComments.Text = replay.Comments;
 }
 public PippidonAutoGenerator(IBeatmap beatmap)
     : base(beatmap)
 {
     Replay = new Replay();
 }
示例#33
0
 public OsuReplayInputHandler(Replay replay)
     : base(replay)
 {
 }
示例#34
0
    void FixedUpdate()
    {
        frames++;
        // seeGround = true;
        // isOnGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
        Debug.DrawRay(theEyes.transform.position, theEyes.transform.right * 20, Color.green);
        RaycastHit2D hit = Physics2D.Raycast(theEyes.transform.position, theEyes.transform.right * 20);

        if (hit && hit.collider.tag == "Killbox")
        {
            seeGround = false;
            Debug.DrawRay(theEyes.transform.position, theEyes.transform.right * 20, Color.red);
        }
        // double[] distancesFromObjects = new double[platforms.Length];
        // for(int i = 0; i < platforms.Length; i++)
        // {
        //  Vector3 heading = transform.position - platforms[i].transform.position;
        //  distancesFromObjects[i] = heading.magnitude;
        // }
        // // second closest, to be honest
        // System.Array.Sort(distancesFromObjects);
        // double closestPlatform = distancesFromObjects[1];
        // int indexOfClosest = distancesFromObjects.ToList().IndexOf(closestPlatform);
        // Vector3 closestPoint = platforms[indexOfClosest].transform.position;

        timer += Time.deltaTime;
        List <double> states = new List <double>();
        List <double> qs     = new List <double>();

        GameObject[] platforms    = GameObject.FindGameObjectsWithTag("platform");
        Vector3      bestPoint    = GetClosestEnemy(platforms);
        Vector3      closestPoint = GetClosestGap(platforms);

        Vector3 directionToNextPlatform = bestPoint - transform.position;
        Vector3 directionToNextGap      = closestPoint - transform.position;

        // states.Add(transform.position.y);
        // states.Add(rb.velocity.y);
        states.Add(directionToNextPlatform.x);
        // states.Add(directionToNextPlatform.y);
        states.Add(directionToNextGap.x);
        // Debug.Log(directionToNextGap.x);

        qs = SoftMax(ann.CalcOutput(states));
        double maxQ      = qs.Max();
        int    maxQIndex = qs.ToList().IndexOf(maxQ);

        exploreRate = Mathf.Clamp(exploreRate - exploreDecay, minExploreRate, maxExploreRate);

        if (Random.Range(0, 100) < exploreRate)
        {
            maxQIndex = Random.Range(0, 2);
        }

        if (maxQIndex == 1)
        {
            sumOfJumps++;
        }

        if (maxQIndex == 0)
        {
            sumOfStays++;
        }

        if (frames % 8 == 0)
        {
            if (sumOfJumps > sumOfStays)
            {
                robotAccess.RobotJump();
            }
            sumOfStays = 0;
            sumOfJumps = 0;
            frames     = 0;
        }

        if (rb.velocity.x < 0.5)
        {
            robotAccess.RobotJump();
        }

        if (hitObstacle)
        {
            reward = -5.0f;
        }
        else
        {
            reward = 0.1f;
        }



        Replay lastMemory = new Replay(
            // transform.position.y,
            // rb.velocity.y,
            directionToNextPlatform.x,
            // directionToNextPlatform.y,
            directionToNextGap.x,
            reward);

        if (replayMemory.Count > mCapacity)
        {
            replayMemory.RemoveAt(0);
        }

        replayMemory.Add(lastMemory);

        if (hitObstacle)
        {
            for (int i = replayMemory.Count - 1; i >= 0; i--)
            {
                List <double> tOutputsOld = new List <double>();
                List <double> tOutputsNew = new List <double>();
                tOutputsOld = SoftMax(ann.CalcOutput(replayMemory[i].states));

                double maxQOld = tOutputsOld.Max();
                int    action  = tOutputsOld.ToList().IndexOf(maxQOld);

                double feedback;
                if (i == replayMemory.Count - 1 || replayMemory[i].reward == -1)
                {
                    feedback = replayMemory[i].reward;
                }
                else
                {
                    tOutputsNew = SoftMax(ann.CalcOutput(replayMemory[i + 1].states));
                    maxQ        = tOutputsNew.Max();
                    feedback    = (replayMemory[i].reward + discount * maxQ);
                }

                tOutputsOld[action] = feedback;
                ann.Train(replayMemory[i].states, tOutputsOld);
            }
            if (timer > maxBalanceTime)
            {
                maxBalanceTime = timer;
            }

            timer = 0;

            hitObstacle = false;
            theGameManager.Reset();
            replayMemory.Clear();
            failCount++;
        }
    }
示例#35
0
 public KaraokeFramedReplayInputHandler(Replay replay)
     : base(replay)
 {
 }
示例#36
0
        public TestSceneReplayRecording()
        {
            Replay replay = new Replay();

            Add(new GridContainer
            {
                RelativeSizeAxes = Axes.Both,
                Content          = new[]
                {
                    new Drawable[]
                    {
                        recordingManager = new TestRulesetInputManager(new TestSceneModSettings.TestRulesetInfo(), 0, SimultaneousBindingMode.Unique)
                        {
                            Recorder = new TestReplayRecorder(new Score
                            {
                                Replay    = replay,
                                ScoreInfo = { BeatmapInfo = gameplayState.Beatmap.BeatmapInfo }
                            })
                            {
                                ScreenSpaceToGamefield = pos => recordingManager.ToLocalSpace(pos)
                            },
                            Child = new Container
                            {
                                RelativeSizeAxes = Axes.Both,
                                Children         = new Drawable[]
                                {
                                    new Box
                                    {
                                        Colour           = Color4.Brown,
                                        RelativeSizeAxes = Axes.Both,
                                    },
                                    new OsuSpriteText
                                    {
                                        Text   = "Recording",
                                        Scale  = new Vector2(3),
                                        Anchor = Anchor.Centre,
                                        Origin = Anchor.Centre,
                                    },
                                    new TestConsumer()
                                }
                            },
                        }
                    },
                    new Drawable[]
                    {
                        playbackManager = new TestRulesetInputManager(new TestSceneModSettings.TestRulesetInfo(), 0, SimultaneousBindingMode.Unique)
                        {
                            ReplayInputHandler = new TestFramedReplayInputHandler(replay)
                            {
                                GamefieldToScreenSpace = pos => playbackManager.ToScreenSpace(pos),
                            },
                            Child = new Container
                            {
                                RelativeSizeAxes = Axes.Both,
                                Children         = new Drawable[]
                                {
                                    new Box
                                    {
                                        Colour           = Color4.DarkBlue,
                                        RelativeSizeAxes = Axes.Both,
                                    },
                                    new OsuSpriteText
                                    {
                                        Text   = "Playback",
                                        Scale  = new Vector2(3),
                                        Anchor = Anchor.Centre,
                                        Origin = Anchor.Centre,
                                    },
                                    new TestConsumer()
                                }
                            },
                        }
                    }
                }
            });
        }
 public HitokoriReplayInputHandler(Replay replay) : base(replay)
 {
 }
示例#38
0
 public static int GetWinnerTeam(this Replay replay)
 {
     return(replay.Players.First(p => p.IsWinner).Team);
 }
示例#39
0
 protected override FramedReplayInputHandler CreateReplayInputHandler(Replay replay) => new PippidonFramedReplayInputHandler(replay);
示例#40
0
 public static int GetFirstPickTeam(this Replay replay)
 {
     return(replay.DraftOrder.Count < 10 ? -1 : replay.Players.First().Team);
 }
示例#41
0
文件: Brain.cs 项目: sarignamer/Unity
    private void FixedUpdate()
    {
        timer += Time.deltaTime;
        List <double> states = new List <double>();
        List <double> qs     = new List <double>();

        states.Add(this.transform.rotation.x);
        states.Add(this.transform.rotation.z);
        states.Add(this.transform.position.z);
        states.Add(ball.GetComponent <Rigidbody>().angularVelocity.x);
        states.Add(ball.GetComponent <Rigidbody>().angularVelocity.z);

        qs = ANN.SoftMax(ann.CalculateOutput(states));
        double maxQ      = qs.Max();
        int    maxQIndex = qs.ToList().IndexOf(maxQ);

        exploreRate = Mathf.Clamp(exploreRate - exploreDecay, minExploreRate, maxExploreRate);

        //check to see if we choose a random action
        if (UnityEngine.Random.Range(1, 100) < exploreRate)
        {
            maxQIndex = UnityEngine.Random.Range(0, 4);
        }

        //action 0 tilt right
        //action 1 tilt left
        //action 2 tilt forward
        //action 3 tilt backward
        //mapQIndex == 0 means action 0
        if (maxQIndex == 0)
        {
            this.transform.Rotate(Vector3.right, tiltSpeed * (float)qs[maxQIndex]);
        }
        else if (maxQIndex == 1)
        {
            this.transform.Rotate(Vector3.right, -tiltSpeed * (float)qs[maxQIndex]);
        }
        else if (maxQIndex == 2)
        {
            this.transform.Rotate(Vector3.forward, tiltSpeed * (float)qs[maxQIndex]);
        }
        else if (maxQIndex == 3)
        {
            this.transform.Rotate(Vector3.forward, -tiltSpeed * (float)qs[maxQIndex]);
        }

        if (ball.GetComponent <BallState>().dropped)
        {
            reward = -1f;
        }
        else
        {
            reward = 0.1f;
        }

        Replay lastMemory = new Replay(this.transform.rotation.x,
                                       this.transform.rotation.z,
                                       ball.transform.position.z,
                                       ball.GetComponent <Rigidbody>().angularVelocity.x,
                                       ball.GetComponent <Rigidbody>().angularVelocity.z,
                                       reward);

        if (replayMemory.Count > mCapacity)
        {
            replayMemory.RemoveAt(0);
        }

        replayMemory.Add(lastMemory);

        //Q learning starts here
        //upto this point all we did is get an inputs and getting the result from ann,
        //rewarding accordingly and then storing them.
        if (ball.GetComponent <BallState>().dropped)
        {
            //looping backwards so the quality of the last memory get carried
            //backwards up through the list so we can attributed it's blame through
            //the list
            for (int i = replayMemory.Count - 1; i >= 0; --i)
            {
                //foreach memory we ran the ann
                //first we found out what are the q values of the current memory
                List <double> currentMemoryQValues = new List <double>();
                //then we take the q values of the next memory
                List <double> nextMemoryQValues = new List <double>();
                currentMemoryQValues = ANN.SoftMax(ann.CalculateOutput(replayMemory[i].states));

                //find the maximum Q value of the current memories
                double maxQOld = currentMemoryQValues.Max();
                //which action gave that q value
                int action = currentMemoryQValues.ToList().IndexOf(maxQOld);

                double feedback;
                //checking if the current memory is the last memeory
                //or if that memory reward is -1, if it is -1, it means, that ball was dropped
                //and every memory after this is meaningless, because this is the end of the
                //memories sequance
                if ((i == replayMemory.Count - 1) || (replayMemory[i].reward == -1f))
                {
                    feedback = replayMemory[i].reward;
                }
                else
                {
                    nextMemoryQValues = ANN.SoftMax(ann.CalculateOutput(replayMemory[i + 1].states));
                    maxQ     = nextMemoryQValues.Max();
                    feedback = (replayMemory[i].reward + discount * maxQ);
                }

                //adding the correct reward (Q value) to the current action
                currentMemoryQValues[action] = feedback;
                //using the feedback to train the ANN
                ann.Train(replayMemory[i].states, currentMemoryQValues);
            }

            if (timer > maxBalanceTime)
            {
                maxBalanceTime = timer;
            }

            timer = 0;

            ball.GetComponent <BallState>().dropped = false;
            this.transform.rotation = Quaternion.identity;
            ResetBall();
            replayMemory.Clear();
            failCount++;
        }
    }
示例#42
0
 protected override ReplayInputHandler CreateReplayInputHandler(Replay replay) => new HishigataFramedReplayInputHandler(replay);
示例#43
0
 public TauAutoGenerator(IBeatmap beatmap)
     : base(beatmap)
 {
     Replay = new Replay();
 }
示例#44
0
 public EmptyFreeformFramedReplayInputHandler(Replay replay)
     : base(replay)
 {
 }
示例#45
0
        public void SetReplay(Replay.Recording recording)
        {
            if (recording == null) throw new ArgumentNullException("recording");

            m_recording = recording;
        }
示例#46
0
        public JsonResult ResponseMessage(int id, string response)
        {
            Response responseObject = null;

            try
            {
                List <BotSettings> _Settings   = null;
                BotMessage         UserMessage = null;
                BotUserData        user;

                using (KiaGalleryContext db = new KiaGalleryContext())
                {
                    _Settings   = db.BotSettings.ToList();
                    UserMessage = db.BotMessage.FirstOrDefault(x => x.Id == id);
                    user        = db.BotUserData.First(x => x.ChatId == UserMessage.ChatId);
                }

                TelegramBotClient Bot = new TelegramBotClient(_Settings.First(x => x.Key == "BotApi").Value);

                if (user.Language == 0)
                {
                    var PersianMainKeyBoard = new ReplyKeyboardMarkup();
                    PersianMainKeyBoard.Keyboard = new KeyboardButton[][] {
                        new KeyboardButton[] { _Settings.First(x => x.Key == "ContactUs").ValueFa, _Settings.First(x => x.Key == "Branch").ValueFa },
                        new KeyboardButton[] { _Settings.First(x => x.Key == "Collection").ValueFa, _Settings.First(x => x.Key == "News").ValueFa },
                        new KeyboardButton[] { _Settings.First(x => x.Key == "Persian").Value, _Settings.First(x => x.Key == "English").Value }
                    };
                    PersianMainKeyBoard.ResizeKeyboard = true;
                    Bot.SendTextMessageAsync(UserMessage.ChatId.GetValueOrDefault(), response, Telegram.Bot.Types.Enums.ParseMode.Html, false, false, UserMessage.MessageId, PersianMainKeyBoard);
                }
                else
                {
                    var EnglishMainKeyBoard = new ReplyKeyboardMarkup();
                    EnglishMainKeyBoard.Keyboard = new KeyboardButton[][] {
                        new KeyboardButton[] { _Settings.First(x => x.Key == "ContactUs").Value, _Settings.First(x => x.Key == "Branch").Value },
                        new KeyboardButton[] { _Settings.First(x => x.Key == "Collection").Value, _Settings.First(x => x.Key == "News").Value },
                        new KeyboardButton[] { _Settings.First(x => x.Key == "Persian").Value, _Settings.First(x => x.Key == "English").Value }
                    };
                    EnglishMainKeyBoard.ResizeKeyboard = true;

                    Bot.SendTextMessageAsync(UserMessage.ChatId.GetValueOrDefault(), response, Telegram.Bot.Types.Enums.ParseMode.Html, false, false, UserMessage.MessageId, EnglishMainKeyBoard);
                }

                using (KiaGalleryContext db = new KiaGalleryContext())
                {
                    UserMessage = db.BotMessage.FirstOrDefault(x => x.Id == id);
                    var Replay = new Replay()
                    {
                        Text        = response,
                        CreatedDate = DateTime.Now
                    };
                    db.BotReplay.Add(Replay);
                    UserMessage.Replay = Replay;
                    db.SaveChanges();
                }

                responseObject = new Response()
                {
                    status  = 200,
                    message = "Your response sent successfully."
                };
            }
            catch (Exception)
            {
                responseObject = new Response()
                {
                    status  = 200,
                    message = "Your response not sent successfully, try again later."
                };
            }

            return(Json(responseObject, JsonRequestBehavior.AllowGet));
        }
 private static ViewModel OpenReplayInternal(Replay replay)
 {
     ViewModel view = new ViewModel();
     view.Editor = new Editor(view);
     view.Editor.ActiveTool = Tools.Move;
     view.Game = new Game(replay);
     view.Game.Seek(view.Game.Replay.Actions.Count - 1);
     return view;
 }
        /// <summary> Parses the replay.details file, applying it to a Replay object. </summary>
        /// <param name="replay"> The replay object to apply the parsed information to. </param>
        /// <param name="buffer"> The buffer containing the replay.details file. </param>
        public static void Parse(Replay replay, byte[] buffer, bool ignoreErrors = false)
        {
            using (var stream = new MemoryStream(buffer))
                using (var reader = new BinaryReader(stream))
                {
                    var replayDetailsStructure = new TrackerEventStructure(reader);
                    replay.Players = replayDetailsStructure.dictionary[0].optionalData.array.Select(i => new Player
                    {
                        Name = i.dictionary[0].blobText,
                        BattleNetRegionId = (int)i.dictionary[1].dictionary[0].vInt.Value,
                        BattleNetSubId    = (int)i.dictionary[1].dictionary[2].vInt.Value,
                        BattleNetId       = (int)i.dictionary[1].dictionary[4].vInt.Value,
                        // [2] = Race (SC2 Remnant, Always Empty String in Heroes of the Storm)
                        Color = i.dictionary[3].dictionary.Keys.OrderBy(j => j).Select(j => (int)i.dictionary[3].dictionary[j].vInt.Value).ToArray(),
                        // [4] = Player Type (2 = Human, 3 = Computer (Practice, Try Me, or Cooperative)) - This is more accurately gathered in replay.attributes.events
                        Team     = (int)i.dictionary[5].vInt.Value,
                        Handicap = (int)i.dictionary[6].vInt.Value,
                        // [7] = VInt, Default 0 - 'm_observe'
                        IsWinner = i.dictionary[8].vInt.Value == 1,
                        // [9] = 'm_workingSetSlotId'
                        Character = i.dictionary[10].blobText
                    }).ToArray();

                    if (!ignoreErrors && (replay.Players.Length != 10 || replay.Players.Count(i => i.IsWinner) != 5))
                    {
                        // Try Me Mode, or something strange
                        return;
                    }

                    for (var i = 0; i < replay.Players.Length; i++)
                    {
                        if (replayDetailsStructure.dictionary[0].optionalData.array[i].dictionary[9].optionalData != null)
                        {
                            replay.ClientListByWorkingSetSlotID[replayDetailsStructure.dictionary[0].optionalData.array[i].dictionary[9].optionalData.vInt.Value] = replay.Players[i];
                        }
                        else
                        {
                            // Less than 0.1% of replays seem to be missing this
                            replay.ClientListByWorkingSetSlotID[i] = replay.Players[i];
                            replay.ReplayDetailParsedSuccessfully  = false;
                        }
                    }

                    replay.Map = replayDetailsStructure.dictionary[1].blobText;
                    // [2] - m_difficulty
                    // [3] - m_thumbnail - "Minimap.tga", "CustomMiniMap.tga", etc
                    // [4] - m_isBlizzardMap

                    replay.Timestamp = DateTime.FromFileTimeUtc(replayDetailsStructure.dictionary[5].vInt.Value); // m_timeUTC

                    switch (replay.ReplayBuild)
                    {
                    // There was a bug during the below builds where timestamps were buggy for the Mac build of Heroes of the Storm
                    // The replay, as well as viewing these replays in the game client, showed years such as 1970, 1999, etc
                    // I couldn't find a way to get the correct timestamp, so I am just estimating based on when these builds were live
                    case 34053 when replay.Timestamp < new DateTime(2015, 2, 8):
                        replay.Timestamp = new DateTime(2015, 2, 13);
                        break;

                    case 34190 when replay.Timestamp < new DateTime(2015, 2, 15):
                        replay.Timestamp = new DateTime(2015, 2, 20);
                        break;
                    }

                    // [6] - m_timeLocalOffset - For Windows replays, this is Utc offset.  For Mac replays, this is actually the entire Local Timestamp
                    // [7] - m_description - Empty String
                    // [8] - m_imageFilePath - Empty String
                    // [9] - m_mapFileName - Empty String
                    // [10] - m_cacheHandles - "s2ma"
                    // [11] - m_miniSave - 0
                    // [12] - m_gameSpeed - 4
                    // [13] - m_defaultDifficulty - Usually 1 or 7
                    // [14] - m_modPaths - Null
                    // [15] - m_campaignIndex - 0
                    // [16] - m_restartAsTransitionMap - 0
                }
        }
示例#49
0
        public static void Parse()
        {
            var dialog = new OpenFileDialog
            {
                InitialDirectory = Path.GetPath(),
                Filter = Resources.mouseMoverThread_parse_osr_files____osr____osr,
                FilterIndex = 1,
                RestoreDirectory = true
            };
            if (dialog.ShowDialog() != DialogResult.OK) return;
            var path = dialog.FileName;
            Rep.Clear();
            var originalReplay = new Replay(path, true);
            _mode = originalReplay.GameMode;
            var index = 0;
            while (index < originalReplay.ReplayFrames.Count - 2)
            {
                var thisFrame = originalReplay.ReplayFrames[index];

                if (thisFrame.Time < 0) { index++; continue; } // i don't like negative time :)

                var futureFrame = originalReplay.ReplayFrames[index + 1];
                var frame = new ReplayFrame
                {
                    X = thisFrame.X,
                    Y = thisFrame.Y,
                    Time = thisFrame.Time,
                    Keys = thisFrame.Keys
                };
                Rep.Add(frame);

                //Smooth linear moving
                if (thisFrame.Time > 0 && futureFrame.TimeDiff > 19)
                {
                    var steps = futureFrame.TimeDiff / 10;
                    var xMult = (futureFrame.X - thisFrame.X) / steps;
                    var yMult = (futureFrame.Y - thisFrame.Y) / steps;

                    var startX = thisFrame.X;
                    var startY = thisFrame.Y;
                    var startTime = thisFrame.Time;
                    var startBtn = thisFrame.Keys;
                    for (var i = 0; i < steps; i++)
                    {
                        startX = startX + xMult;
                        startY = startY + yMult;
                        startTime = startTime + 10;
                        var smoothFrame = new ReplayFrame
                        {
                            X = startX,
                            Y = startY,
                            Time = startTime,
                            Keys = startBtn
                        };
                        Rep.Add(smoothFrame);
                    }
                }

                index++;
            }

            var speedFrame = new ReplayFrame
            {
                X = 0,
                Y = 0,
                Keys = KeyData.None,
                Time = 999999999
            };
            for (var i = 0; i < 4; i++) // I'm use it for speed up... Really, it don't good...
            {
                Rep.Add(speedFrame);
            }

            Menu.ReplayParsed = true;
        }
示例#50
0
 public static void save_replay(Replay replay)
 {
     Debug.Log("save_replay " + Application.persistentDataPath);
     SaveLoad.replay = replay;
     BinaryFormatter bf = new BinaryFormatter();
     FileStream file = File.Create(Application.persistentDataPath + "/replay.txt");
     bf.Serialize(file, replay);
     file.Close();
 }
示例#51
0
        public void Rep120()
        {
            Replay rep = new Replay(@"data\1.20.w3g");
            Assert.AreEqual(9, rep.Players.Count);

            Assert.AreEqual(Race.Human, rep.Players[1].Race);
            //this is right. w3g master is wrong.
            Assert.AreEqual(PlayerColor.Yellow, rep.Players[1].Color);
            Assert.AreEqual(100, rep.Players[1].Handicap);
            //this time may be wrong
            Assert.AreEqual(new TimeSpan(0, 0, 22, 29, 616), rep.Players[1].GetTime());

            Assert.AreEqual(4361, rep.Players[1].Actions);
            Assert.AreEqual(6258, rep.Players[7].Actions);

            Assert.AreEqual(Race.Undead, rep.Players[7].Race);
            Assert.AreEqual(PlayerColor.Gray, rep.Players[7].Color);
            Assert.AreEqual(100, rep.Players[2].Handicap);
        }
示例#52
0
 private void AddGhost(Replay replay)
 {
     if (Any(replay))
         return;
     replaysLoaded = true;
     Player gh = InstanciatePlayer();
     gh.playerNameTxt.text = Trn(replay.playerName);
     gh.ghost = true;
     //var carSkin = Random.Range(0, _Loader.CarSkins.Count);
     gh.replay = replay;
     //if (gameType == GameType.VsPlayers && replay.playerName != _Loader.playerName && !_Loader.GetCarSkin(carSkin).special && replay.carSkin == 0)
     //replay.carSkin = carSkin;
     //gh.playBackTime = Random.Range(.9f, 1f);
 }
示例#53
0
 public void ZipOK()
 {
     Replay replay1 = new Replay(@"data\1.20.w3g");
     Replay replay2 = new Replay(@"data\ladder.w3g");
 }
示例#54
0
        private static void DetailedParse(BitReader bitReader, Replay replay, uint s2maCacheHandlesLength)
        {
            bitReader.AlignToByte();
            for (; ;)
            {
                // we're just going to skip all the way down to the s2mh
                if (bitReader.ReadString(4) == "s2mh")
                {
                    bitReader.stream.Position -= 4;
                    break;
                }
                else
                {
                    bitReader.stream.Position -= 3;
                }
            }

            // bitReader.Read(???); // this depends on previous data (not byte aligned)

            // s2mh cache handles
            // uint s2mhCacheHandlesLength = bitReader.Read(6);
            // for (int i = 0; i < s2mhCacheHandlesLength; i++)
            for (var i = 0; i < s2maCacheHandlesLength; i++)
            {
                bitReader.AlignToByte();
                if (bitReader.ReadString(4) != "s2mh")
                {
                    throw new Exception($"s2mh cache");
                }

                bitReader.ReadBytes(36);
            }

            // Player collections - starting with HOTS 2.0 (live build 52860)
            // strings gone starting with build (ptr) 55929
            // --------------------------------------------------------------
            var playerCollection = new List <string>();

            int collectionSize = replay.ReplayBuild >= 48027 ? bitReader.ReadInt16() : bitReader.ReadInt32();

            if (collectionSize > 8000)
            {
                throw new DetailedParsedException("collectionSize is an unusually large number");
            }

            for (var i = 0; i < collectionSize; i++)
            {
                if (replay.ReplayBuild >= 55929)
                {
                    bitReader.ReadBytes(8); // most likey an identifier for the item; first six bytes are 0x00
                }
                else
                {
                    playerCollection.Add(bitReader.ReadString(bitReader.ReadByte()));
                }
            }

            // use to determine if the collection item is usable by the player (owns/free to play/internet cafe)
            if (bitReader.ReadInt32() != collectionSize)
            {
                throw new DetailedParsedException("skinArrayLength not equal");
            }

            for (var i = 0; i < collectionSize; i++)
            {
                for (var j = 0; j < 16; j++) // 16 is total player slots
                {
                    bitReader.ReadByte();

                    var num = bitReader.Read(8);

                    if (replay.ReplayBuild < 55929)
                    {
                        if (replay.ClientListByUserID[j] != null)
                        {
                            if (num > 0)
                            {
                                replay.ClientListByUserID[j].PlayerCollectionDictionary.Add(playerCollection[i], true);
                            }
                            else if (num == 0)
                            {
                                replay.ClientListByUserID[j].PlayerCollectionDictionary.Add(playerCollection[i], false);
                            }
                            else
                            {
                                throw new NotImplementedException();
                            }
                        }
                    }
                }
            }

            if (replay.ReplayBuild >= 85027)
            {
                // m_disabledHeroList
                uint disabledHeroListLength = bitReader.Read(8);

                for (int i = 0; i < disabledHeroListLength; i++)
                {
                    string disabledHeroAttributeId = bitReader.ReadStringFromBits(32, true);

                    if (replay.DisabledHeroes.Count == 0)
                    {
                        replay.DisabledHeroes.Add(disabledHeroAttributeId);
                    }
                }
            }

            // Player info
            // ------------------------

            // m_randomSeed, set it if it hasn't been set
            if (replay.RandomValue == 0)
            {
                replay.RandomValue = (uint)bitReader.ReadInt32();
            }
            else
            {
                bitReader.ReadInt32();
            }

            bitReader.ReadBytes(4);

            uint playerListLength = bitReader.Read(5);

            for (uint i = 0; i < playerListLength; i++)
            {
                bitReader.Read(32);

                bitReader.Read(5); // player index

                // toon
                bitReader.Read(8);                                    // m_region
                if (bitReader.ReadStringFromBits(32, true) != "Hero") // m_programId
                {
                    throw new DetailedParsedException("Not Hero");
                }
                bitReader.Read(32);     // m_realm
                bitReader.ReadLong(64); // m_id

                // internal toon
                bitReader.Read(8);                                    // m_region
                if (bitReader.ReadStringFromBits(32, true) != "Hero") // m_programId
                {
                    throw new DetailedParsedException("Not Hero");
                }
                bitReader.Read(32); // m_realm

                int idLength = (int)bitReader.Read(7) + 2;
                bitReader.AlignToByte();
                replay.ClientListByUserID[i].BattleNetTId = bitReader.ReadString(idLength);

                bitReader.Read(6);

                if (replay.ReplayBuild <= 47479)
                {
                    // internal toon repeat
                    bitReader.Read(8);                                    // m_region
                    if (bitReader.ReadStringFromBits(32, true) != "Hero") // m_programId
                    {
                        throw new DetailedParsedException("Not Hero");
                    }
                    bitReader.Read(32); // m_realm

                    idLength = (int)bitReader.Read(7) + 2;
                    bitReader.AlignToByte();
                    if (replay.ClientListByUserID[i].BattleNetTId != bitReader.ReadString(idLength))
                    {
                        throw new DetailedParsedException("Duplicate internal id does not match");
                    }
                }

                bitReader.Read(2);
                bitReader.ReadBytes(25);
                bitReader.Read(24);

                if (replay.GameMode == GameMode.Cooperative)
                {
                    bitReader.ReadBytes(8); // ai games have 8 more bytes somewhere around here
                }
                bitReader.Read(7);

                if (!bitReader.ReadBoolean())
                {
                    // repeat of the collection section above
                    if (replay.ReplayBuild >= 51609 || replay.ReplayBuild == 47903 || replay.ReplayBuild == 47479)
                    {
                        bitReader.ReadBitArray(bitReader.Read(12));
                    }
                    else if (replay.ReplayBuild > 47219)
                    {
                        // each byte has a max value of 0x7F (127)
                        bitReader.ReadBytes((int)bitReader.Read(15) * 2);
                    }
                    else
                    {
                        bitReader.ReadBitArray(bitReader.Read(9));
                    }

                    bitReader.ReadBoolean();
                }

                bitReader.ReadBoolean(); // m_hasSilencePenalty

                if (replay.ReplayBuild >= 61718)
                {
                    bitReader.ReadBoolean();
                    bitReader.ReadBoolean(); // m_hasVoiceSilencePenalty
                }

                if (replay.ReplayBuild >= 66977)
                {
                    bitReader.ReadBoolean();                                                                 // m_isBlizzardStaff
                }
                if (bitReader.ReadBoolean())                                                                 // is player in party
                {
                    replay.ClientListByUserID[i].PartyValue = bitReader.ReadInt32() + bitReader.ReadInt32(); // players in same party will have the same exact 8 bytes of data
                }
                bitReader.ReadBoolean();                                                                     // has battletag?

                var battleTag = Encoding.UTF8.GetString(bitReader.ReadBlobPrecededWithLength(7)).Split('#'); // battleTag <name>#xxxxx

                if (battleTag[0] != replay.ClientListByUserID[i].Name)
                {
                    throw new DetailedParsedException("Couldn't find BattleTag");
                }

                if (battleTag.Length == 2)
                {
                    replay.ClientListByUserID[i].BattleTag = int.Parse(battleTag[1]);
                }

                if (replay.ReplayBuild >= 52860 || (replay.ReplayVersionMajor == 2 && replay.ReplayBuild >= 51978))
                {
                    replay.ClientListByUserID[i].AccountLevel = (int)bitReader.Read(32);  // in custom games, this is a 0
                }
                if (replay.ReplayBuild >= 69947)
                {
                    bitReader.ReadBoolean(); // m_hasActiveBoost
                }
            }

            // some more data after this
            // there is also a CSTM string down here, if it exists, the game is a custom game
        }
示例#55
0
 public TauFramedReplayInputHandler(Replay replay)
     : base(replay)
 {
 }
示例#56
0
 protected bool CreateChange()
 {
     if (!DataOk())
         return false;
     if (replay == null)
     {
         replay = new Replay();
         UnloadData(replay);
         ctx.Add(replay);
     }
     else
     {
         replay = CntAriCli.GetReplay(replayId, ctx);
         UnloadData(replay);
     }
     ctx.SaveChanges();
     return true;
 }
示例#57
0
        // used for builds <= 47479 and 47903
        private static void ExtendedBattleTagParsingOld(Replay replay, BitReader bitReader)
        {
            bool changed47479 = replay.ReplayBuild == 47479 && DetectBattleTagChangeBuild47479(replay, bitReader);

            for (var i = 0; i < replay.ClientListByUserID.Length; i++)
            {
                if (replay.ClientListByUserID[i] == null)
                {
                    break;
                }

                string TId;
                string TId_2;

                // this first one is weird, nothing to indicate the length of the string
                if (i == 0)
                {
                    var offset = bitReader.ReadByte();
                    bitReader.ReadString(2); // T:
                    TId = bitReader.ReadString(12 + offset);

                    if (replay.ReplayBuild <= 47479 && !changed47479)
                    {
                        bitReader.ReadBytes(6);
                        ReadByte0x00(bitReader);
                        ReadByte0x00(bitReader);
                        ReadByte0x00(bitReader);
                        bitReader.Read(6);

                        // get T: again
                        TId_2 = Encoding.UTF8.GetString(ReadSpecialBlob(bitReader, 8));

                        if (TId != TId_2)
                        {
                            throw new DetailedParsedException("TID dup not equal");
                        }
                    }
                }
                else
                {
                    ReadByte0x00(bitReader);
                    ReadByte0x00(bitReader);
                    ReadByte0x00(bitReader);
                    bitReader.Read(6);

                    // get XXXXXXXX#YYY
                    TId = Encoding.UTF8.GetString(ReadSpecialBlob(bitReader, 8));

                    if (replay.ReplayBuild <= 47479 && !changed47479)
                    {
                        bitReader.ReadBytes(6);
                        ReadByte0x00(bitReader);
                        ReadByte0x00(bitReader);
                        ReadByte0x00(bitReader);
                        bitReader.Read(6);

                        // get T: again
                        TId_2 = Encoding.UTF8.GetString(ReadSpecialBlob(bitReader, 8));

                        if (TId != TId_2)
                        {
                            throw new DetailedParsedException("TID dup not equal");
                        }
                    }
                }
                replay.ClientListByUserID[i].BattleNetTId = TId;

                // next 31 bytes
                bitReader.ReadBytes(4); // same for all players
                bitReader.ReadByte();
                bitReader.ReadBytes(8); // same for all players
                bitReader.ReadBytes(4);

                bitReader.ReadBytes(14); // same for all players

                if (replay.ReplayBuild >= 47903 || changed47479)
                {
                    bitReader.ReadBytes(40);
                }
                else if (replay.ReplayBuild >= 47219 || replay.ReplayBuild == 47024)
                {
                    bitReader.ReadBytes(39);
                }
                else if (replay.ReplayBuild >= 45889)
                {
                    bitReader.ReadBytes(38);
                }
                else if (replay.ReplayBuild >= 45228)
                {
                    bitReader.ReadBytes(37);
                }
                else if (replay.ReplayBuild >= 44468)
                {
                    bitReader.ReadBytes(36);
                }
                else
                {
                    bitReader.ReadBytes(35);
                }

                if (replay.ReplayBuild >= 47903 || changed47479)
                {
                    bitReader.Read(1);
                }
                else if (replay.ReplayBuild >= 47219 || replay.ReplayBuild == 47024)
                {
                    bitReader.Read(6);
                }
                else if (replay.ReplayBuild >= 46690 || replay.ReplayBuild == 46416)
                {
                    bitReader.Read(5);
                }
                else if (replay.ReplayBuild >= 45889)
                {
                    bitReader.Read(2);
                }
                else if (replay.ReplayBuild >= 45228)
                {
                    bitReader.Read(3);
                }
                else
                {
                    bitReader.Read(5);
                }

                if (bitReader.ReadBoolean())
                {
                    // use this to determine who is in a party
                    // those in the same party will have the same exact 8 bytes of data
                    // the party leader is the first one (in the order of the client list)
                    replay.ClientListByUserID[i].PartyValue = bitReader.ReadInt32() + bitReader.ReadInt32();
                }

                bitReader.Read(1);
                var battleTag = Encoding.UTF8.GetString(bitReader.ReadBlobPrecededWithLength(7)).Split('#'); // battleTag <name>#xxxxx

                if (battleTag.Length != 2 || battleTag[0] != replay.ClientListByUserID[i].Name)
                {
                    throw new DetailedParsedException("Couldn't find BattleTag");
                }

                replay.ClientListByUserID[i].BattleTag = int.Parse(battleTag[1]);

                // these similar bytes don't occur for last player
                bitReader.ReadBytes(27);
            }

            // some more bytes after (at least 700)
            // theres some HeroICONs and other repetitive stuff
        }
示例#58
0
        private static void GetBattleTags(Replay replay, BitReader reader)
        {
            // Search for the BattleTag for each player
            var battleTagDigits = new List <char>();

            for (var playerNum = 0; playerNum < replay.Players.Length; playerNum++)
            {
                var player = replay.Players[playerNum];
                if (player == null || string.IsNullOrEmpty(player.Name))
                {
                    continue;
                }

                // Find each player's name, and then their associated BattleTag
                battleTagDigits.Clear();
                var playerNameBytes = Encoding.UTF8.GetBytes(player.Name);
                while (!reader.EndOfStream)
                {
                    var isFound = true;
                    for (var i = 0; i < playerNameBytes.Length + 1; i++)
                    {
                        if ((i == playerNameBytes.Length && reader.ReadByte() != 35 /* '#' Character */) || (i < playerNameBytes.Length && reader.ReadByte() != playerNameBytes[i]))
                        {
                            isFound = false;
                            break;
                        }
                    }

                    if (isFound)
                    {
                        break;
                    }
                }

                // Get the digits from the BattleTag
                while (!reader.EndOfStream)
                {
                    var currentCharacter = (char)reader.ReadByte();

                    if (playerNum == 9 && (currentCharacter == 'z' || currentCharacter == 'Ø'))
                    {
                        // If player is in slot 9, there's a chance that an extra digit could be appended to the BattleTag
                        battleTagDigits.RemoveAt(battleTagDigits.Count - 1);
                        break;
                    }
                    else if (char.IsDigit(currentCharacter))
                    {
                        battleTagDigits.Add(currentCharacter);
                    }
                    else
                    {
                        break;
                    }
                }

                if (reader.EndOfStream)
                {
                    break;
                }
                else if (battleTagDigits.Count == 0)
                {
                    continue;
                }

                player.BattleTag = int.Parse(string.Join("", battleTagDigits));
            }
        }
 //obsolete
 private void LoadPlayerPreviews2(List<string> list, List<Replay> previews)
 {
     for (int i = list.Count - 1; i >= 0; i--)
     {
         var nick = list[i];
         if (Any(previews, nick)) continue;
         var path = "replays/" + nick + "." + mapNamePrefixed + ".info";
         Download(mainSite + path, delegate(string s, bool b)
         {
             if (!b)
                 return;
             var ss = s.Split(new[] { "\r", "\n", "\\n", "\\r\\n" }, StringSplitOptions.RemoveEmptyEntries);
             try
             {
                 var replay = new Replay();
                 replay.playerName = nick;
                 replay.finnishTime = float.Parse(ss[0]);
                 replay.avatarId = int.Parse(ss[1]);
                 replay.dif = ss.Length > 2 ? (Difficulty)int.Parse(ss[2]) : Difficulty.Easy;
                 replay.backupRetries = ss.Length > 3 ? int.Parse(ss[3]) : -1;
                 previews.Add(replay);
             } catch (Exception e) { Debug.LogError(e); }
             previews.Sort(previews[0]);
         }, false);
     }
 }
 private Replay ReadReplay(byte[] buffer)
 {
     Replay rep = new Replay();
     if (buffer == null) { print("Buffer is null"); return rep; }
     rep.contry = _Loader.Country;
     using (var ms = new BinaryReader(buffer))
     {
         Vector3 oldPos = Vector3.zero;
         float oldmeters = 0;
         PosVel posvel = null;
         int vers = 0;
         int errors = 0;
         while (ms.Position < ms.Length)
         {
             lastRd = curredRd;
             var b = curredRd = ms.ReadByte();
             try
             {
                 if (b == RD.playerName)
                 {
                     rep.playerName = ms.ReadString();
                     Debug.LogWarning(rep.playerName);
                 }
                 else if (b == RD.clan)
                     rep.clanTag = ms.ReadString();
                 else if (b == RD.version)
                 {
                     if (vers == 1241 || vers == 1234) return null;
                     vers = ms.ReadInt();
                 }
                 else if (b == RD.posVel)
                 {
                     posvel = new PosVel();
                     posvel.pos = ms.ReadVector();
                     if (oldPos == Vector3.zero)
                         oldPos = posvel.pos;
                     posvel.meters = oldmeters = oldmeters + (posvel.pos - oldPos).magnitude;
                     oldPos = posvel.pos;
                     posvel.rot.eulerAngles = ms.ReadVector();
                     posvel.vel = ms.ReadVector();
                     rep.posVels.Add(posvel);
                 }
                 else if (b == RD.score)
                     /*posvel.score = */
                     ms.ReadInt();
                 else if (b == RD.posVelMouse)
                     posvel.mouserot = ms.ReadFloat();
                 else if (b == RD.posVelSkid)
                     posvel.skid = ms.ReadFloat();
                 else if (b == RD.keyCode)
                 {
                     var kc = (KeyCode)ms.ReadInt();
                     float t = ms.ReadFloat();
                     bool d = ms.ReadBool();
                     //if (Player.recordKeys.Contains(kc))
                     rep.keyDowns.Add(new KeyDown() { down = d, keyCode = kc, time = t });
                 }
                 else if (b == RD.avatarId)
                     rep.avatarId = ms.ReadInt();
                 else if (b == RD.carSkin)
                     rep.carSkin = ms.ReadInt();
                 else if (b == RD.FinnishTime)
                     rep.finnishTime = ms.ReadFloat();
                 else if (b == RD.country)
                 {
                     CountryCodes countryCodes = (CountryCodes)ms.ReadByte();
                     //if (countryCodes != CountryCodes.fi)
                     rep.contry = countryCodes;
                     //print("Read Country " + rep.contry);
                 }
                 else if (b == RD.color)
                     rep.color = new Color(ms.ReadFloat(), ms.ReadFloat(), ms.ReadFloat());
                 else if (b == RD.avatarUrl)
                     rep.avatarUrl = ms.ReadString();
                 else if (b == RD.rank)
                     rep.rank = ms.ReadInt();
                 else
                 {
                     if (errors == 0)
                         Debug.LogError("byte unknown type " + b + " lastType " + lastRd + " version " + vers);
                     errors++;
                     //if (isDebug)
                     //    Debug.LogError("byte unknown type " + b);
                 }
             }
             catch (Exception e)
             {
                 if (errors == 0)
                     Debug.LogError("error curType" + b + " lastType " + lastRd + " version " + vers + "\n" + e);
                 errors++;
             }
         }
         print("Replay version " + vers + " errors" + errors);
     }
     return rep;
 }