示例#1
0
 void LoadPassage(int passage, CameraPos pos)
 {
     if (active != null) active.Cleanup();
     active = passages[passage];
     active.Initialize(cam);
     LoadCamera(pos);
 }
示例#2
0
        public bool Update([FromBody] Object value)
        {
            string  json    = JsonConvert.SerializeObject(value);
            Passage passage = JsonConvert.DeserializeObject <Passage>(json);

            return(_context.Update(passage));
        }
示例#3
0
        private void ShowLinks(Passage passage)
        {
            // This used to be > 1 but we want to show them
            var shouldShowLinks = passage.links?.Count() > 1;

            if (!shouldShowLinks && passage.links?.Count() == 1)
            {
                var firstLink = passage.links[0];

                shouldShowLinks = firstLink.name.Contains("|");
            }

            if (shouldShowLinks)
            {
                foreach (var link in passage.links)
                {
                    var option = new SelectableOptionRuntime();
                    option.Text = link.StrippedName;
                    option.CurrentSelectedStateState = SelectableOptionRuntime.SelectedState.Deselected;
                    this.DialogOptions.AddChild(option);
                }
            }

            var firstOption = this.DialogOptions.Children.FirstOrDefault();

            if (firstOption != null)
            {
                firstOption.CurrentSelectedStateState =
                    SelectableOptionRuntime.SelectedState.Selected;
            }
        }
示例#4
0
    public void LeaveRoom(Passage passage)
    {
        if (passage.destRoom != entity.currentNode.room)
        {
            if (gm == null)
            {
                gm = GameMaster.instance;
            }
            Room curRoom = gm.rooms[entity.currentNode.room];
            curRoom.Entities.Remove(this.gameObject);
            entity.currentNode.Leave(); //leave passage
            Room destRoom = gm.rooms[passage.destRoom];
            destRoom.Entities.Add(this.gameObject);
            entity.currentNode = destRoom.NodeGrid[passage.destX, passage.destY];
            entity.currentNode.Occupy(entity);

            // encapsulate the whole hiding and drawing stuff?
            //this is bad but whatever
            if (entity.Visible)
            {
                entity.Erase();
            }
            if (destRoom.Key == gm.board.currentRoom.Key)
            {
                entity.Draw();
            }

            //abstract out the movement function?
            SharpMovement(entity.currentNode.center);
        }
    }
示例#5
0
        public ActionResult AdjPas(string name, Passage passage)//向数据库提交编辑文章
        {
            if (name != null)
            {
                ViewBag.name = name;
            }
            else
            {
                if (Session["Author"] != null)
                {
                    ViewBag.name = Session["Author"];
                    name         = (string)Session["Author"];
                }
            }
            var result = from p in Passagesdb.Passages
                         where p.ID == passage.ID
                         select p;

            foreach (var p in result)
            {
                p.Sort    = passage.Sort.Trim();
                p.Text    = passage.Text.Trim();
                p.Title   = passage.Title.Trim();
                p.OutDate = DateTime.Now.Date;
            }
            Passagesdb.SaveChanges();
            return(RedirectToAction("Contain"));
        }
示例#6
0
        public ActionResult CommitEdit(string name, Passage passage)//提交编辑文章
        {
            if (name != null)
            {
                ViewBag.name = name;
            }
            else
            {
                if (Session["Author"] != null)
                {
                    ViewBag.name = Session["Author"];
                    name         = (string)Session["Author"];
                }
            }
            Passage p = Passagesdb.Passages.Find(passage.ID);

            p.Sort    = passage.Sort.Trim();
            p.Text    = passage.Text.Trim();
            p.Author  = (string)Session["Author"];
            p.Title   = passage.Title.Trim();
            p.OutDate = DateTime.Now.Date;
            Passagesdb.Entry(p).State = EntityState.Modified;
            Passagesdb.SaveChanges();
            return(RedirectToAction("Contain"));
        }
示例#7
0
        public Boolean AddExit()
        {
            Console.WriteLine("PASSAGE ADDED TO ROOM " + roomID);
            Passage p = new Passage(true);

            if (north == null)
            {
                north = p;
                grid[grid.GetLength(0) / 2, grid.GetLength(1) - 1] = Tiles.PASSAGE;
                return(true);
            }
            else if (south == null)
            {
                south = p;
                grid[grid.GetLength(0) / 2, 0] = Tiles.PASSAGE;
                return(true);
            }
            else if (east == null)
            {
                east = p;
                grid[grid.GetLength(0) - 1, grid.GetLength(1) / 2] = Tiles.PASSAGE;
                return(true);
            }
            else if (west == null)
            {
                west = p;
                grid[0, grid.GetLength(1) / 2] = Tiles.PASSAGE;
                return(true);
            }

            return(false);
        }
        public Passage GetPassageByLocationAndCoords(int locationID, int x, int y)
        {
            object[] data    = context.GetPassageByLocationAndCoords(locationID, x, y);
            Passage  passage = new Passage(Convert.ToInt32(data[2]), Convert.ToInt32(data[5]), Convert.ToInt32(data[6]), Convert.ToInt32(data[7]), Convert.ToInt32(data[8]), GetCurrentLocation(Convert.ToInt32(data[4])));

            return(passage);
        }
        private static XmlElement GenerateSmarterAppMetadata(XmlDocument document, Passage passage)
        {
            var smarterAppMetadata = document.CreateElement("smarterAppMetadata");
            var identifier         = document.CreateElement("Identifier");

            identifier.InnerText = passage.Id;
            smarterAppMetadata.AppendChild(identifier);
            smarterAppMetadata.AppendChild(document.CreateElement("Subject"));
            smarterAppMetadata.AppendChild(document.CreateElement("Version"));
            smarterAppMetadata.AppendChild(document.CreateElement("InteractionType"));
            smarterAppMetadata.AppendChild(document.CreateElement("ItemAuthorIdentifier"));
            smarterAppMetadata.AppendChild(document.CreateElement("ItemSpecFormat"));
            smarterAppMetadata.AppendChild(document.CreateElement("LastModifiedBy"));
            smarterAppMetadata.AppendChild(document.CreateElement("SecurityStatus"));
            smarterAppMetadata.AppendChild(document.CreateElement("SmarterAppItemDescriptor"));
            smarterAppMetadata.AppendChild(document.CreateElement("Status"));
            smarterAppMetadata.AppendChild(document.CreateElement("StimulusFormat"));
            smarterAppMetadata.AppendChild(document.CreateElement("MaximumGrade"));
            smarterAppMetadata.AppendChild(document.CreateElement("MinimumGrade"));
            smarterAppMetadata.AppendChild(document.CreateElement("IntendedGrade"));
            smarterAppMetadata.AppendChild(document.CreateElement("StimulusLength"));
            smarterAppMetadata.AppendChild(document.CreateElement("StimulusGenre"));
            smarterAppMetadata.AppendChild(document.CreateElement("StimulusGraphic"));
            smarterAppMetadata.AppendChild(document.CreateElement("BrailleType"));
            smarterAppMetadata.AppendChild(document.CreateElement("Language"));
            return(smarterAppMetadata);
        }
示例#10
0
        //[System.Web.Http.HttpPost]
        /// <summary>
        /// Register a passage event
        /// </summary>
        /// <param name="payload"></param>
        /// <param name="hash"></param>
        /// <returns></returns>
        public IHttpActionResult Post(string payload, string hash)
        {
            // Validate hash
            // TODO use nonce
            const String SALT        = "%8vvpAwg48cvlcRwfAiY%A4gEj"; // not very secure
            var          hashCompare = Crypto.GetHashString(SALT + payload);
            var          response    = string.Format("payload: [{0}], hash: [{1}], hashCompare: [{2}]", payload, hash, hashCompare);

            if (hashCompare.Equals(hash, StringComparison.CurrentCultureIgnoreCase))
            {
                // Map parameters to properties
                var passage = new Passage();
                switch (payload.ToUpper())
                {
                case "IN":
                    passage.Direction = Passage.DirectionType.IN;
                    break;

                case "OUT":
                    passage.Direction = Passage.DirectionType.OUT;
                    break;

                default:
                    break;
                }
                passage.Message = DateTime.Now.ToString();
                CatFlapData.Save(passage);
            }
            else
            {
                return(Unauthorized());
            }
            return(Ok("OK"));
        }
    private void LoadPassage()
    {
        // Makes the cutscene visuals visible
        cutscene_cover.color = new Color(1, 1, 1, 1);
        Passage current_passage = null;

        // Retrieving the current passage of the current dialogue
        for (int i = 0; i < current_cutscene.dialogue.passages.Length; i++)
        {
            var passage = current_cutscene.dialogue.passages[i];

            if (i == current_passage_index)
            {
                current_passage = passage;
                current_passage_index++;
                break;
            }
        }

        if (current_passage == null)
        {
            return;
        }
        cutscene_cover.sprite = current_passage.cover;
        cutscene_text.text    = current_passage.text;
    }
示例#12
0
        // Called when local map passage is updated. If cell becomes non-passable, it may split area into two.
        public void update(int x, int y, int z)
        {
            Vector3Int center  = new Vector3Int(x, y, z);
            Passage    passing = passage.calculateTilePassage(center);

            passage.passage.set(center, passing.VALUE);
            if (passing == PASSABLE)   // tile became passable, areas should be merged
            {
                List <byte> areas = new NeighbourPositionStream(center)
                                    .filterConnectedToCenter()
                                    .filterNotInArea(0)
                                    .stream.Select(position => passage.area.get(position))
                                    .ToList();
                // take new area number, if new tile is not connected to any area
                byte areaNumber = areas.Count() == 0 ? getUnusedAreaNumber() : areas.First();
                passage.area.set(x, y, z, areaNumber); // set area value to current tile
                if (areas.Count() > 1)
                {
                    mergeAreas(areas);
                }
            }
            else     // tile became impassable, areas may split
            {
                splitAreas(center);
            }
        }
示例#13
0
文件: BOPassage.cs 项目: h4ltYu/EOS
        public bool SaveList(IList list)
        {
            ISession     session     = this.sessionFactory.OpenSession();
            ITransaction transaction = session.BeginTransaction();
            bool         result;

            try
            {
                foreach (object obj in list)
                {
                    Passage passage = (Passage)obj;
                    session.Save(passage);
                    foreach (object obj2 in passage.PassageQuestions)
                    {
                        Question question = (Question)obj2;
                        question.PID = passage.PID;
                        session.Save(question);
                        foreach (object obj3 in question.QuestionAnswers)
                        {
                            QuestionAnswer questionAnswer = (QuestionAnswer)obj3;
                            questionAnswer.QID = question.QID;
                            session.Save(questionAnswer);
                        }
                    }
                }
                transaction.Commit();
                result = true;
            }
            catch
            {
                transaction.Rollback();
                result = false;
            }
            return(result);
        }
示例#14
0
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //标题 内容 封面 作者 分类 不能为空
        if (title.Text.Trim().Length > 0 && editor.InnerHtml.Trim().Length > 0 && Request.Form["lb"].Trim().Length > 0 && author.SelectedValue.Length > 0 && category.SelectedValue.Length > 0)
        {
            using (var db = new huxiuEntities())
            {
                Passage passage = new Passage
                {
                    PassageTitle    = title.Text,
                    PassageBody     = UeditorHelper.change(editor.InnerHtml),
                    PassageImage    = "/File/" + Request.Form["lb"],
                    PassageCategory = Convert.ToInt32(category.SelectedValue),
                    PublishDate     = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    AuthorId        = Convert.ToInt32(author.SelectedValue),
                    PageViews       = 0,
                    IsDel           = false
                };
                db.Passage.Add(passage);

                if (db.SaveChanges() == 1)
                {
                    Response.Write("<script>alert('添加成功');location='PassageList.aspx'</script>");
                }
                else
                {
                    Response.Write("<script>alert('添加失败请重试')</script>");
                }
            }
        }
        else
        {
            Response.Write("<script>alert('不能为空!')</script>");
        }
    }
示例#15
0
    /// <summary>
    /// 记录原始数据项的删除标记
    /// </summary>
    /// <param name="yes_or_no"></param>
    /// <returns>返回bool类型</returns>
    private bool recordDelFlag(bool yes_or_no)
    {
        try
        {
            using (var db = new huxiuEntities())
            {
                switch (CategoryId)
                {
                case 1:    //查找资讯
                    Passage delPassage = db.Passage.SingleOrDefault(a => a.PassageId == DelId);
                    delPassage.IsDel = yes_or_no;
                    break;

                case 2:    //查找活动
                    Activity delActivty = db.Activity.SingleOrDefault(a => a.ActivityId == DelId);
                    delActivty.IsDel = yes_or_no;
                    break;

                case 3:    //查找短趣
                    News delnews = db.News.SingleOrDefault(a => a.NewsId == DelId);
                    delnews.IsDel = yes_or_no;
                    break;
                }
                db.SaveChanges();
            }
            return(true);
        }
        catch
        {
            return(false);
        }
    }
示例#16
0
        /**
         * Tile is passable, if its block type allows walking(like floor, ramp, etc.), plants are passable(not tree trunks), buildings are impassable.
         * TODO add water depth checking, etc.
         */
        public Passage calculateTilePassage(Vector3Int position)
        {
            Passage tilePassage = BlockTypeEnum.get(blockTypeMap.get(position)).PASSAGE;

            // TODO
            if (tilePassage == PASSABLE)   // tile still can be blocked by plants or buildings
            {
                bool plantPassable = true;
                //  GameModel.map(plantContainer => plantContainer.isPlantBlockPassable(position)).orElse(true);
                if (!plantPassable)
                {
                    return(IMPASSABLE);
                }

                bool buildingPassable = true;
                //        model.optional(BuildingContainer.class)
                //        .map(container -> container.buildingBlocks.get(position))
                //        .map(block -> block.passage == PASSABLE).orElse(true);
                if (!buildingPassable)
                {
                    return(IMPASSABLE);
                }

                bool waterPassable = true;
                //model.optional(LiquidContainer.class)
                //.map(container -> container.getTile(position))
                //.map(tile -> tile.amount <= 4).orElse(true);
                if (!waterPassable)
                {
                    return(IMPASSABLE);
                }
            }
            return(tilePassage);
        }
示例#17
0
    /// <summary>
    /// 本函数删除相应分类下面的某一条
    /// </summary>
    /// <param name="completeCate"> 相应分类</param>
    /// <param name="completeId"> 分类下面的id </param>
    /// <returns>返回 bool</returns>
    private bool delSourceData(int completeCate, int completeId)
    {
        try
        {
            using (var db = new huxiuEntities())
            {
                switch (completeCate)
                {
                case 1:    //查找资讯
                    Passage delPassage = db.Passage.SingleOrDefault(a => a.PassageId == completeId);
                    db.Passage.Remove(delPassage);
                    break;

                case 2:    //查找活动
                    Activity delActivty = db.Activity.SingleOrDefault(a => a.ActivityId == completeId);
                    db.Activity.Remove(delActivty);
                    break;

                case 3:    //查找短趣
                    News delnews = db.News.SingleOrDefault(a => a.NewsId == completeId);
                    db.News.Remove(delnews);
                    break;
                }
                db.SaveChanges();
            }
            return(true);
        }
        catch
        {
            return(false);
        }
    }
 public void LoadQuestions(String fileName)
 {
     Cursor.Current = Cursors.WaitCursor;
     try
     {
         using (System.IO.Stream stream = System.IO.File.Open(fileName, System.IO.FileMode.Open))
         {
             var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             m_questions = (List<Question>)bformatter.Deserialize(stream);
         }
         using (System.IO.Stream stream = System.IO.File.Open(fileName+"p", System.IO.FileMode.Open))
         {
             Passage p = new Passage();
             var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             m_passage = (Passage)bformatter.Deserialize(stream);
         }
     }
     catch (Exception e)
     {
         Cursor.Current = Cursors.Default;
         MessageBox.Show("failed to load the file \"" + fileName + "\"\n\r" + e.Message, "Question Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     m_currentPage = 0;
     m_totalPages = m_questions.Count / m_questionsPerPage;
     this.RefreshQuestions();
     Cursor.Current = Cursors.Default;
 }
 public void LoadQuestions(String fileName)
 {
     Cursor.Current = Cursors.WaitCursor;
     try
     {
         using (System.IO.Stream stream = System.IO.File.Open(fileName, System.IO.FileMode.Open))
         {
             var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             m_questions = (List <Question>)bformatter.Deserialize(stream);
         }
         using (System.IO.Stream stream = System.IO.File.Open(fileName + "p", System.IO.FileMode.Open))
         {
             Passage p          = new Passage();
             var     bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             m_passage = (Passage)bformatter.Deserialize(stream);
         }
     }
     catch (Exception e)
     {
         Cursor.Current = Cursors.Default;
         MessageBox.Show("failed to load the file \"" + fileName + "\"\n\r" + e.Message, "Question Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     m_currentPage = 0;
     m_totalPages  = m_questions.Count / m_questionsPerPage;
     this.RefreshQuestions();
     Cursor.Current = Cursors.Default;
 }
示例#20
0
    protected void btnEditor_Click(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(Request.QueryString["id"]);

        //标题 内容  不能为空
        if (title.Text.Trim().Length > 0 && editor.InnerHtml.Trim().Length > 0)
        {
            using (var db = new huxiuEntities())
            {
                Passage person = (from it in db.Passage where it.PassageId == id select it).FirstOrDefault();
                person.PassageTitle = title.Text;                             //标题
                person.PassageBody  = UeditorHelper.change(editor.InnerHtml); //内容
                if (Request.Form["lb"] != "")
                {
                    person.PassageImage = "~/File/" + Request.Form["lb"];
                }
                person.PassageCategory = Convert.ToInt32(category.SelectedValue);                        //资讯分类
                person.PublishDate     = Convert.ToDateTime(dates.Text).ToString("yyyy-MM-dd HH:mm:ss"); //时间
                person.AuthorId        = Convert.ToInt32(author.SelectedValue);                          //作者

                if (db.SaveChanges() == 1)
                {
                    Response.Write("<script>alert('编辑成功');location='PassageEditor.aspx?id=" + id + "'</script>");
                }
                else
                {
                    Response.Write("<script>alert('编辑失败请重试')</script>");
                }
            }
        }
        else
        {
            Response.Write("<script>alert('不能为空')</script>");
        }
    }
    public static DataPackage generateDataPackage(ref List <Article> arls, int currentPage)
    {
        DataPackage    dp   = new DataPackage();
        List <Passage> psLs = new List <Passage>();

        dp.totalCnt = arls.Count;
        arls        = arls.Skip(currentPage * WEBCONFIG.ARTICLE_EVERYPAGE_COUNT).Take(WEBCONFIG.ARTICLE_EVERYPAGE_COUNT).ToList();
        foreach (Article ar in arls)
        {
            Passage ps = new Passage();
            ps.title   = ar.Title;
            ps.author  = ar.Author;
            ps.summary = ar.Summary;
            ps.link    = ar.Link;
            string keyword = string.Empty;//;连接
            foreach (KeyValuePair <int, string> kp in ArticleHelper.getKeyowrd(ar.id))
            {
                keyword += ";" + kp.Value;
            }
            ps.keyword = keyword.Substring(1);
            psLs.Add(ps);
        }

        dp.nowPage = currentPage;
        dp.info    = psLs;
        return(dp);
    }
示例#22
0
        /// <summary>
        /// *new 导入文件
        /// </summary>
        /// <returns></returns>
        public async Task <Passage> OpenFile()
        {
            Passage passage = new Passage();
            var     picker  = new FileOpenPicker();

            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
            picker.FileTypeFilter.Add(".txt");

            // TODO:
            //picker.FileTypeFilter.Add(".pdf");

            StorageFile storageFile = await picker.PickSingleFileAsync();

            if (storageFile != null)
            {
                var stream = await storageFile.OpenStreamForReadAsync();

                passage.Content = await FileIO.ReadTextAsync(storageFile);

                passage.HeadName = storageFile.Name.Replace(".txt", "");//获取文章标题,去除扩展名

                return(passage);
            }
            else
            {
                return(null);
            }
        }
示例#23
0
        public Passage ConnectRegions(Region firstRegion, Region secondRegion, int distance)
        {
            if (firstRegion == null || secondRegion == null)
            {
                return(null);
            }
            var passage = new Passage()
            {
                FirstRegionID  = firstRegion.ID,
                SecondRegionID = secondRegion.ID,
                Distance       = distance
            };

            //this will be not be called frequently. We will add some new checks for this.

            if (DoesPassageExist(firstRegion, secondRegion))
            {
                return(null); //this is acceptable.
            }
            regionRepository.AddPassage(passage);
            regionRepository.SaveChanges();

            Console.WriteLine($"Regions {firstRegion.Name} and {secondRegion.Name} connected!");

            return(passage);
        }
示例#24
0
        public List <Passage> LoadPassage()
        {
            List <Passage> myPassages = new List <Passage>();
            var            command    = new SqliteCommand();

            command.Connection  = db;
            command.CommandText = "SELECT title FROM articles";

            var reader = command.ExecuteReader();

            while (reader.Read())
            {
                Passage passage = new Passage();
                passage.HeadName = reader.GetString(0);
                myPassages.Add(passage);
            }

            // >>> TANG HAO ADD
            command.CommandText = "SELECT content FROM articles";
            var reader2 = command.ExecuteReader();
            int length  = 0;

            while (reader2.Read() && length < myPassages.Count)
            {
                myPassages[length].Content = reader2.GetString(0);
                length++;
            }
            reader2.Close();
            // <<< TANG HAO ADD

            reader.Close();

            return(myPassages);
        }
示例#25
0
 public PassageListItem(Passage passage)
 {
     Line            = passage.Line;
     Direction       = passage.Direction;
     TramDescription = passage.Vehicle != null ? $"{passage.Vehicle.SideNo} ({passage.Vehicle.ModelName})" : string.Empty;
     MixedTime       = passage.MixedTime;
 }
        public void CreateReadPassageNoLocation()
        {
            var passage = new Passage(Passage.PassageTypeEnum.StairsDown, "PASSAGE");

            Assert.AreEqual(Passage.PassageTypeEnum.StairsDown, passage.PassageType);
            Assert.AreEqual("PASSAGE", passage.DestinationID);
            Assert.AreEqual(null, passage.Location);
        }
示例#27
0
    Passage CreatePassage(Room roomA, Room roomB, Coord tileA, Coord tileB)
    {
        Passage passage = CreatePassage(tileA, tileB);

        Room.ConnectRooms(roomA, roomB, passage);

        return(passage);
    }
示例#28
0
    // this creates a passage on the edge of two cells
    private void createPassage(Cell cell, Cell otherCell, Direction direction)
    {
        Passage passage = Instantiate(passagePrefab) as Passage;      // creates an instance of the passage prefab

        passage.initialise(cell, otherCell, direction);               // initialise the passage
        passage = Instantiate(passagePrefab) as Passage;              // creates another instance of the passage prefab
        passage.initialise(otherCell, cell, direction.getOpposite()); // creates an instance of the passage on the edge in the opposite direction
    }
示例#29
0
        private void CreatePassage(Cell cell, Cell neighbourCell, Direction dir)
        {
            Passage passage = Instantiate(mazePassagePrefab) as Passage;

            passage.Initialise(cell, neighbourCell, dir);
            passage = Instantiate(mazePassagePrefab) as Passage;
            passage.Initialise(neighbourCell, cell, dir.GetOpposite());
        }
示例#30
0
    private void CreatePassage(Cell cell, Cell otherCell, Direction direction)
    {
        Passage passage = Instantiate(passagePrefab) as Passage;

        passage.Initialize(cell, otherCell, direction);
        passage = Instantiate(passagePrefab) as Passage;
        passage.Initialize(otherCell, cell, direction.GetOpposite());
    }
        public static PubTatorResponse ParseString(string json)
        {
            JObject jsonAnnotation = JObject.Parse(json);
            var     response       = new PubTatorResponse();

            response.Id     = jsonAnnotation.GetValue("id").ToObject <String>();
            response.Infons = jsonAnnotation.GetValue("infons").ToObject <Dictionary <string, string> >();
            var passagesArray = JArray.Parse(jsonAnnotation["passages"].ToString());

            foreach (var passage in passagesArray)
            {
                var passageObject = new Passage();
                passageObject.Infons = passage["infons"].ToObject <Dictionary <String, String> >();
                passageObject.Offset = passage["offset"].ToObject <int>();
                passageObject.Text   = passage["text"].ToObject <String>();
                var annotationsListString = passage["annotations"].ToString();
                var annotationsListArray  = JArray.Parse(annotationsListString);
                passageObject.Annotations = new List <Annotation>();
                foreach (var token in annotationsListArray)
                {
                    passageObject.Annotations.Add(Annotation.ParseString(token.ToString()));
                }
                response.Passages.Add(passageObject);
            }

            var date = jsonAnnotation.GetValue("created");

            response.Created = DateTimeOffset.FromUnixTimeMilliseconds(jsonAnnotation.GetValue("created")["$date"].ToObject <long>()).DateTime;
            var tagsArray = JArray.Parse(jsonAnnotation["accessions"].ToString());

            foreach (var token in tagsArray)
            {
                var accessionString = token.ToString();
                var parts           = accessionString.Split("@");
                var works           = Enum.TryParse(parts[0], true, out Tag myTag);
                if (!works)
                {
                    Console.WriteLine("Enum Parse Failed for" + parts[0]);
                }
                response.Tags.Add(new Accessor
                {
                    tag = myTag, data = parts[1]
                });
            }
            var authorsArray = jsonAnnotation.GetValue("authors").ToObject <List <String> >();

            response.Authors = authorsArray;
            response.Journal = jsonAnnotation.GetValue("journal").ToObject <String>();
            try
            {
                response.Year = jsonAnnotation.GetValue("year").ToObject <Int32>();
            }
            catch (ArgumentException)
            {
                response.Year = 0;
            }
            return(response);
        }
示例#32
0
 public void AddPassage(Passage passage)
 {
     if (_passageContentMacroStack.Count != 0)
     {
         Logger.LogWarning("A macro isn´t closed before passage " + passage.Name + " begins");
     }
     _passageContentMacroStack.Clear();
     _lastPassageContent = null;
     _currentPassage = passage;
     _currentFormat = new PassageContentFormat();
     _tree.AddPassage(passage);
 }
示例#33
0
 public void AddPassage(Passage passage)
 {
     if (!_passages.ContainsKey(passage.Name))
     {
         switch (passage.Name)
         {
             case "Start":
                 _start = passage;
                 break;
             case "StoryTitle":
                 _storyTitle = passage;
                 break;
             case "StoryAuthor":
                 _storyAuthor = passage;
                 break;
         }
         _passages.Add(passage.Name, passage);
     }
     else
     {
         Logger.LogWarning("ignoring passage with same name: " + passage.Name);
     }
 }
示例#34
0
        static void Main(string[] args)
        {
            List<Passage> allPassages = new List<Passage>();
            // Заполнение "сети" начальными данными
            using (StreamReader file = new StreamReader(string.Format(@"{0}\..\..\input\Web.txt", Environment.CurrentDirectory)))
            {
                string s;
                while ((s = file.ReadLine()) != null)
                {
                    string[] arr = s.Trim().Split(' ');
                    if (arr.Length != 3)
                    {
                        Console.WriteLine("Ошибка формата входных данных файла Web.txt");
                        Console.ReadLine();
                        return;
                    }
                    int s1, s2, d;
                    if (Int32.TryParse(arr[0], out s1) && Int32.TryParse(arr[1], out s2) && Int32.TryParse(arr[2], out d))
                    {
                        Passage p = new Passage(s1, s2, d);
                        if (!allPassages.Contains(p)) allPassages.Add(p);
                    }
                    else
                    {
                        Console.WriteLine("Ошибка формата входных данных файла Web.txt");
                        Console.ReadLine();
                        return;
                    }
                }
            }

            List<string> locos = new List<string>();
            //Заполнение массива маршрутов поездов, где каждый маршрут набор станций, и массива времен прибывания на них
            using (StreamReader file = new StreamReader(string.Format(@"{0}\..\..\input\Locos.txt", Environment.CurrentDirectory)))
            {
                string s;
                while ((s = file.ReadLine()) != null)
                {
                    locos.Add(s.Trim());
                }
            }
            int[][] stations = new int[locos.Count][];
            int[][] time = new int[locos.Count][];
            int counter = 0;
            foreach (string s in locos)
            {
                string[] tmp = s.Split(' ');
                stations[counter] = new int[tmp.Length];
                time[counter] = new int[tmp.Length];
                for (int i = 0; i < tmp.Length; i++)
                {
                    if (!Int32.TryParse(tmp[i], out stations[counter][i]))
                    {
                        Console.WriteLine("Ошибка формата входных данных Locos.txt");
                        Console.ReadLine();
                        return;
                    }
                    if (i == 0) time[counter][i] = 0;
                    else
                    {
                        time[counter][i] = time[counter][i - 1] + allPassages.Find(item => (item.station1 == stations[counter][i - 1]) && (item.station2 == stations[counter][i]) ||
                            (item.station2 == stations[counter][i - 1]) && (item.station1 == stations[counter][i])).distance;
                    }
                }
                counter++;
            }

            // Выводим расписание движения паровозов
            Console.WriteLine("Ниже представлено расписание движения поездов по станциям. Первая цифра номер станции, цифра в скобках время прибытия. ");
            for (int i = 0; i < locos.Count; i++)
            {
                Console.Write("Паровоз " + (i + 1) + ":  ");
                for (int j = 0; j < stations[i].Length - 1; j++)
                {
                    Console.Write(stations[i][j] + "(" + time[i][j] + ") - ");
                }
                Console.WriteLine(stations[i][stations[i].Length - 1] + "(" + time[i][stations[i].Length - 1] + ")");
            }
            Console.WriteLine();

            // Проверяем все станции на предмет столкновения
            for (int i = 0; i < locos.Count - 1; i++)
            {
                for (int j = 0; j < stations[i].Length; j++)
                {
                    for (int k = i + 1; k < locos.Count; k++)
                    {
                        for (int l = 0; l < stations[k].Length; l++)
                        {
                            if ((stations[i][j] == stations[k][l]) && (time[i][j] == time[k][l]))
                                Console.WriteLine("Паровозы " + (i + 1) + " и " + (k + 1) + " cталкиваются на станции " + stations[i][j]);
                        }
                    }
                }
            }

            // Проверяем все переезды на предмет столкновения
            for (int i = 0; i < locos.Count - 1; i++)
            {
                for (int j = 0; j < stations[i].Length - 1; j++)
                {
                    for (int k = i + 1; k < locos.Count; k++)
                    {
                        for (int l = 0; l < stations[k].Length - 1; l++)
                        {
                            if ((stations[i][j] == stations[k][l + 1]) && (stations[i][j + 1] == stations[k][l]) &&
                                ((time[i][j] >= time[k][l]) && (time[i][j] <= time[k][l + 1]) || (time[i][j + 1] >= time[k][l]) && (time[i][j + 1] <= time[k][l + 1])))
                                Console.WriteLine("Паровозы " + (i + 1) + " и " + (k + 1) + " cталкиваются на переезде между станциями " + stations[i][j] + " и " + stations[i][j + 1]);
                        }
                    }
                }
            }

            Console.ReadLine();
        }
示例#35
0
 private bool validateStoryAuthor()
 {
     if (_tree.StoryAuthor == null)
     {
         Logger.LogWarning("No story author passage found");
         Passage storyTitle = new Passage("StoryAuthor");
         storyTitle.AddPassageContent(new PassageText("Unknown author"));
         _tree.AddPassage(storyTitle);
     }
     return true;
 }
示例#36
0
 void LoadPassage(int passage)
 {
     if(active != null) active.Cleanup();
     active = passages[passage];
     active.Initialize(cam);
 }
示例#37
0
 public Route(Waypoint start, Passage passage)
 {
     Start = start;
     Passage = passage;
 }
示例#38
0
        private ZRoutine ConvertPassageToRoutine(Passage passage, string storyTitle, string storyAuthor)
        {
            List<ZInstruction> instructions = new List<ZInstruction>();
            int currentLink = 0;
            var links = new List<Tuple<string, Assign>>();

            instructions.Add(new EraseWindow(0));
            instructions.Add(new Add(_symbolTable.GetSymbol("%turns%"), 1, _symbolTable.GetSymbol("%turns%")));
            ZGlobalVariable visited = _symbolTable.GetSymbol("%visited:" + _routineTable.GetRoutine(passage.Name) + "%");
            instructions.Add(new Add(visited, 1, visited));

            if (!String.IsNullOrWhiteSpace(storyTitle))
            {
                instructions.Add(new SetTextStyle(SetTextStyle.StyleFlags.ReverseVideo | SetTextStyle.StyleFlags.Bold));

                instructions.Add(new Print(storyTitle));
                instructions.Add(new SetTextStyle(SetTextStyle.StyleFlags.None));

                if (!String.IsNullOrWhiteSpace(storyAuthor))
                {
                    instructions.Add(new SetTextStyle(SetTextStyle.StyleFlags.ReverseVideo));
                    instructions.Add(new Print(" (" + storyAuthor + ")"));
                    instructions.Add(new SetTextStyle(SetTextStyle.StyleFlags.None));
                }

                instructions.Add(new NewLine());
            }

            instructions.AddRange(ConvertPassageContent(passage.PassageContentList, ref currentLink, links, passage.Name));

            if (currentLink > 0)
            {
                instructions.Add(new NewLine());
                instructions.Add(new PrintUnicode('>') { Label = new ZLabel("read" + passage.Name) });
                instructions.Add(new ReadChar(new ZLocalVariable(0)));

                List<Guid> callGuids = new List<Guid>();

                for (int i = 0; i < links.Count(); i++)
                {
                    callGuids.Add(Guid.NewGuid());

                    char charToWrite;
                    if (i >= 0 && i < 10)
                        charToWrite = Convert.ToChar('1' + i);
                    else if (i >= 10 && i < 36)
                        charToWrite = Convert.ToChar('a' + i - 10);
                    else if (i >= 36 && i < 62)
                        charToWrite = Convert.ToChar('A' + i - 36);
                    else
                        throw new Exception();

                    instructions.Add(new Je(new ZLocalVariable(0), (short)charToWrite, new ZBranchLabel(links[i].Item1 + "Call_" + callGuids[i])));
                }

                instructions.Add(new NewLine());
                instructions.Add(new Print("Unbekannte Eingabe!"));
                instructions.Add(new NewLine());
                instructions.Add(new Jump(new ZJumpLabel("read" + passage.Name)));

                for (int i = 0; i < links.Count(); i++)
                {
                    instructions.Add(new Nop() { Label = new ZLabel(links[i].Item1 + "Call_" + callGuids[i]) });

                    if (links[i].Item2 != null)
                    {
                        instructions.AddRange(ConvertAssignExpression(links[i].Item2, passage.Name));
                    }

                    if (links[i].Item1 == "previous()")
                    {
                        instructions.Add(new Store(_symbolTable.GetSymbol("%nextprevious%"), _routineTable.GetRoutine(passage.Name)));
                        instructions.Add(new Call1n(new ZRoutineLabel("routineCallTable")));
                    }
                    else
                    {
                        instructions.Add(new Store(_symbolTable.GetSymbol("%previous%"), _routineTable.GetRoutine(passage.Name)));
                        instructions.Add(new Call1n(new ZRoutineLabel(links[i].Item1)));
                    }
                }
            }
            else
            {
                instructions.Add(new Print(" "));
                instructions.Add(new Quit());
            }

            return new ZRoutine(instructions, 1) { Label = new ZRoutineLabel(passage.Name) };
        }