public void cargarGrillaPacientes()
        {
            //Creamos un documento y lo cargamos con los datos del XML.
            XmlDocument documento = new XmlDocument();

            documento.Load(ruta);

            //Obtenemos una colección con todos los pacientes.
            XmlNodeList listaPacientes = documento.SelectNodes("pacientes/paciente");

            //Creamos un único profesional.
            XmlNode Pac;

            //Limpiamos datagridview
            dgv.Rows.Clear();
            //Recorremos toda la lista de pacientes.
            for (int i = 0; i < listaPacientes.Count; i++)
            {
                //Obtenemos cada profesional.
                Pac = listaPacientes.Item(i);

                //Obtenemos valores para cada fila
                string idPac = Pac.SelectSingleNode("idPaciente").InnerText;
                string nom   = Pac.SelectSingleNode("nombre").InnerText;
                string ape   = Pac.SelectSingleNode("apellidos").InnerText;
                string dir   = Pac.SelectSingleNode("direccion").InnerText;
                string tel   = Pac.SelectSingleNode("telefono").InnerText;
                string mail  = Pac.SelectSingleNode("correo").InnerText;

                //Insertamos nueva fila en datagridview
                dgv.Rows.Add(idPac, nom, ape, dir, tel, mail, "Eliminar");
                dgv.Update();
            }
        }
Example #2
0
        private MoveAction MoveToRandomPellet(Pac pac)
        {
            var cell         = _game.Map.Cells[pac.Position.Y, pac.Position.X];
            var closestCells = BFS.GetClosestCells(cell, GetClosestCellCondition(pac), GetObstacleCondition(pac), 20);

            if (closestCells.Any())
            {
                var closestCell = closestCells.OrderByDescending(c => c.VisibleCells.Count()).First();
                Io.Debug($"Pac Id {pac.Id} : Random Uneaten pellet Position: {closestCell.Position}");
                _chosenCells[pac.Id] = closestCell;

                var path = BFS.GetPath(cell, closestCell, GetObstacleCondition(pac));
                if (path != null)
                {
                    var nextCell = path.First();
                    _moveCells.Add(nextCell);

                    if (pac.SpeedTurnsLeft > 0 && path.Count >= 2)
                    {
                        nextCell = path.Skip(1).First();
                        _moveCells.Add(nextCell);
                    }

                    Io.Debug($"Pac Id: {pac.Id} : Random Uneaten pellet Position {_chosenCells[pac.Id].Position} : Next cell position {nextCell.Position}");
                    {
                        return(new MoveAction(nextCell.Position));
                    }
                }
            }

            return(null);
        }
Example #3
0
        private MoveAction AddChosenCellAction(Pac pac, Cell cell)
        {
            if (_chosenCells.ContainsKey(pac.Id) && _chosenCells[pac.Id].HasPellet)
            {
                var path = BFS.GetPath(cell, _chosenCells[pac.Id], GetObstacleCondition(pac, cell));
                if (path != null)
                {
                    var nextCell = path.First();
                    _moveCells.Add(nextCell);

                    if (pac.SpeedTurnsLeft > 0 && path.Count >= 2)
                    {
                        nextCell = path.Skip(1).First();
                        _moveCells.Add(nextCell);
                    }

                    Io.Debug($"Pac Id: {pac.Id} : Chosen Cell Position {_chosenCells[pac.Id].Position} : Next cell position {nextCell.Position}");
                    {
                        return(new MoveAction(nextCell.Position));
                    }
                }
            }

            return(null);
        }
Example #4
0
    public void Update()
    {
        //Log("Begin","++++++++++++++");;
        base.Update();
        if (sendingQueue.Count > 0)
        {
            for (int i = 0; i < sendingQueue.Count; i++)
            {
                Pac pack = (Pac)sendingQueue[i];
                pack.data.Add("from", CharacterInfo._instance.idUserSocketIO);

                socket.Emit("cmd", pack.type, pack.data);
                Log("send pack ", pack.type + " " + pack.data["messageID"] + " " + pack.data.Keys.Count);

                if (pack.type == IN_TURN_REQUEST)
                {
                    foreach (string key in pack.data.Keys)
                    {
                        Log("before sending pack in Turn Request in Master ", key);
                    }
                }

                sendingQueue.RemoveAt(i);

                i--;
            }
        }
        //Log("End", "++++++++++++++"); ;
    }
Example #5
0
        private MoveAction GetMoveAction(Pac pac)
        {
            var cell = _game.Map.Cells[pac.Position.Y, pac.Position.X];

            var action = GetMoveActionInSamePosition(pac, cell);

            if (action != null)
            {
                return(action);
            }

            action = MoveToNeighbourPellet(pac, cell);
            if (action != null)
            {
                return(action);
            }

            action = AddChosenCellAction(pac, cell);
            if (action != null)
            {
                return(action);
            }

            action = MoveToRandomPellet(pac);
            if (action != null)
            {
                return(action);
            }

            return(new MoveAction(cell.Position));
        }
Example #6
0
        public NextAction Next(Pac pac, CancellationToken cancellation, params Pac[] enemies)
        {
            if (!enemies.Any())
            {
                return(new NoAction(pac));
            }

            var closestY = enemies.OrderBy(p => Math.Abs(p.Location.X - pac.Location.X)).First();
            var closestX = enemies.OrderBy(p => Math.Abs(p.Location.Y - pac.Location.Y)).First();
            Pac closestEnemy;

            if (Math.Abs(closestX.Location.X - pac.Location.X) < Math.Abs(closestY.Location.Y - pac.Location.Y))
            {
                closestEnemy = closestX;
            }
            else
            {
                closestEnemy = closestX;
            }

            var typeToBeatEnemy = PacType.ToBeat(closestEnemy.Type);

            if (pac.SpecialActionReady && pac.Type != typeToBeatEnemy)
            {
                Console.Error.WriteLine($"Me {pac.Id} {pac.Type} switching to {typeToBeatEnemy}");
                return(new SwitchAction(pac, typeToBeatEnemy));
            }

            if (pac.Type.Play(closestEnemy.Type) == PacType.Outcome.Win)
            {
                return(new MoveAction(pac, closestEnemy.Location));
            }

            return(new NoAction(pac));
        }
Example #7
0
        private void PacFiles_DragDrop(object sender, DragEventArgs e)
        {
            List <string> paths = ((string[])e.Data.GetData(DataFormats.FileDrop)).ToList();

            Console.WriteLine(Path.GetExtension(paths[0]));
            if (paths.Count == 1 && Path.GetExtension(paths[0] ?? "").Equals(".pac", StringComparison.InvariantCultureIgnoreCase))
            {
                pac?.Dispose();
                PacFiles.Items.Clear();

                pac = new Pac();
                pac.LoadFile(paths[0]);

                PacFiles.Items.AddRange(pac.Files.Select(entry => new ListViewItem(entry.Path.ZeroTerminatedString)
                {
                    Tag = entry
                }).ToArray());
            }
            else
            {
                List <string> directories = new List <string>();
                List <string> files       = new List <string>();
                paths.ForEach(path =>
                {
                    if (Directory.Exists(path))
                    {
                        directories.Add(path);
                        files.AddRange(Directory.GetFiles(path, "*", SearchOption.AllDirectories));
                    }
                });

                directories.ForEach(directory => paths.Remove(directory));
                paths.AddRange(files);

                if (pac == null)
                {
                    MessageBox.Show("Please load a .pac first !", "Warning !", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    foreach (var file in paths)
                    {
                        string correspondingPath = (from ListViewItem pacFile in PacFiles.Items select pacFile.Text).ToList().Find(path => file.Contains(path));
                        if (correspondingPath == null)
                        {
                            MessageBox.Show($"{file} isn't present in the currently opened .pac !", "Not found !", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            continue;
                        }

                        ListViewItem item = PacFiles.Items.Cast <ListViewItem>().FirstOrDefault(fileItem => fileItem.Text == correspondingPath);
                        item.ForeColor = Color.Red;

                        var entry      = (PacEntry)item.Tag;
                        var fileStream = File.OpenRead(file);

                        entry.SetFile(false, (int)fileStream.Length, fileStream, 0, (int)fileStream.Length, false, false);
                    }
                }
            }
        }
    static void Main()
    {
        Sprite s = new Sprite();

        s.Mover();
        Pac p = new Pac(8, 10);

        p.Mostrar();
        p.Mover();
        Fantasma f1 = new Fantasma(15, 12);

        f1.Mostrar();
        f1.Mover();
        Fantasma f2 = new Fantasma(17, 14);

        f2.Mostrar();
        f2.Mover();
        Fantasma f3 = new Fantasma(19, 16);

        f3.Mostrar();
        f3.Mover();
        Fantasma f4 = new Fantasma(21, 18);

        f4.Mostrar();
        f4.Mover();
    }
Example #9
0
 private bool ShouldAvoidCell(Pac pac, Cell cell)
 {
     return(_chosenCells.ContainsValue(cell) ||
            IsOpponentInCell(pac, cell) ||
            GetPacInCell(cell, _game.MyPlayer.Pacs) != null ||
            _moveCells.Contains(cell));
 }
Example #10
0
 private bool ShouldAvoidCell(Pac pac, Cell neighbour)
 {
     return(_chosenCells.ContainsValue(neighbour) ||
            IsOpponentInCell(pac, neighbour) ||
            GetPacInCell(neighbour, _game.MyPlayer.Pacs) != null ||
            _moveCells.Contains(neighbour));
 }
Example #11
0
        public NextAction Next(Pac pac, CancellationToken cancellation)
        {
            if (pac.LocationHistory.Count < 2)
            {
                return(new MoveAction(pac, _gameGrid.RandomLocation));
            }

            return(new MoveAction(pac, pac.LocationHistory[^ 2]));
Example #12
0
        public void HashCodesDifferOnMine()
        {
            var left  = new Pac(1, true, new FixedMovementStrategy(), new GiveWayMovementStrategy(null));
            var right = new Pac(1, false, new FixedMovementStrategy(), new GiveWayMovementStrategy(null));

            Assert.NotEqual(left.Key, right.Key);
            Assert.NotEqual(left.GetHashCode(), right.GetHashCode());
        }
Example #13
0
    public void Play()
    {
        // reset target pellet if pellet not existing anymore
        foreach (Pac pa in GetMyPacs().Where(p => p.TargetPellet != null).ToList())
        {
            if (!Pellets.Any(pe => pe.Position == pa.TargetPellet.Position))
            {
                pa.TargetPellet = null;
            }
        }

        // IF big pellets
        List <Pellet> bigPellets = Pellets.Where(p => p.Value == 10).ToList();

        foreach (Pellet pe in bigPellets)
        {
            Pac pa = GetMyPacs().OrderBy(p => p.Distance(pe)).First();

            if (pa.TargetPellet == null || pe.Distance(pa) < pa.TargetPellet.Distance(pa))
            {
                pa.TargetPellet = pe;
            }
        }
        Debug(Grid.ToString());
        foreach (Pac p in GetMyPacs())
        {
            if (p.TargetPellet == null)
            {
                List <Pellet> AlreadyTargeted = GetMyPacs().Select(e => e.TargetPellet).Where(e => e != null).ToList();

                p.TargetPellet = GetPelletsNearest(p).Except(AlreadyTargeted).FirstOrDefault();

                if (p.TargetPellet == null)
                {
                    p.TargetPellet = GetPelletsNearest(p).FirstOrDefault();
                }
            }

            if (p.TargetPellet != null)
            {
                p.Move(p.TargetPellet.Position);
            }
            else
            {
                Cell target = Grid.Map.Cast <Cell>().Where(e => e.HasPellet).OrderBy(e => p.Distance(e.Position)).FirstOrDefault();

                if (target != null)
                {
                    p.Move(target.Position);
                }
                else
                {
                    p.Move(p.Position);
                }
            }
        }
        Console.WriteLine();
    }
Example #14
0
        private void comboBoxCodePage_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxCodePage.SelectedIndex >= 0)
            {
                CodePageIndex = comboBoxCodePage.SelectedIndex;
                if (_previewBuffer != null)
                {
                    Encoding  encoding     = Pac.GetEncoding(CodePageIndex);
                    const int feIndex      = 0;
                    const int endDelimiter = 0x00;
                    var       sb           = new StringBuilder();
                    int       index        = feIndex + 3;
                    while (index < _previewBuffer.Length && _previewBuffer[index] != endDelimiter)
                    {
                        if (_previewBuffer[index] == 0xFE)
                        {
                            sb.AppendLine();
                            index += 2;
                        }
                        else if (_previewBuffer[index] == 0xFF)
                        {
                            sb.Append(' ');
                        }
                        else if (CodePageIndex == Pac.CodePageLatin)
                        {
                            sb.Append(Pac.GetLatinString(encoding, _previewBuffer, ref index));
                        }
                        else if (CodePageIndex == Pac.CodePageArabic)
                        {
                            sb.Append(Pac.GetArabicString(_previewBuffer, ref index));
                        }
                        else if (CodePageIndex == Pac.CodePageHebrew)
                        {
                            sb.Append(Pac.GetHebrewString(_previewBuffer, ref index));
                        }
                        else if (CodePageIndex == Pac.CodePageCyrillic)
                        {
                            sb.Append(Pac.GetCyrillicString(_previewBuffer, ref index));
                        }
                        else
                        {
                            sb.Append(encoding.GetString(_previewBuffer, index, 1));
                        }

                        index++;
                    }
                    if (CodePageIndex == Pac.CodePageArabic)
                    {
                        textBoxPreview.Text = Utilities.FixEnglishTextInRightToLeftLanguage(sb.ToString(), PreviewChars);
                    }
                    else
                    {
                        textBoxPreview.Text = sb.ToString();
                    }
                }
            }
        }
Example #15
0
        private void comboBoxCodePage_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxCodePage.SelectedIndex >= 0)
            {
                CodePageIndex = comboBoxCodePage.SelectedIndex;
                if (_previewBuffer != null)
                {
                    Encoding      encoding     = Pac.GetEncoding(CodePageIndex);
                    int           FEIndex      = 0;
                    int           endDelimiter = 0x00;
                    StringBuilder sb           = new StringBuilder();
                    int           index        = FEIndex + 3;
                    while (index < _previewBuffer.Length && _previewBuffer[index] != endDelimiter)
                    {
                        if (_previewBuffer[index] == 0xFE)
                        {
                            sb.AppendLine();
                            index += 2;
                        }
                        else if (_previewBuffer[index] == 0xFF)
                        {
                            sb.Append(" ");
                        }
                        else if (CodePageIndex == 0)
                        {
                            sb.Append(Pac.GetLatinString(encoding, _previewBuffer, ref index));
                        }
                        else if (CodePageIndex == 3)
                        {
                            sb.Append(Pac.GetArabicString(_previewBuffer, ref index));
                        }
                        else if (CodePageIndex == 4)
                        {
                            sb.Append(Pac.GetHebrewString(_previewBuffer, ref index));
                        }
                        else if (CodePageIndex == 6)
                        {
                            sb.Append(Pac.GetCyrillicString(_previewBuffer, ref index));
                        }
                        else
                        {
                            sb.Append(encoding.GetString(_previewBuffer, index, 1));
                        }

                        index++;
                    }
                    if (CodePageIndex == 3)
                    {
                        textBoxPreview.Text = Utilities.FixEnglishTextInRightToLeftLanguage(sb.ToString(), "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
                    }
                    else
                    {
                        textBoxPreview.Text = sb.ToString();
                    }
                }
            }
        }
Example #16
0
 protected override ReadOnlyMemory <byte> SignInternal(KerberosKey key)
 {
     return(decryptor.MakeChecksum(
                Pac.ToArray(),
                key.GetKey(decryptor),
                KeyUsage.PaForUserChecksum,
                KeyDerivationMode.Kc,
                decryptor.ChecksumSize
                ));
 }
Example #17
0
        protected override ReadOnlyMemory <byte> SignInternal(KerberosKey key)
        {
            var crypto = CryptoService.CreateTransform(EncryptionType.RC4_HMAC_NT);

            return(crypto.MakeChecksum(
                       key.GetKey(crypto),
                       Pac.ToArray(),
                       KeyUsage.PaForUserChecksum
                       ));
        }
Example #18
0
 public IActionResult Edit(Pac pac)
 {
     if (ModelState.IsValid)
     {
         _contenedorTrabajo.Pac.Update(pac);
         _contenedorTrabajo.Save();
         return(RedirectToAction(nameof(Index)));
     }
     return(View(pac));
 }
 public static bool EsFinDePartida(Fantasma[] fantasmas, Pac pac)
 {
     foreach (Fantasma f in fantasmas)
     {
         if (f.X == pac.X && f.Y == pac.Y)
         {
             return(true);
         }
     }
     return(false);
 }
Example #20
0
    public void Play()
    {
        // reset target pellet if pellet not target not exist anymore
        foreach (Pac pa in GetMyPacs().Where(p => p.Action.HasAction).ToList())
        {
            if (!Pellets.Any(pe => pe.Position == pa.Action.TargetPosition))
            {
                pa.Action = new Action();
            }
        }

        // IF there is big pellets, go get them
        List <Pellet> bigPellets = Pellets.Where(p => p.Value == 10).ToList();

        foreach (Pellet pe in bigPellets)
        {
            Pac pa = GetMyPacs().OrderBy(p => p.Distance(pe)).First();

            if (!pa.Action.HasAction || pe.Distance(pa) < pa.Distance(pa.Action.TargetPosition))
            {
                pa.Move(pe);
            }
        }
        // Else set the nearest not targeted pellet
        foreach (Pac p in GetMyPacs())
        {
            if (!p.Action.HasAction)
            {
                List <Pellet> AlreadyTargeted = GetMyPacs().Select(e => e.Action.TargetEntity).Where(e => e != null).Cast <Pellet>().ToList();

                p.Move(GetPelletsNearest(p).Except(AlreadyTargeted).FirstOrDefault());

                if (!p.Action.HasAction)
                {
                    p.Move(GetPelletsNearest(p).FirstOrDefault());
                }
            }
            // If can't see pellets go where we never go
            if (!p.Action.HasAction)
            {
                Cell target = Grid.Map.Cast <Cell>().Where(e => e.HasPellet).OrderBy(e => p.Distance(e.Position)).FirstOrDefault();

                if (target != null)
                {
                    p.Move(target.Position);
                }
            }
        }

        // If can speed, Override and speed
        GetMyPacs().FindAll(p => p.AbilityCooldown == 0).ForEach(p => p.Speed());

        this.ExecuteActions();
    }
Example #21
0
        public IActionResult Edit(int id)
        {
            Pac pac = new Pac();

            pac = _contenedorTrabajo.Pac.Get(id);
            if (pac == null)
            {
                return(NotFound());
            }

            return(View(pac));
        }
Example #22
0
    public void Sync()
    {
        string[] inputs = Console.ReadLine().Split(' ');

        this.StopWatch.Restart();

        this.MyScore       = int.Parse(inputs[0]);
        this.OpponentScore = int.Parse(inputs[1]);

        // Reset is alive to false foreach pac
        foreach (Pac p in GetMyPacs())
        {
            p.IsAlive = false;
        }
        /// LOOP PACS
        this.VisiblePacCount = int.Parse(Console.ReadLine());         // all your pacs and enemy pacs in sight

        for (int i = 0; i < this.VisiblePacCount; i++)
        {
            inputs = Console.ReadLine().Split(' ');
            int     pacId           = int.Parse(inputs[0]);                                    // pac number (unique within a team)
            bool    mine            = inputs[1] != "0";                                        // true if this pac is yours
            Vector2 position        = new Vector2(int.Parse(inputs[2]), int.Parse(inputs[3])); // position in the grid
            string  typeId          = inputs[4];                                               // unused in wood leagues
            int     speedTurnsLeft  = int.Parse(inputs[5]);                                    // unused in wood leagues
            int     abilityCooldown = int.Parse(inputs[6]);                                    // unused in wood leagues

            Pac pac = Pacs.Find(e => e.Id == pacId && e.Mine == mine);
            if (pac == null)
            {
                this.Pacs.Add(new Pac(pacId, mine, position, typeId, speedTurnsLeft, abilityCooldown));
            }
            else
            {
                pac.Update(position, typeId, speedTurnsLeft, abilityCooldown);
            }
        }

        // LOOP PELLETS
        this.VisiblePelletCount = int.Parse(Console.ReadLine());         // all pellets in sight
        this.Pellets            = new List <Pellet>(this.VisiblePelletCount);

        for (int i = 0; i < this.VisiblePelletCount; i++)
        {
            inputs = Console.ReadLine().Split(' ');

            Vector2 position = new Vector2(int.Parse(inputs[0]), int.Parse(inputs[1]));
            int     value    = int.Parse(inputs[2]);      // amount of points this pellet is worth
            this.Pellets.Add(new Pellet(position, value));
        }
        this.Grid.Update(this.Pacs, this.Pellets);
    }
Example #23
0
        private void RemoveInvalidChosenCells(Pac pac)
        {
            if (_chosenCells.ContainsKey(pac.Id))
            {
                var chosenCell = _chosenCells[pac.Id];

                if (!pac.IsAlive || pac.Position.IsSame(chosenCell.Position) || chosenCell.PelletValue == 0)
                {
                    Io.Debug($"removing Pac Id {pac.Id} : Chosen Cell {chosenCell.Position}");
                    _chosenCells.Remove(pac.Id);
                }
            }
        }
Example #24
0
    public void ReadTick()
    {
        ++Tick;
        MyPacs = 0;
        var inputs          = GameInput.ReadLine().Split(' ');
        var myScore         = int.Parse(inputs[0]);
        var opponentScore   = int.Parse(inputs[1]);
        var visiblePacCount = int.Parse(GameInput.ReadLine()); // all your pacs and enemy pacs in sight
        var toRemove        = new List <Pac>(Pacs);

        for (var i = 0; i < visiblePacCount; i++)
        {
            inputs = GameInput.ReadLine().Split(' ');
            var pacId  = int.Parse(inputs[0]); // pac number (unique within a team)
            var isMine = inputs[1] == "1";
            var trueId = (pacId << 1) | (isMine ? 1 : 0);

            var pac = Pacs.FirstOrDefault(p => p.Id == trueId);
            if (pac == null)
            {
                Pacs.Add(pac = new Pac(trueId));
            }

            pac.ReadTick(inputs);
            if (pac.Type != PacType.Dead)
            {
                toRemove.Remove(pac);
            }
            else
            {
                toRemove.Add(pac);
            }

            if (isMine)
            {
                ++MyPacs;
            }
        }

        foreach (var pac in toRemove)
        {
            Pacs.Remove(pac);
        }

        Field.ReadTick();

        foreach (var pac in Pacs)
        {
            pac.VisiblePellets = Field.SetPac(pac);
        }
    }
Example #25
0
        public void DoubleForwardTest()
        {
            Pac pac = new Pac();

            pac.Pos      = new Pos(16, 1);
            pac.LastMove = new Pos(14, 1);
            pac.LastMove = new Pos(15, 1);
            pac.LastMove = new Pos(16, 1);
            pac.LastMove = new Pos(16, 1);

            var df = pac.DoubleForward;

            Assert.Fail();
        }
Example #26
0
    public void UpdateState(Pac visiblePac)
    {
        CheckIfBlocked(visiblePac);

        this.x = visiblePac.x;
        this.y = visiblePac.y;

        this.typeId          = visiblePac.typeId;
        this.speedTurnsLeft  = visiblePac.speedTurnsLeft;
        this.abilityCooldown = visiblePac.abilityCooldown;

        this.activateSpeed = false;
        this.newType       = string.Empty;
    }
Example #27
0
        private MoveAction GetMoveActionInSamePosition(Pac pac, Cell cell)
        {
            if (pac.IsInSamePosition() && pac.SpeedTurnsLeft != 5)
            {
                Io.Debug($"Pac Id {pac.Id} : Same position {pac.Position}");
                var action = GetMoveIfInSamePosition(pac, cell);
                if (action != null)
                {
                    return(action);
                }
            }

            return(null);
        }
Example #28
0
        private MoveAction GetMoveActionInSamePosition(Pac pac, Cell cell)
        {
            if (pac.IsInSamePosition() && pac.AbilityCooldown != 9)
            {
                Io.Debug($"Pac Id {pac.Id} : Same position {pac.Position}");
                var action = GetMoveIfInSamePosition(pac, cell);
                if (action != null)
                {
                    return(action);
                }
            }

            return(null);
        }
Example #29
0
        private MoveAction GetMoveIfInSamePosition(Pac pac, Cell cell)
        {
            foreach (var(_, neighbour) in cell.Neighbours)
            {
                if (!ShouldAvoidCell(pac, neighbour))
                {
                    Io.Debug($"Pac Id {pac.Id} :  Same Position Move {neighbour.Position}");
                    _chosenCells[pac.Id] = neighbour;
                    _moveCells.Add(neighbour);
                    return(new MoveAction(neighbour.Position));
                }
            }

            return(null);
        }
Example #30
0
        public void PacItalic6()
        {
            var    target   = new Pac();
            var    subtitle = new Subtitle();
            string subText  = "V <i>Now</i>.";

            subtitle.Paragraphs.Add(new Paragraph(subText, 0, 999));
            var ms = new MemoryStream();

            target.Save("test.pac", ms, subtitle);
            var reload = new Subtitle();

            target.LoadSubtitle(reload, ms.ToArray());
            Assert.IsTrue(reload.Paragraphs[0].Text == "V <i>Now</i>.");
        }
        internal static bool BatchConvertSave(string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList<SubtitleFormat> formats, string fileName, Subtitle sub, SubtitleFormat format, bool overwrite, string pacCodePage, double? targetFrameRate)
        {
            double oldFrameRate = Configuration.Settings.General.CurrentFrameRate;
            try
            {
                // adjust offset
                AdjustOffset(offset, sub);

                // adjust frame rate
                if (targetFrameRate.HasValue)
                {
                    sub.ChangeFrameRate(Configuration.Settings.General.CurrentFrameRate, targetFrameRate.Value);
                    Configuration.Settings.General.CurrentFrameRate = targetFrameRate.Value;
                }

                bool targetFormatFound = false;
                string outputFileName;
                foreach (SubtitleFormat subtitleFormat in formats)
                {
                    if (subtitleFormat.IsTextBased && (
                        subtitleFormat.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) ||
                        subtitleFormat.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)))
                    {
                        targetFormatFound = true;
                        subtitleFormat.BatchMode = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, subtitleFormat.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);

                        if (subtitleFormat.IsFrameBased && !sub.WasLoadedWithFrameNumbers)
                        {
                            sub.CalculateFrameNumbersFromTimeCodesNoCheck(Configuration.Settings.General.CurrentFrameRate);
                        }
                        else if (subtitleFormat.IsTimeBased && sub.WasLoadedWithFrameNumbers)
                        {
                            sub.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
                        }

                        if ((subtitleFormat.GetType() == typeof(WebVTT) || subtitleFormat.GetType() == typeof(WebVTTFileWithLineNumber)))
                        {
                            targetEncoding = Encoding.UTF8;
                        }

                        if (subtitleFormat.GetType() == typeof(ItunesTimedText) || subtitleFormat.GetType() == typeof(ScenaristClosedCaptions) || subtitleFormat.GetType() == typeof(ScenaristClosedCaptionsDropFrame))
                        {
                            Encoding outputEnc = new UTF8Encoding(false);
                            using (var file = new StreamWriter(outputFileName, false, outputEnc))
                            {
                                file.Write(sub.ToText(subtitleFormat));
                            }
                        }
                        else if (targetEncoding == Encoding.UTF8 && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml)))
                        {
                            Encoding outputEnc = new UTF8Encoding(false);
                            using (var file = new StreamWriter(outputFileName, false, outputEnc))
                            {
                                file.Write(sub.ToText(subtitleFormat));
                            }
                        }
                        else
                        {
                            try
                            {
                                File.WriteAllText(outputFileName, sub.ToText(subtitleFormat), targetEncoding);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                                errors++;
                                return false;
                            }
                        }

                        if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern))
                        {
                            //var sami = (Sami)format;
                            foreach (string className in Sami.GetStylesFromHeader(sub.Header))
                            {
                                var newSub = new Subtitle();
                                foreach (Paragraph p in sub.Paragraphs)
                                {
                                    if (p.Extra != null && p.Extra.Trim().Equals(className.Trim(), StringComparison.OrdinalIgnoreCase))
                                    {
                                        newSub.Paragraphs.Add(p);
                                    }
                                }

                                if (newSub.Paragraphs.Count > 0 && newSub.Paragraphs.Count < sub.Paragraphs.Count)
                                {
                                    string s = fileName;
                                    if (s.LastIndexOf('.') > 0)
                                    {
                                        s = s.Insert(s.LastIndexOf('.'), "_" + className);
                                    }
                                    else
                                    {
                                        s += "_" + className + format.Extension;
                                    }

                                    outputFileName = FormatOutputFileNameForBatchConvert(s, subtitleFormat.Extension, outputFolder, overwrite);
                                    File.WriteAllText(outputFileName, newSub.ToText(subtitleFormat), targetEncoding);
                                }
                            }
                        }
                        Console.WriteLine(" done.");
                        break;
                    }
                }

                if (!targetFormatFound)
                {
                    var ebu = new Ebu();
                    if (ebu.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, ebu.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        Ebu.Save(outputFileName, sub, true);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    var pac = new Pac();
                    if (pac.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) ||
                        toFormat.Equals("pac", StringComparison.OrdinalIgnoreCase) ||
                        toFormat.Equals(".pac", StringComparison.OrdinalIgnoreCase))
                    {
                        pac.BatchMode = true;
                        int codePage;

                        if (!string.IsNullOrEmpty(pacCodePage) && int.TryParse(pacCodePage, out codePage))
                        {
                            pac.CodePage = codePage;
                        }

                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, pac.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        pac.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    var cavena890 = new Cavena890();
                    if (cavena890.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, cavena890.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        cavena890.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    var cheetahCaption = new CheetahCaption();
                    if (cheetahCaption.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, cheetahCaption.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        CheetahCaption.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    var capMakerPlus = new CapMakerPlus();
                    if (capMakerPlus.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, capMakerPlus.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        CapMakerPlus.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    if (Configuration.Settings.Language.BatchConvert.PlainText == toFormat ||
                        Configuration.Settings.Language.BatchConvert.PlainText.Replace(" ", string.Empty)
                        .Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, ".txt", outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        File.WriteAllText(outputFileName, ExportText.GeneratePlainText(sub, false, false, false, false, false, false, string.Empty, true, false, true, true, false), targetEncoding);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    Console.WriteLine("{0}: {1} - target format '{2}' not found!", count, fileName, toFormat);
                    errors++;
                    return false;
                }

                converted++;
                return true;
            }

            finally
            {
                Configuration.Settings.General.CurrentFrameRate = oldFrameRate;
            }
        }
        private static SubtitleFormat GetSubtitleFormat(SubtitleFormat format, string fileName, Subtitle sub, string pacCodePage)
        {
            if (format == null || format.GetType() == typeof(Ebu))
            {
                var ebu = new Ebu();
                if (ebu.IsMine(null, fileName))
                {
                    ebu.LoadSubtitle(sub, null, fileName);
                    format = ebu;
                }
            }
            if (format == null)
            {
                var pac = new Pac();
                if (pac.IsMine(null, fileName))
                {
                    pac.BatchMode = true;

                    if (!string.IsNullOrEmpty(pacCodePage) && Utilities.IsInteger(pacCodePage))
                    {
                        pac.CodePage = int.Parse(pacCodePage);
                    }
                    else
                    {
                        pac.CodePage = -1;
                    }

                    pac.LoadSubtitle(sub, null, fileName);
                    format = pac;
                }
            }
            if (format == null)
            {
                var cavena890 = new Cavena890();
                if (cavena890.IsMine(null, fileName))
                {
                    cavena890.LoadSubtitle(sub, null, fileName);
                    format = cavena890;
                }
            }
            if (format == null)
            {
                var spt = new Spt();
                if (spt.IsMine(null, fileName))
                {
                    spt.LoadSubtitle(sub, null, fileName);
                    format = spt;
                }
            }
            if (format == null)
            {
                var cheetahCaption = new CheetahCaption();
                if (cheetahCaption.IsMine(null, fileName))
                {
                    cheetahCaption.LoadSubtitle(sub, null, fileName);
                    format = cheetahCaption;
                }
            }
            if (format == null)
            {
                var chk = new Chk();
                if (chk.IsMine(null, fileName))
                {
                    chk.LoadSubtitle(sub, null, fileName);
                    format = chk;
                }
            }
            if (format == null)
            {
                var ayato = new Ayato();
                if (ayato.IsMine(null, fileName))
                {
                    ayato.LoadSubtitle(sub, null, fileName);
                    format = ayato;
                }
            }
            if (format == null)
            {
                var capMakerPlus = new CapMakerPlus();
                if (capMakerPlus.IsMine(null, fileName))
                {
                    capMakerPlus.LoadSubtitle(sub, null, fileName);
                    format = capMakerPlus;
                }
            }
            if (format == null)
            {
                var captionate = new Captionate();
                if (captionate.IsMine(null, fileName))
                {
                    captionate.LoadSubtitle(sub, null, fileName);
                    format = captionate;
                }
            }
            if (format == null)
            {
                var ultech130 = new Ultech130();
                if (ultech130.IsMine(null, fileName))
                {
                    ultech130.LoadSubtitle(sub, null, fileName);
                    format = ultech130;
                }
            }
            if (format == null)
            {
                var nciCaption = new NciCaption();
                if (nciCaption.IsMine(null, fileName))
                {
                    nciCaption.LoadSubtitle(sub, null, fileName);
                    format = nciCaption;
                }
            }
            if (format == null)
            {
                var tsb4 = new TSB4();
                if (tsb4.IsMine(null, fileName))
                {
                    tsb4.LoadSubtitle(sub, null, fileName);
                    format = tsb4;
                }
            }
            if (format == null)
            {
                var avidStl = new AvidStl();
                if (avidStl.IsMine(null, fileName))
                {
                    avidStl.LoadSubtitle(sub, null, fileName);
                    format = avidStl;
                }
            }
            if (format == null)
            {
                var elr = new ELRStudioClosedCaption();
                if (elr.IsMine(null, fileName))
                {
                    elr.LoadSubtitle(sub, null, fileName);
                    format = elr;
                }
            }
            return format;
        }