Пример #1
0
 private void LoadStats(Adventure currLocalAdventure)
 {
     try
     {
         txtProtagonist.Text = currLocalAdventure.CharacterName ?? "Unnamed";
         txtTitle.Text = currLocalAdventure.CharacterTitle ?? "the Titleless";
         if (currLocalAdventure.ArmorSet != null)
             txtArmorSet.Text = currLocalAdventure.ArmorSet.ArmorName ?? "Naked";
         else
             txtArmorSet.Text = "Naked";
         if (currLocalAdventure.MeleeWeapon != null)
             txtMeleeWeapon.Text = currLocalAdventure.MeleeWeapon.WeaponName ?? "Unarmed";
         else
             txtMeleeWeapon.Text = "Unarmed";
         if (currLocalAdventure.RangedWeapon != null)
             txtRangedWeapon.Text = currLocalAdventure.RangedWeapon.WeaponName ?? "Unarmed";
         else
             txtRangedWeapon.Text = "Unarmed";
         txtHealthStat.Text = currLocalAdventure.Health.ToString() ?? "100";
         txtArmorStat.Text = currLocalAdventure.Armor.ToString() ?? "100";
         txtSpeedStat.Text = currLocalAdventure.Speed.ToString() ?? "100";
         txtMagicStat.Text = currLocalAdventure.Magic.ToString() ?? "0";
         txtLuckStat.Text = currLocalAdventure.Luck.ToString() ?? "0";
         txtDecisionsMade.Text = currLocalAdventure.DecisionsMade.ToString();
         txtStoryLength.Text = currLocalAdventure.StoryLength.ToString();
     }
     catch (Exception err)
     {
         exHand.LogException(err, "Story-LoadStats");
     }
 }
Пример #2
0
 private void LoadStoryInfo(Adventure currAdventure)
 {
     currLocalAdventure = currAdventure;
     LoadFlowDocsForStory(currLocalAdventure);
     LoadCurrentFlowDocChapter(currLocalAdventure, currLocalAdventure.CurrentChapter);
     //LoadSceneImage(currLocalAdventure, currLocalAdventure.CurrentChapter);
     //LoadSceneMusic(currLocalAdventure, currentMusic);
     LoadStats(currLocalAdventure);
 }
Пример #3
0
 public void Init()
 {
     //初始化冒險
     Adventure adventure = new Adventure(1);
     MC = transform.FindChild("MilestoneController").GetComponent<MilestoneController>();
     MC.Init(adventure.Data, adventure.GetEventTypes(), adventure.GetEventMiles(), adventure.GetUnknownEvent());
     //設定里程
     Miles = transform.FindChild("Miles").FindChild("miles").GetComponent<Text>();
 }
        private void PopulateAdventure(Adventure currCreation)
        {
            newCreation = currCreation;

            txtAdventureTitle.Text = newCreation.Title;
            txtArmorSet.Text = newCreation.ArmorSet.ArmorName;
            txtArmorStat.Text = newCreation.Armor.ToString();
            txtAuthor.Text = newCreation.Author;
            txtHealthStat.Text = newCreation.Health.ToString();
            txtLuckStat.Text = newCreation.Luck.ToString();
            txtMagicStat.Text = newCreation.Magic.ToString();
            txtMeleeWeapon.Text = newCreation.MeleeWeapon.WeaponName;
            txtProtagonist.Text = newCreation.CharacterName;
            txtRangedWeapon.Text = newCreation.RangedWeapon.WeaponName;
            txtSpeedStat.Text = newCreation.Speed.ToString();
            txtSummary.Text = newCreation.Summary;
            txtTitle.Text = newCreation.CharacterTitle;
            cmbGenre.SelectedValue = newCreation.Genre;
            cmbTheme.SelectedValue = newCreation.Theme;
        }
 private void PopulateAdventure(Adventure currCreation)
 {
     newCreation = currCreation;
     GetSceneFiles();
     GetMusicFiles();
 }
 public StoryGeneratorStageTwo(Adventure currCreation)
 {
     InitializeComponent();
     Loaded += StoryGenerator_Loaded;
     PopulateAdventure(currCreation);
 }
Пример #7
0
        //vytvori village, resources, buildings, products, units pre village
        //pre kazdy typ budovy budovu, pre kazdy typ res res atd

        public void CreateVillage(int playerID)
        {
            var village = new Village();

            using (var uow = UnitOfWorkProvider.Create())
            {
                var player = playerRepository.GetById(playerID, p => p.Villages, p => p.Account);
                player.NumOfVillages++;

                village.Player           = player;
                village.Huts             = 1;
                village.AvailableWorkers = 4;
                if (player.Villages.Count() == 0)
                {
                    village.Number = 1;
                }
                else
                {
                    village.Number = player.Villages.Last().Number + 1;
                }
                villageRepository.Insert(village);
                playerRepository.Update(player);
                uow.Commit();
            }

            using (var uow = UnitOfWorkProvider.Create())
            {
                var v = villageRepository.GetById(village.ID);

                var        resourceTypesCount = resourceTypeListQuery.GetTotalRowCount();
                Resource[] resources          = new Resource[resourceTypesCount];

                //takto, alebo i = 0  inicializovat, i++ inicializovat a for od 2 //opakovanie kodu, ci efektivita?
                for (int i = 0; i < resourceTypesCount; ++i)
                {
                    resources[i] = new Resource();
                    resources[i].ResourceType = resourceTypeRepository.GetById(i + 1);

                    if (i == 0)
                    {
                        resources[i].Amount = 90;
                    }

                    if (i == 1)
                    {
                        resources[i].Amount = 50;
                    }

                    resources[i].Village = v;
                    resourceRepository.Insert(resources[i]);
                }

                var        buildingTypesCount = buildingTypeListQuery.GetTotalRowCount();
                var        buildingTypes      = buildingTypeRepository.GetByIds(Enumerable.Range(1, buildingTypesCount).ToArray()); // 2. Sposob na priradovanie type
                Building[] buildings          = new Building[buildingTypesCount];

                for (int i = 0; i < buildingTypesCount; ++i)
                {
                    buildings[i] = new Building();
                    buildings[i].BuildingType = buildingTypes[i];   //2. sposob
                    buildings[i].Village      = v;
                    buildingRepository.Insert(buildings[i]);
                }


                var       productTypesCount = productTypeListQuery.GetTotalRowCount();
                Product[] products          = new Product[productTypesCount];

                for (int i = 0; i < productTypesCount; ++i)
                {
                    products[i]             = new Product();
                    products[i].ProductType = productTypeRepository.GetById(i + 1);
                    products[i].Village     = v;
                    productRepository.Insert(products[i]);
                }


                var unitTypesCount = unitTypeListQuery.Execute().Where(u => u.Role.Equals(UnitRole.Friendly)).Count();    //friendly/hostile units

                Unit[] units = new Unit[unitTypesCount];
                for (int i = 0; i < unitTypesCount; ++i)
                {
                    units[i]          = new Unit();
                    units[i].UnitType = unitTypeRepository.GetById(i + 1);
                    units[i].Village  = v;
                    unitRepository.Insert(units[i]);
                }

                var         adventureTypesCount = adventureTypeListQuery.GetTotalRowCount();
                var         adventureTypes      = adventureTypeRepository.GetByIds(Enumerable.Range(1, adventureTypesCount).ToArray()); // 2. Sposob na priradovanie type
                Adventure[] adventures          = new Adventure[adventureTypesCount];

                for (int i = 0; i < adventureTypesCount; ++i)
                {
                    adventures[i] = new Adventure();
                    adventures[i].AdventureType = adventureTypes[i];   //2. sposob
                    adventures[i].Village       = v;
                    adventureRepository.Insert(adventures[i]);
                }

                uow.Commit();
            }
        }
Пример #8
0
        private async Task <AlexaResponse> GetIntentResponseAsync(AlexaRequest request)
        {
            string intentName = request?.Request?.Intent?.Name;

            if (string.IsNullOrWhiteSpace(intentName))
            {
                throw new Exception("No intent name found");
            }



            Adventure adv = await _adventureRep.GetAdventureAsync();

            AdventureNode curNode = await _curNodeRep.GetCurrentNodeAsync(request, adv.Nodes);

            string        nextNodeName = null;
            AlexaResponse resp         = null;

            if (intentName.Equals("BeginIntent", StringComparison.OrdinalIgnoreCase) || intentName.Equals(BuiltInIntents.StartOverIntent))
            {
                AdventureNode startNode = adv.GetStartNode();

                if (startNode == null)
                {
                    throw new Exception($"Start node {adv.StartNodeName} not found");
                }

                nextNodeName = startNode.Name;
                resp         = startNode.ToAlexaResponse(_linkProcessor, adv.VoiceId);
            }
            else if (intentName.Equals(BuiltInIntents.CancelIntent) || intentName.Equals(BuiltInIntents.StopIntent))
            {
                AdventureNode stopNode = adv.GetStopNode();

                if (stopNode == null)
                {
                    throw new Exception($"Start node {adv.StopNodeName} not found");
                }

                resp = stopNode.ToAlexaResponse(_linkProcessor, adv.VoiceId);
            }
            else if (intentName.Equals("ResumeIntent", StringComparison.OrdinalIgnoreCase))
            {
                resp = curNode.ToAlexaResponse(_linkProcessor, adv.VoiceId);
            }
            else if (intentName.Equals(BuiltInIntents.HelpIntent))
            {
                AdventureNode helpNode = adv.GetHelpNode();

                if (helpNode == null)
                {
                    throw new Exception($"Help node {helpNode.Name} not found");
                }

                resp = MergeNodeResponses(helpNode, curNode, adv.VoiceId);
            }
            else if (intentName.Equals(BuiltInIntents.FallbackIntent))
            {
                resp = GenerateFallbackResponse(adv, curNode);
            }
            else
            {
                if (curNode != null)
                {
                    // Process the route

                    NodeRoute selectedRoute = curNode.NodeRoutes.FirstOrDefault(x => x.IntentName.Equals(intentName, StringComparison.OrdinalIgnoreCase));

                    if (selectedRoute != null)
                    {
                        nextNodeName = selectedRoute.NextNodeName;

                        if (!string.IsNullOrWhiteSpace(nextNodeName))
                        {
                            AdventureNode nextNode = adv.GetNode(nextNodeName);

                            if (nextNode != null)
                            {
                                resp = nextNode.ToAlexaResponse(_linkProcessor, adv.VoiceId);
                            }
                            else
                            {
                                _logger.LogWarning($"Next node {nextNodeName} on node {curNode} not found for intent {intentName}");
                            }
                        }
                        else
                        {
                            _logger.LogWarning($"Node name missing for node route for {intentName} provided on node {curNode.Name}");
                        }
                    }
                    else
                    {
                        resp = GenerateFallbackResponse(adv, curNode);
                        // unsupported intent. Send reprompt.
                        _logger.LogWarning($"Node route not found for {intentName} provided on node {curNode.Name}");
                    }
                }
                else
                {
                    resp = GenerateFallbackResponse(adv, null);
                    // unsupported intent. Send reprompt.
                    _logger.LogWarning($"Node {curNode.Name} on session attribute {AdventureNode.CURNODE_ATTRIB} not found");
                }
            }

            // If the next node is known, then set it. Otherwise, keep the user on the current node.
            if (string.IsNullOrWhiteSpace(nextNodeName))
            {
                if (curNode != null)
                {
                    await _curNodeRep.SetCurrentNodeAsync(request, resp, curNode.Name);
                }
            }
            else
            {
                await _curNodeRep.SetCurrentNodeAsync(request, resp, nextNodeName);
            }

            return(resp);
        }
Пример #9
0
        public Adventure Generate(int numberOfCompanions, int personID, Random rand)
        {
            Adventure   adventure   = new Adventure();
            ElfLogic    elfLogic    = new ElfLogic();
            DwarfLogic  dwarfLogic  = new DwarfLogic();
            HobbitLogic hobbitLogic = new HobbitLogic();
            HumanLogic  humanLogic  = new HumanLogic();
            WizardLogic wizardLogic = new WizardLogic();

            List <string> CompanionNames = new List <string>();

            //randomly assign leader
            adventure.LeaderName = wizardLogic.GenerateName(rand.Next(2) == 1 ? "female" : "male", rand);

            LocationLogic          locationLogic = new LocationLogic();
            IEnumerable <Location> locations     = locationLogic.GetAllLocations();
            int index = rand.Next(0, locations.Count());

            //set WhereTo
            adventure.WhereToLocationID = locations.ElementAt(index).LocationID;

            for (int i = 0; i < numberOfCompanions; i++)
            {
                int    randomNum = rand.Next(1, 5);
                string gender    = rand.Next(2) == 1 ? "female" : "male";
                string name;
                if (randomNum == 1)
                {
                    name = hobbitLogic.GenerateName(gender, rand);

                    while (CompanionNames.Contains(name))
                    {
                        name = hobbitLogic.GenerateName(gender, rand);
                    }
                    CompanionNames.Add(name);
                }
                else if (randomNum == 2)
                {
                    name = elfLogic.GenerateName(gender, rand);

                    CompanionNames.Add(name);
                }
                else if (randomNum == 3)
                {
                    name = dwarfLogic.GenerateName(gender, rand);

                    CompanionNames.Add(name);
                }
                else if (randomNum == 4)
                {
                    name = humanLogic.GenerateName(gender, rand);

                    CompanionNames.Add(name);
                }
            }

            //set Successful
            adventure.Successful = rand.Next(2) == 1;

            //set fatal - fatal cannot be true if successful is true because a successful adventure cannot be fatal, but a unsuccessful mission could be fatal, but doesn't have to be
            adventure.Fatal = adventure.Successful ? false : rand.Next(2) == 1;
            if (adventure.Fatal)
            {
                bool leaderDead  = rand.Next(2) == 1;
                char deathDagger = (char)8224;
                adventure.LeaderName = leaderDead ? adventure.LeaderName + deathDagger : adventure.LeaderName;
                int        numDeadCompanions = leaderDead ? rand.Next(CompanionNames.Count()) : rand.Next(0, CompanionNames.Count());
                List <int> usedIndexes       = new List <int>();
                for (int i = 0; i < numDeadCompanions; i++)
                {
                    do
                    {
                        index = rand.Next(CompanionNames.Count());
                    } while (usedIndexes.Contains(index));
                    usedIndexes.Add(index);
                    CompanionNames[index] = CompanionNames[index] + deathDagger;
                }
            }
            adventure.CompanionNames = string.Join(",", CompanionNames);
            adventure.MainPersonID   = personID;
            AddAdventure(adventure);
            return(adventure);
        }
Пример #10
0
        private void UpdateOngoing(Adventure currLocalAdventure, FlowDocument doc)
        {
            try
            {
                List<Block> docBlocks = doc.Blocks.ToList();
                foreach (Block indivBlock in docBlocks)
                {
                    TextRange range = new TextRange(indivBlock.ContentStart, indivBlock.ContentEnd);
                    Paragraph gg = new Paragraph();
                    gg.Inlines.Add(range.Text);
                    if (currLocalAdventure.ongoingStory.Blocks.Count == 0)
                        currLocalAdventure.ongoingStory.Blocks.Add(indivBlock);
                    else
                        currLocalAdventure.ongoingStory.Blocks.InsertAfter(currLocalAdventure.ongoingStory.Blocks.Last(), gg);
                    //currLocalAdventure.ongoingStory.Blocks.Add(indivBlock);

                    currLocalAdventure.StoryLength = currLocalAdventure.StoryLength + CountWords(range.Text);
                }
            }
            catch (Exception err)
            {
                exHand.LogException(err, "Story-UpdateOngoing");
            }
        }
Пример #11
0
        private void LoadCurrentFlowDocChapter(Adventure currLocalAdventure, int currChapter)
        {
            try
            {
                string newChapterStoryPath = string.Empty;
                string newChapterStoryMetaPath = string.Empty;
                currentMusic = null;
                foreach (var file in adventureStoryFiles)
                {
                    string filename = Regex.Replace(file.Name, "[^.0-9]", "");
                    char[] trim = { '.' };
                    if (filename.TrimEnd(trim) == currChapter.ToString())
                    {
                        newChapterStoryPath = file.Name;
                        break;
                    }
                }
                foreach (var file in adventureStoryMetaFiles)
                {
                    string filename = Regex.Replace(file.Name, "[^.0-9]", "");
                    char[] trim = { '.' };
                    if (filename.TrimEnd(trim) == currChapter.ToString())
                    {
                        newChapterStoryMetaPath = file.Name;
                        break;
                    }
                }

                //READ XAML FOR STORY
                using (FileStream fs = File.OpenRead(@currLocalAdventure.folderPath + "/" + newChapterStoryPath))
                {
                    FlowDocument document = (FlowDocument)XamlReader.Load(fs);
                    fdrDocumentReader.Document = document;
                }

                using (FileStream fs = File.OpenRead(@currLocalAdventure.folderPath + "/" + newChapterStoryPath))
                {
                    FlowDocument document = (FlowDocument)XamlReader.Load(fs);
                    UpdateOngoing(currLocalAdventure, document);
                }

                //READ META FOR CHOICE
                try
                {
                    using (FileStream fs = File.OpenRead(@currLocalAdventure.folderPath + "/" + newChapterStoryMetaPath))
                    {
                        FlowDocument document = (FlowDocument)XamlReader.Load(fs);

                        //RPG STATS WORK
                        int armor = 0;
                        int health = 0;
                        int luck = 0;
                        int magic = 0;
                        int speed = 0;

                        //BREAK OUT INTO TAGS TO ASSIGN
                        List<Block> docBlocks = document.Blocks.ToList();
                        foreach (Block indivBlock in docBlocks)
                        {
                            char[] trimmer = { '%', '}' };
                            TextRange range = new TextRange(indivBlock.ContentStart, indivBlock.ContentEnd);
                            string[] metaTexts = range.Text.Split('[');
                            foreach (string indivString in metaTexts)
                            {
                                if (indivString.Contains("%MUSIC%"))
                                {
                                    currentMusic = indivString.Split(']').Last();
                                    LoadSceneMusic(currentMusic);
                                    noTunes = false;
                                }
                                if (indivString.Contains("%SCENE%"))
                                {
                                    var currentScene = "";
                                    currentScene = indivString.Split(']').Last();
                                    LoadSceneImage(currentScene);
                                }
                                if (indivString.Contains("%CHOICE%"))
                                {
                                    txtDirections.Text = indivString.Split(']').Last();
                                }
                                if (indivString.Contains("%ANSWERONE%"))
                                {
                                    var text = indivString.Split(']').Last();
                                    txtChoiceOne.Text = text;

                                    if (textOne.Inlines.Count > 0)
                                        textOne.Inlines.Clear();
                                    textOne.Inlines.Add(text);
                                }
                                if (indivString.Contains("%ANSWERTWO%"))
                                {
                                    var text = indivString.Split(']').Last();
                                    txtChoiceTwo.Text = text;

                                    if (textTwo.Inlines.Count > 0)
                                        textTwo.Inlines.Clear();
                                    textTwo.Inlines.Add(text);
                                }
                                if (indivString.Contains("%ANSWERTHREE%"))
                                {
                                    var text = indivString.Split(']').Last();
                                    txtChoiceThree.Text = text;

                                    if (textThree.Inlines.Count > 0)
                                        textThree.Inlines.Clear();
                                    textThree.Inlines.Add(text);
                                }
                                if (indivString.Contains("%OUTCOMEONE%"))
                                {
                                    outcomeOne = indivString.Split(']').Last();
                                }
                                if (indivString.Contains("%OUTCOMETWO%"))
                                {
                                    outcomeTwo = indivString.Split(']').Last();
                                }
                                if (indivString.Contains("%OUTCOMETHREE%"))
                                {
                                    outcomeThree = indivString.Split(']').Last();
                                }

                                if (indivString.Contains("%CHARMOR%"))
                                {
                                    //IF RPGENABLED, STATS BECOME COOL
                                    if (currLocalAdventure.RPGEnabled)
                                    {
                                        var g = indivString.Split(']').Last();
                                        if (g == "")
                                            g = "0";
                                        armor = Convert.ToInt32(g);
                                    }
                                        currLocalAdventure.Armor = currLocalAdventure.Armor + Convert.ToInt32(indivString.Split(']').Last());
                                        txtArmorStat.Text = currLocalAdventure.Armor.ToString();
                                }
                                if (indivString.Contains("%CHHEALTH%"))
                                {
                                    //IF RPGENABLED, STATS BECOME COOL
                                    if (currLocalAdventure.RPGEnabled)
                                    {
                                        var g = indivString.Split(']').Last();
                                        if (g == "")
                                            g = "0";
                                        health = Convert.ToInt32(g);
                                    }
                                    currLocalAdventure.Health = currLocalAdventure.Health + Convert.ToInt32(indivString.Split(']').Last());
                                    txtHealthStat.Text = currLocalAdventure.Health.ToString();
                                    if (currLocalAdventure.Health < 0)
                                    {
                                        gameOver = true;
                                    }
                                }
                                if (indivString.Contains("%CHLUCK%"))
                                {
                                    //IF RPGENABLED, STATS BECOME COOL
                                    if (currLocalAdventure.RPGEnabled)
                                    {
                                        var g = indivString.Split(']').Last();
                                        if (g == "")
                                            g = "0";
                                        luck = Convert.ToInt32(g);
                                    }
                                        currLocalAdventure.Luck = currLocalAdventure.Luck + Convert.ToInt32(indivString.Split(']').Last());
                                        txtLuckStat.Text = currLocalAdventure.Luck.ToString();
                                }
                                if (indivString.Contains("%CHMAGIC%"))
                                {
                                    //IF RPGENABLED, STATS BECOME COOL
                                    if (currLocalAdventure.RPGEnabled)
                                    {
                                        var g = indivString.Split(']').Last();
                                        if (g == "")
                                            g = "0";
                                        magic = Convert.ToInt32(g);
                                    }
                                        currLocalAdventure.Magic = currLocalAdventure.Magic + Convert.ToInt32(indivString.Split(']').Last());
                                        txtMagicStat.Text = currLocalAdventure.Magic.ToString();
                                }
                                if (indivString.Contains("%CHSPEED%"))
                                {
                                    //IF RPGENABLED, STATS BECOME COOL
                                    if (currLocalAdventure.RPGEnabled)
                                    {
                                        var g = indivString.Split(']').Last();
                                        if (g == "")
                                            g = "0";
                                        speed = Convert.ToInt32(g);
                                    }
                                        currLocalAdventure.Speed = currLocalAdventure.Speed + Convert.ToInt32(indivString.Split(']').Last());
                                        txtSpeedStat.Text = currLocalAdventure.Speed.ToString();
                                }

                                if (indivString.Contains("%CHARMORSET%"))
                                {
                                    currLocalAdventure.ArmorSet.ArmorName = indivString.Split(']').Last();
                                    txtArmorSet.Text = currLocalAdventure.ArmorSet.ArmorName;
                                }
                                if (indivString.Contains("%CHMELEEWEAPON%"))
                                {
                                    currLocalAdventure.MeleeWeapon.WeaponName = indivString.Split(']').Last();
                                    txtMeleeWeapon.Text = currLocalAdventure.MeleeWeapon.WeaponName;
                                }
                                if (indivString.Contains("%CHRANGEDWEAPON%"))
                                {
                                    currLocalAdventure.RangedWeapon.WeaponName = indivString.Split(']').Last();
                                    txtRangedWeapon.Text = currLocalAdventure.RangedWeapon.WeaponName;
                                }
                            }
                        }
                        if (currLocalAdventure.RPGEnabled)
                            CalculateStatsPost(armor,  health,  luck,  magic,  speed);
                    }

                    if (gameOver)
                    {
                        txtDirections.Text = "Your adventure has ended.";
                        txtChoiceOne.Text = "";
                        txtChoiceTwo.Text = "";
                        txtChoiceThree.Text = "";
                        brdChoiceOne.IsEnabled = false;
                        brdChoiceTwo.IsEnabled = false;
                        brdChoiceThree.IsEnabled = false;
                        ProcessChoice("finished", 0);
                        AppGlobals.player.StopMusic();
                    }
                }
                catch
                {
                    txtDirections.Text = "Your adventure has ended.";
                    txtChoiceOne.Text = "";
                    txtChoiceTwo.Text = "";
                    txtChoiceThree.Text = "";
                    brdChoiceOne.IsEnabled = false;
                    brdChoiceTwo.IsEnabled = false;
                    brdChoiceThree.IsEnabled = false;
                    ProcessChoice("finished", 0);
                    AppGlobals.player.StopMusic();
                }

                if (txtChoiceOne.Text == "")
                    brdChoiceOne.IsEnabled = false;
                else
                    brdChoiceOne.IsEnabled = true;
                if (txtChoiceTwo.Text == "")
                    brdChoiceTwo.IsEnabled = false;
                else
                    brdChoiceTwo.IsEnabled = true;
                if (txtChoiceThree.Text == "")
                    brdChoiceThree.IsEnabled = false;
                else
                    brdChoiceThree.IsEnabled = true;
            }
            catch (Exception err)
            {
                exHand.LogException(err, "Story-LoadCurrentFlowDocChapter");
            }
        }
Пример #12
0
        private async Task <AdventureState> RestoreAdventureState(Adventure adventure, Session session)
        {
            var            recordId = UserIdToSessionRecordKey(session.User.UserId);
            AdventureState state    = null;

            if (session.New)
            {
                // check if the adventure state can be restored from the player table
                if (_adventurePlayerTable != null)
                {
                    // check if a session can be restored from the database
                    var record = await _dynamoClient.GetItemAsync(_adventurePlayerTable, new Dictionary <string, AttributeValue> {
                        ["PlayerId"] = new AttributeValue {
                            S = recordId
                        }
                    });

                    if (record.IsItemSet)
                    {
                        state = JsonConvert.DeserializeObject <AdventureState>(record.Item["State"].S);
                        LogInfo($"restored state from player table\n{record.Item["State"].S}");

                        // check if the place the player was in still exists or if the player had reached an end state
                        if (!adventure.Places.TryGetValue(state.CurrentPlaceId, out AdventurePlace place))
                        {
                            LogWarn($"unable to find matching place for restored state from player table (value: '{state.CurrentPlaceId}')");

                            // reset player
                            state.Reset(Adventure.StartPlaceId);
                        }
                        else if (place.Finished)
                        {
                            LogInfo("restored player had reached end place");

                            // reset player
                            state.Reset(Adventure.StartPlaceId);
                        }
                        else if (state.CurrentPlaceId == Adventure.StartPlaceId)
                        {
                            // reset player
                            state.Reset(Adventure.StartPlaceId);
                        }
                    }
                    else
                    {
                        LogInfo("no previous state found in player table");
                    }
                }
            }
            else
            {
                // attempt to deserialize the player information
                if (!session.Attributes.TryGetValue(SESSION_STATE_KEY, out object playerStateValue) || !(playerStateValue is JObject playerState))
                {
                    LogWarn($"unable to find player state in session (type: {playerStateValue?.GetType().Name})\n" + JsonConvert.SerializeObject(session));
                }
                else
                {
                    state = playerState.ToObject <AdventureState>();

                    // validate the adventure still has a matching place for the player
                    if (!adventure.Places.ContainsKey(state.CurrentPlaceId))
                    {
                        LogWarn($"unable to find matching place for restored player in session (value: '{state.CurrentPlaceId}')\n" + JsonConvert.SerializeObject(session));

                        // reset player
                        state.Reset(Adventure.StartPlaceId);
                    }
                }
            }

            // create new player if no player was restored
            if (state == null)
            {
                LogInfo("new player session started");
                state = new AdventureState(recordId, Adventure.StartPlaceId);
            }
            return(state);

            // local functions
            string UserIdToSessionRecordKey(string userId)
            {
                var md5 = System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(userId));

                return($"resume-{new Guid(md5):N}");
            }
        }
Пример #13
0
        public async static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new ApplicationDbContext(serviceProvider.GetRequiredService <DbContextOptions <ApplicationDbContext> >()))
            {
                var roleStore = new RoleStore <IdentityRole>(context);
                var userstore = new UserStore <User>(context);

                if (!context.Roles.Any(r => r.Name == "Administrator"))
                {
                    var role = new IdentityRole {
                        Name = "Administrator", NormalizedName = "Administrator"
                    };
                    await roleStore.CreateAsync(role);
                }

                if (!context.User.Any(u => u.Email == "*****@*****.**"))
                {
                    //  This method will be called after migrating to the latest version.
                    User user = new User
                    {
                        UserName           = "******",
                        NormalizedUserName = "******",
                        Email           = "*****@*****.**",
                        NormalizedEmail = "*****@*****.**",
                        EmailConfirmed  = true,
                        LockoutEnabled  = false,
                        SecurityStamp   = Guid.NewGuid().ToString("D")
                    };
                    var passwordHash = new PasswordHasher <User>();
                    user.PasswordHash = passwordHash.HashPassword(user, "Admin8*");
                    await userstore.CreateAsync(user);

                    await userstore.AddToRoleAsync(user, "Administrator");
                }

                // Look for any unitClasses.
                if (context.UnitClass.Any())
                {
                    return;   // DB has been seeded
                }

                var unitClass = new UnitClass[]
                {
                    new UnitClass {
                        Name = "Basic",

                        AbilityOneName        = "Punch",
                        AbilityOneDescription = "Lash out with your fists and smack the shit out of the enemy!",
                        AbilityOneDamage      = 15,

                        AbilityTwoName        = "Slap of Death",
                        AbilityTwoDescription = "Slap the life right out of the enemy!",
                        AbilityTwoDamage      = 50,
                        HpModifier            = 1
                    },
                };

                foreach (UnitClass u in unitClass)
                {
                    context.UnitClass.Add(u);
                }
                context.SaveChanges();

                var characters = new Character[]
                {
                    new Character {
                        Name        = "Mordran",
                        UnitClassId = unitClass.Single(u => u.Name == "Basic").Id,
                        HP          = 100,
                        User        = context.User.Single(user => user.Email == "*****@*****.**")
                    },
                };

                foreach (Character c in characters)
                {
                    context.Character.Add(c);
                }
                context.SaveChanges();


                var enemy = new Enemy[]
                {
                    new Enemy {
                        Name        = "Zombie",
                        UnitClassId = unitClass.Single(u => u.Name == "Basic").Id,
                        HP          = 100,
                        Boss        = false
                    },
                    new Enemy {
                        Name        = "Lich",
                        UnitClassId = unitClass.Single(u => u.Name == "Basic").Id,
                        HP          = 75,
                        Boss        = false
                    },
                    new Enemy {
                        Name        = "Balrog",
                        UnitClassId = unitClass.Single(u => u.Name == "Basic").Id,
                        HP          = 200,
                        Boss        = true
                    }
                };

                foreach (Enemy e in enemy)
                {
                    context.Enemy.Add(e);
                }
                context.SaveChanges();

                var adventure = new Adventure[]
                {
                    new Adventure {
                        Title = "The Epic One"
                    },
                };

                foreach (Adventure a in adventure)
                {
                    context.Adventure.Add(a);
                }
                context.SaveChanges();

                var roadBlock1 = new RoadBlock();
                roadBlock1.AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id;
                roadBlock1.StartingPoint    = true;
                roadBlock1.Description      = "You are a loyal member of the Kings Army.  One evening, while on patrol, a woman rushes up to you and says 'It took my necklace!!  That THING took the necklace that's been in my family for generations!' You look past her to see a large creature skulking into the woods nearby.";
                roadBlock1.PreviousOptionId = null;

                context.RoadBlock.Add(roadBlock1);
                context.SaveChanges();

                var options1 = new PathOption[]
                {
                    new PathOption
                    {
                        Description   = "Rush into the woods after the creature!",
                        LeadsToCombat = false
                    },
                    new PathOption
                    {
                        Description   = "Keep on walking, this isn't any of your concern.",
                        LeadsToCombat = true
                    }
                };

                foreach (PathOption p in options1)
                {
                    context.PathOption.Add(p);

                    StoryPath path = new StoryPath();

                    path.RoadBlockId  = roadBlock1.Id;
                    path.PathOptionId = p.Id;

                    context.StoryPath.Add(path);
                }
                context.SaveChanges();

                var roadBlock2_1 = new RoadBlock();
                roadBlock2_1.AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id;
                roadBlock2_1.Description      = "As you enter the woods the world goes black.  The forrest is so dark you cannot see.  You hear nothing but the wind rushing through the branches.";
                roadBlock2_1.PreviousOptionId = options1.Single(p => p.Description == "Rush into the woods after the creature!").Id;
                roadBlock2_1.StartingPoint    = false;

                context.RoadBlock.Add(roadBlock2_1);
                context.SaveChanges();

                var options2_1 = new PathOption[]
                {
                    new PathOption
                    {
                        Description   = "Feel around in the darkness for something to make a torch.",
                        LeadsToCombat = false
                    },

                    new PathOption
                    {
                        Description   = "Rush ahead blindly, the creature is getting away!",
                        LeadsToCombat = true
                    }
                };

                foreach (PathOption p in options2_1)
                {
                    context.PathOption.Add(p);

                    StoryPath path = new StoryPath();

                    path.RoadBlockId  = roadBlock2_1.Id;
                    path.PathOptionId = p.Id;

                    context.StoryPath.Add(path);
                }
                context.SaveChanges();

                RoadBlock Woods_1 = new RoadBlock();
                Woods_1.AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id;
                Woods_1.Description      = "You feel desparately on the ground for anything that will burn.  You find a dry branch, tear the sleae of your tunic off and wrap the top of the branch with it.  You use flint to spark the cloth alight.  You press on into the forrest.  You come to a clearing blanketed in low hanging fog.  The air feels cold, and across the clearing you see the necklace lying on the stump of a tree.  You rush forward but stop short as a figure glides around from the forrest edge towards the necklace.  The figure is floating half a foot off the ground and is cloaked in a black decrepit looking robe embroidered with glittering runes.  Its skin is pale and you can see spots where the flesh is decaying.  You recognize the creature as a Lich, an undead sorceror.  The Lich doesn't appear to have noticed your presence.  It turns towards the necklace and green magic shoots from its fingers!  The necklace rises from the stump.  The lich is transfering its essence into the neckalce to create a phylactory!  If it succeeds it will become immortal and torment the nearby village!";
                Woods_1.PreviousOptionId = options2_1.Single(o => o.Description == "Feel around in the darkness for something to make a torch.").Id;
                Woods_1.StartingPoint    = false;

                context.RoadBlock.Add(Woods_1);
                context.SaveChanges();

                RoadBlock Woods_2 = new RoadBlock();
                Woods_2.AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id;
                Woods_2.Description      = "You run with your arms splayed in front of you feeling for any trees that might be in your way.  Brush snags at your trousers.  You feel wiry twigs claw at your face.  Suddenly the ground beneath your feet disapears.  You fall off the edge of a cliff and plummett to your death.";
                Woods_2.GameOver         = true;
                Woods_2.PreviousOptionId = options2_1.Single(o => o.Description == "Rush ahead blindly, the creature is getting away!").Id;
                Woods_2.StartingPoint    = false;

                context.RoadBlock.Add(Woods_2);
                context.SaveChanges();

                var optionsWood_1 = new PathOption[]
                {
                    new PathOption()
                    {
                        Description   = "Draw your weapon and prepare for battle!  This creature cannot be allowed to terrorize your people!",
                        LeadsToCombat = true
                    },
                    new PathOption()
                    {
                        Description   = "The creature fills you with terror and you turn and run back towards the woods to try and escape!",
                        LeadsToCombat = false
                    }
                };

                foreach (PathOption o in optionsWood_1)
                {
                    context.PathOption.Add(o);

                    StoryPath path = new StoryPath();
                    path.PathOptionId = o.Id;
                    path.RoadBlockId  = Woods_1.Id;

                    context.StoryPath.Add(path);
                }

                context.SaveChanges();

                RoadBlock Woods_1_2 = new RoadBlock();
                Woods_1_2.AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id;
                Woods_1_2.Description      = "The Lich hears you rushing away!  The air around you glows green and you feel your body leave the ground.  You are pulled back with such force that the air is knocked out of your lungs!  The Lich is in front of you now, its eyes glowing a sinister blue.  It raises a hand and lighting crackles from its fingertips.  Your body is wracked with pain and you all to the ground in a heap!";
                Woods_1_2.PreviousOptionId = optionsWood_1.Single(o => o.Description == "The creature fills you with terror and you turn and run back towards the woods to try and escape!").Id;
                Woods_1_2.StartingPoint    = false;

                context.RoadBlock.Add(Woods_1_2);
                context.SaveChanges();

                PathOption Woods_1_2options = new PathOption();
                Woods_1_2options.Description   = "There is no escaping!  Stand and draw your weapon.  Even though you are injured the time has come to end this!";
                Woods_1_2options.LeadsToCombat = true;

                context.PathOption.Add(Woods_1_2options);

                StoryPath WoodsPathFinal = new StoryPath();
                WoodsPathFinal.PathOptionId = Woods_1_2options.Id;
                WoodsPathFinal.RoadBlockId  = Woods_1_2.Id;

                context.StoryPath.Add(WoodsPathFinal);
                context.SaveChanges();

                RoadBlock WoodsFinale1 = new RoadBlock()
                {
                    Description      = "With one final blow, the Lich lets out an agonizing screech and dissipates into a clowd of smoke.  You are vicotrious!  The Lich was unusccessful in creating its phylactery.  You grab the necklace from the ground and venture back towards the village.  You find the woman waiting by the roadside.  You hand her the necklace and she thanks you!  You turn towards the nearest tavern, you deserve a drink!",
                    StartingPoint    = false,
                    AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id,
                    PreviousOptionId = Woods_1_2options.Id,
                };

                context.RoadBlock.Add(WoodsFinale1);
                context.SaveChanges();

                RoadBlock WoodsFinale2 = new RoadBlock()
                {
                    Description      = "With one final blow, the Lich lets out an agonizing screech and dissipates into a clowd of smoke.  You are vicotrious!  The Lich was unusccessful in creating its phylactery.  You grab the necklace from the ground and venture back towards the village.  You find the woman waiting by the roadside.  You hand her the necklace and she thanks you!  You turn towards the nearest tavern, you deserve a drink!",
                    StartingPoint    = false,
                    AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id,
                    PreviousOptionId = optionsWood_1.Single(o => o.Description == "Draw your weapon and prepare for battle!  This creature cannot be allowed to terrorize your people!").Id
                };

                context.RoadBlock.Add(WoodsFinale2);
                context.SaveChanges();



                RoadBlock roadBlock2_2 = new RoadBlock();
                roadBlock2_2.AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id;
                roadBlock2_2.Description      = "As you turn to leave the woman becomes angry.  You turn away to head back towards the barracks.  You hear the sound of bones breaking, and cloth ripping.  The moon goes dark and the world rings out with a bellowing roar!";
                roadBlock2_2.PreviousOptionId = options1.Single(o => o.Description == "Keep on walking, this isn't any of your concern.").Id;
                roadBlock2_2.StartingPoint    = false;

                context.RoadBlock.Add(roadBlock2_2);
                context.SaveChanges();

                var options2_2 = new PathOption[]
                {
                    new PathOption()
                    {
                        Description   = "Stop and look back.",
                        LeadsToCombat = false
                    },

                    new PathOption()
                    {
                        Description   = "RUN FAST!",
                        LeadsToCombat = false
                    }
                };

                foreach (PathOption p in options2_2)
                {
                    context.PathOption.Add(p);

                    StoryPath path = new StoryPath();
                    path.RoadBlockId  = roadBlock2_2.Id;
                    path.PathOptionId = p.Id;

                    context.StoryPath.Add(path);
                }
                context.SaveChanges();

                RoadBlock roadBlock3_1 = new RoadBlock();
                roadBlock3_1.AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id;
                roadBlock3_1.Description      = "As you turn you see an enormous dragon where the woman once stood.  The dragon is black with glowing red eyes.  Its immense wings unfold from its back.  Smoke and fiery sparks lick from its great jaws.  Clearly the woman was hiding her true nature from you.  The dragon bares takes a step towards you and belows a challanging roar!";
                roadBlock3_1.PreviousOptionId = options2_2.Single(p => p.Description == "Stop and look back.").Id;
                roadBlock3_1.StartingPoint    = false;

                context.RoadBlock.Add(roadBlock3_1);
                context.SaveChanges();

                RoadBlock roadBlock3_2 = new RoadBlock();
                roadBlock3_2.AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id;
                roadBlock3_2.Description      = "You run faster than you've ever run before.  From behind you comes a ground shaking roar and you feel the ground shaking beneath you.  You steal a glance behind you and see an enormous dragon barelling towards you!  Clearly the woman wasn't telling you the entire truth.  The woman, now in the form of a immense black dragon, unfurls her immense wings.  The gust of wind from her wings causes you to plummet to the ground.  You roll over on your back to see the behemoth tower above you!  It raises it's head with smoke and fiery sparks escaping its jaws and roars!";
                roadBlock3_2.StartingPoint    = false;
                roadBlock3_2.PreviousOptionId = options2_2.Single(p => p.Description == "RUN FAST!").Id;

                context.RoadBlock.Add(roadBlock3_2);
                context.SaveChanges();

                PathOption option3_1 = new PathOption();
                option3_1.Description   = "Draw your weapon and prepare for battle!";
                option3_1.LeadsToCombat = true;

                context.PathOption.Add(option3_1);
                context.SaveChanges();

                StoryPath path3_1 = new StoryPath();
                path3_1.PathOptionId = option3_1.Id;
                path3_1.RoadBlockId  = roadBlock3_1.Id;

                context.StoryPath.Add(path3_1);
                context.SaveChanges();

                PathOption option3_2 = new PathOption();
                option3_2.Description   = "You roll out of reach of the beasts immense claws.  Get to your feet and draw your weapon.  This Isn't going to be easy.";
                option3_2.LeadsToCombat = true;

                context.PathOption.Add(option3_2);
                context.SaveChanges();

                StoryPath path3_2 = new StoryPath();
                path3_2.PathOptionId = option3_2.Id;
                path3_2.RoadBlockId  = roadBlock3_2.Id;

                RoadBlock roadBlock4_Final = new RoadBlock();
                roadBlock4_Final.AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id;
                roadBlock4_Final.Description      = "The dragon let's out one final gutteral roar as it drops lifelessly to the ground.  You dust yourself off, sheath your sword and head to the nearest tavern.  You deserve a drink!";
                roadBlock4_Final.PreviousOptionId = option3_1.Id;
                roadBlock4_Final.StartingPoint    = false;

                context.RoadBlock.Add(roadBlock4_Final);
                context.SaveChanges();

                RoadBlock roadBlock4_2Final = new RoadBlock();
                roadBlock4_2Final.AdventureId      = adventure.Single(a => a.Title == "The Epic One").Id;
                roadBlock4_2Final.Description      = "The dragon let's out one final gutteral roar as it drops lifelessly to the ground.  You dust yourself off, sheath your sword and head to the nearest tavern.  You deserve a drink!";
                roadBlock4_2Final.PreviousOptionId = option3_1.Id;
                roadBlock4_2Final.StartingPoint    = false;

                context.RoadBlock.Add(roadBlock4_2Final);
                context.SaveChanges();
            }
        }
Пример #14
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool Evolve()
        {
            // any shift left?
            if (!CanEvolve)
            {
                return(false);
            }

            // increase pointer to next block height
            Pointer++;

            // set current shift to the actual shift we process
            //_currentShift = Shifts[Pointer];
            if (!Shifts.TryGetValue(Pointer, out _currentShift))
            {
                return(false);
            }

            if (Pointer % 180 == 0)
            {
                HomeTown.Shop.Resupply(_currentShift);
            }

            // we go for the adventure if there is one up
            if (Adventure != null && Adventure.IsActive)
            {
                Adventure.Enter(this, _currentShift);
                return(true);
            }

            if (Adventure != null && Adventure.AdventureState == AdventureState.Completed && Adventure.Reward != null)
            {
                AddExp(Adventure.Reward.Exp);
                AddGold(Adventure.Reward.Gold);
            }

            Adventure   = null;
            MogwaiState = MogwaiState.HomeTown;

            // first we always calculated current lazy experience
            var lazyExp = Experience.GetExp(CurrentLevel, _currentShift);

            if (lazyExp > 0)
            {
                AddExp(Experience.GetExp(CurrentLevel, _currentShift));
            }

            if (!_currentShift.IsSmallShift)
            {
                // TODO remove this is only for debug
                Log.Info(_currentShift.ToString());

                switch (_currentShift.Interaction.InteractionType)
                {
                case InteractionType.Adventure:
                    // only alive mogs can go to an adventure, finish adventure before starting a new one ...
                    if (CanAct && (Adventure == null || !Adventure.IsActive))
                    {
                        Adventure = AdventureGenerator.Create(_currentShift,
                                                              (AdventureAction)_currentShift.Interaction);
                        Adventure.Enter(this, _currentShift);
                        MogwaiState = MogwaiState.Adventure;
                        return(true);
                    }
                    break;

                case InteractionType.Leveling:
                    var levelingAction = (LevelingAction)_currentShift.Interaction;
                    switch (levelingAction.LevelingType)
                    {
                    case LevelingType.Class:
                        LevelClass(levelingAction.ClassType);
                        break;

                    case LevelingType.Ability:
                        break;

                    case LevelingType.None:
                        break;
                    }
                    break;

                case InteractionType.Special:
                    var specialAction = (SpecialAction)_currentShift.Interaction;

                    if (SpecialAction(specialAction.SpecialType))
                    {
                        return(true);
                    }
                    break;
                }
            }

            // lazy health regeneration, only rest healing if he is not dieing TODO check MogwaiState?
            if (MogwaiState == MogwaiState.HomeTown && !IsDying)
            {
                Heal(_currentShift.IsSmallShift ? 2 * CurrentLevel : CurrentLevel, HealType.Rest);
            }

            History.Add(LogType.Info, $"Evolved {Coloring.Name(Name)} shift {Coloring.Exp(Pointer)}!");

            // no more shifts to proccess, no more logging possible to the game log
            _currentShift = null;

            return(true);
        }
 public AdventureController(Adventure adventure, Map adventureMap, AdventureUIController uiController)
 {
     _adventure    = adventure;
     _adventureMap = adventureMap;
     _uiController = uiController;
 }
Пример #16
0
        public void Generate()
        {
            if (adventureGenerator.HasAdventure(SwenugTextAdventure))
            {
                return;
            }

            var swenugMeetupRoom = new Room
            {
                Id          = "rooms/1",
                Name        = "Swenug meetup room at Kvadrat",
                Description = @"
You find yourself in a well lit room surrounded by distinguished people. Of different appearance and complexions, yet somehow
sharing the same knowing expression, the same disposition and depth of look of people that has pursued, unrelentlessly, the fleeting
virtue of wisdom.

Some standing, some sitting, some resting in different corners of the room, they stand, sit and rest listening closely and 
attentively to yet another one of them, one bald fellow of fair expression that talks... about... RavenDB... 

At the end of the room, in a majestic sign, it reads _Kvadrat_.

****************************************************************************************************
    Thank you Kvadrat for sponsoring this event!! You've just become immortal! (www.kvadrat.se) 
****************************************************************************************************

",
                Pathways    = new RoomPathways(
                    new RoomPathway {
                    Direction = "outside", RoomId = "rooms/2"
                }),
                ArbitraryActions = new ArbitraryActions(
                    new ArbitraryAction {
                    Action = "say RavenDB sucks", Response = diedie
                },
                    new ArbitraryAction {
                    Action = "hi", Response = @"The bald figure responds: ""hi traveller, where come you from and what brings you here?"""
                },
                    new ArbitraryAction {
                    Action = "grue", Response = @"The bald figure ponders and says: ""...grues... evil creatures those are... You are likely to be eaten by a grue"""
                }
                    )
            };
            var corridor = new Room
            {
                Id          = "rooms/2",
                Name        = "Corridor",
                Description = @"

",
                Pathways    = new RoomPathways(
                    new RoomPathway {
                    Direction = "inside", RoomId = "rooms/1"
                },
                    new RoomPathway {
                    Direction = "the dark room", RoomId = "rooms/3"
                },
                    new RoomPathway {
                    Direction = "the lobby", RoomId = "rooms/6"
                },
                    new RoomPathway {
                    Direction = "the toilet", RoomId = "rooms/4"
                })
            };
            var programmersRoom = new Room
            {
                Id          = "rooms/3",
                Name        = "Programmer's Lair",
                Description = @"
",
                Pathways    = new RoomPathways(
                    new RoomPathway {
                    Direction = "outside", RoomId = "rooms/2"
                })
            };
            var toilet = new Room
            {
                Id          = "rooms/4",
                Name        = "Toilet",
                Description = @"

",
                Pathways    = new RoomPathways(
                    new RoomPathway {
                    Direction = "outside", RoomId = "rooms/2"
                })
            };
            var cafeteria = new Room
            {
                Id          = "rooms/5",
                Name        = "Cafeteria",
                Description = @"

",
                Pathways    = new RoomPathways(
                    new RoomPathway {
                    Direction = "outside", RoomId = "rooms/6"
                })
            };
            var lobby = new Room()
            {
                Id          = "rooms/6",
                Name        = "Lobby",
                Description = "Lobby",
                Pathways    = new RoomPathways(
                    new RoomPathway {
                    Direction = "the corridor", RoomId = "rooms/2"
                },
                    new RoomPathway {
                    Direction = "cafeteria", RoomId = "rooms/5"
                })
            };

            adventureGenerator.AddRooms(swenugMeetupRoom, corridor, programmersRoom, cafeteria, toilet, lobby);

            var swenugTextAdventure = new Adventure
            {
                Name = SwenugTextAdventure,
                Map  = new Map {
                    StartingRoom = swenugMeetupRoom
                }
            };

            adventureGenerator.CreateAdventure(swenugTextAdventure);
        }
 private void DiscardCreation()
 {
     try
     {
         AppGlobals.inCreationMode = false;
         newCreation = null;
         MainMenu mainMenu = new MainMenu();
         this.NavigationService.Navigate(mainMenu);
     }
     catch (Exception err)
     {
         exHand.LogException(err, "StoryGeneratorStageOne-DiscardCreation");
     }
 }
    public void ResolveEffects(Adventure inAdventure)
    {
        if (!wasEvaded)
        {
            //update most recent source of damage to target
            target.UpdateMostRecentSourceOfDamage(source.name, skill.id, false, wasBackAttack);

            target.stats.Add(statChanges);

            StatusEffect curEffect;
            int          numStatusNegative = 0;
            int          numStatusResisted = 0;

            for (int i = 0; i < statusEffects.Count; i++)
            {
                curEffect = statusEffects[i];

                if (curEffect.IsNegative())
                {
                    numStatusNegative++;
                    if (target.HasItemToPreventStatusEffect(curEffect.type) || target.PassesStatusResistCheck(curEffect.type))
                    {
                        numStatusResisted++;
                        curEffect.MarkAsResisted();
                    }
                    else
                    {
                        target.ApplyStatusEffect(curEffect);
                    }
                }
                else
                {
                    target.ApplyStatusEffect(curEffect);
                }
            }

            int numStatusNegativeReceived = numStatusNegative - numStatusResisted;

            //REMOVED: tracking/recording stats related to status effects

            if (numStatusNegative > 0 && numStatusNegative == numStatusResisted)
            {
                resistedAllNegativeStatuses = true;
            }

            //clear the resisted ones
            statusEffects.RemoveAll(e => e.wasResisted);

            target.stats.EnforceNonzeroForKeys(statChanges.GetKeys());
            target.stats.EnforceLimits();

            //turn target around
            if (turnedTargetAround)
            {
                target.FlipDirection();
            }

            //item earned on hit?
            if (itemIdEarnedOnHit != null)
            {
                inAdventure.AddLoot(new Loot(LootType.ITEM, itemIdEarnedOnHit, 1));
            }

            //stolen loot?
            if (stolenLoot != null)
            {
                inAdventure.AddLootBundle(stolenLoot);
            }

            //exhaustion
            if (turnsExhaustedSourceFor > 0)
            {
                source.SetExhaustedTurns(turnsExhaustedSourceFor);
            }

            //autocrits?
            if (autocritsGiven > 0)
            {
                target.SetAutoCrits(autocritsGiven);
            }

            //huntress capture?
            if (!target.isOre && source.id == CharId.HUNTRESS && target.IsInFaction(Faction.ENEMY) && target.species == Species.CREATURE)
            {
                if (target.stats.Get(Stat.hp) == 0)
                {
                    wasHuntressCapture = true;
                    EnemyCharacterData ecd = (EnemyCharacterData)target;
                    //Main.services.saveManager.currentFile.IncrementHuntressCaptures(ecd.storageId);
                }
            }
        }
    }
Пример #19
0
 private void LoadFlowDocsForStory(Adventure currLocalAdventure)
 {
     try
     {
         DirectoryInfo currentDir = new DirectoryInfo(@currLocalAdventure.folderPath);
         foreach (FileInfo files in currentDir.GetFiles())
         {
             if (files.Name.Contains(".png") || files.Name.Contains(".jpg") || files.Name.Contains(".gif") || files.Name.Contains(".bmp"))
                 adventureSceneFiles.Add(files);
             else if (!files.Name.Contains("-meta") && !files.Name.Contains("-adventuremeta"))
                 adventureStoryFiles.Add(files);
             else
                 adventureStoryMetaFiles.Add(files);
         }
     }
     catch (Exception err)
     {
         exHand.LogException(err, "Story-LoadFlowDocsForStory");
     }
 }
Пример #20
0
        public void SaveAdventure(Adventure currLocalAdventure)
        {
            //SAVE ONGOING STORY
            using (FileStream fs = new FileStream(@AppGlobals.saveGameDir + "/" + AppGlobals.currGlobalAdventure.Title + ".xaml", FileMode.Create))
            {
                try
                {
                    CYOA.utilities.XamlWriter.Save(currLocalAdventure.ongoingStory, fs);
                }
                catch (Exception err)
                {
                    exHand.LogException(err, "Story-SaveAdventure");
                }
                finally
                {
                    fs.Close();
                }
                    
            }

            //SAVE CURRENT STORY META FOR LOADING
            using (FileStream fs = new FileStream(@AppGlobals.saveGameMetaDir + "/" + AppGlobals.currGlobalAdventure.Title + ".xaml", FileMode.Create))
            {
                try
                {
                    FlowDocument currSaveMeta = new FlowDocument();
                    Paragraph newBlock = new Paragraph();
                    newBlock.Inlines.Add("[%ARMOR%]" + AppGlobals.currGlobalAdventure.Armor.ToString());
                    newBlock.Inlines.Add("[%ARMORSET%]" + AppGlobals.currGlobalAdventure.ArmorSet.ArmorName);
                    newBlock.Inlines.Add("[%AUTHOR%]" + AppGlobals.currGlobalAdventure.Author);
                    newBlock.Inlines.Add("[%CHARACTERNAME%]" + AppGlobals.currGlobalAdventure.CharacterName);
                    newBlock.Inlines.Add("[%CHARACTERTITLE%]" + AppGlobals.currGlobalAdventure.CharacterTitle);
                    newBlock.Inlines.Add("[%CURRENTCHAPTER%]" + AppGlobals.currGlobalAdventure.CurrentChapter.ToString());
                    newBlock.Inlines.Add("[%DECISIONSMADE%]" + AppGlobals.currGlobalAdventure.DecisionsMade.ToString());
                    newBlock.Inlines.Add("[%FOLDERPATH%]" + AppGlobals.currGlobalAdventure.folderPath);
                    newBlock.Inlines.Add("[%HEALTH%]" + AppGlobals.currGlobalAdventure.Health.ToString());
                    newBlock.Inlines.Add("[%LUCK%]" + AppGlobals.currGlobalAdventure.Luck.ToString());
                    newBlock.Inlines.Add("[%MAGIC%]" + AppGlobals.currGlobalAdventure.Magic.ToString());
                    newBlock.Inlines.Add("[%MELEEWEAPON%]" + AppGlobals.currGlobalAdventure.MeleeWeapon.WeaponName);
                    newBlock.Inlines.Add("[%PUBLISHDATE%]" + AppGlobals.currGlobalAdventure.PublishDate);
                    newBlock.Inlines.Add("[%RANGEDWEAPON%]" + AppGlobals.currGlobalAdventure.RangedWeapon.WeaponName);
                    newBlock.Inlines.Add("[%SPEED%]" + AppGlobals.currGlobalAdventure.Speed.ToString());
                    newBlock.Inlines.Add("[%STORYLENGTH%]" + AppGlobals.currGlobalAdventure.StoryLength.ToString());
                    newBlock.Inlines.Add("[%SUMMARY%]" + AppGlobals.currGlobalAdventure.Summary);
                    newBlock.Inlines.Add("[%TITLE%]" + AppGlobals.currGlobalAdventure.Title);
                    newBlock.Inlines.Add("[%GENRE%]" + AppGlobals.currGlobalAdventure.Genre);
                    newBlock.Inlines.Add("[%THEME%]" + AppGlobals.currGlobalAdventure.Theme);

                    currSaveMeta.Blocks.Add(newBlock);

                    CYOA.utilities.XamlWriter.Save(currSaveMeta, fs);
                }
                catch (Exception err)
                {
                    exHand.LogException(err, "Story-SaveAdventure");
                }
                finally
                {
                    fs.Close();
                }

            }
        }
Пример #21
0
 public Story(Adventure currAdventure)
 {
     InitializeComponent();
     Loaded += Story_Loaded;
     LoadStoryInfo(currAdventure);
 }
Пример #22
0
 public void AddAdventure(Adventure myAdventure)
 {
     context.Adventures.Add(myAdventure);
     context.SaveChanges();
 }
Пример #23
0
        public override async Task <SkillResponse> ProcessMessageAsync(SkillRequest skill, ILambdaContext context)
        {
            try {
                // load adventure from S3
                string source;
                try {
                    using (var s3Response = await _s3Client.GetObjectAsync(_adventureFileBucket, _adventureFileKey)) {
                        var memory = new MemoryStream();
                        await s3Response.ResponseStream.CopyToAsync(memory);

                        source = Encoding.UTF8.GetString(memory.ToArray());
                    }
                } catch (AmazonS3Exception e) when(e.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new Exception($"unable to load file from 's3://{_adventureFileBucket}/{_adventureFileKey}'");
                }

                // process adventure file
                var adventure = Adventure.Parse(source, Path.GetExtension(_adventureFileKey));

                // restore player object from session
                var state = await RestoreAdventureState(adventure, skill.Session);

                var engine = new AdventureEngine(adventure, state);
                LogInfo($"player status: {state.Status}");

                // decode skill request
                IOutputSpeech response = null;
                IOutputSpeech reprompt = null;
                switch (skill.Request)
                {
                // skill was activated without an intent
                case LaunchRequest launch:
                    LogInfo("launch");

                    // kick off the adventure!
                    if (state.Status == AdventureStatus.New)
                    {
                        state.Status = AdventureStatus.InProgress;
                        response     = Do(engine, AdventureCommandType.Restart, new XElement("speak", new XElement("p", new XText(PROMPT_WELCOME))));
                    }
                    else
                    {
                        response = Do(engine, AdventureCommandType.Describe, new XElement("speak", new XElement("p", new XText(PROMPT_WELCOME_BACK))));
                    }
                    reprompt = Do(engine, AdventureCommandType.Help);
                    break;

                // skill was activated with an intent
                case IntentRequest intent:
                    var isAdventureCommand = Enum.TryParse(intent.Intent.Name, true, out AdventureCommandType command);

                    // check if the intent is an adventure intent
                    if (isAdventureCommand)
                    {
                        LogInfo($"adventure intent ({intent.Intent.Name})");
                        response = Do(engine, command);
                        reprompt = Do(engine, AdventureCommandType.Help);
                    }
                    else
                    {
                        // built-in intents
                        switch (intent.Intent.Name)
                        {
                        case BuiltInIntent.Help:
                            LogInfo($"built-in help intent ({intent.Intent.Name})");
                            response = Do(engine, AdventureCommandType.Help);
                            reprompt = Do(engine, AdventureCommandType.Help);
                            break;

                        case BuiltInIntent.Stop:
                        case BuiltInIntent.Cancel:
                            LogInfo($"built-in stop/cancel intent ({intent.Intent.Name})");
                            response = Do(engine, AdventureCommandType.Quit);
                            break;

                        default:

                            // unknown & unsupported intents
                            LogWarn("intent not recognized");
                            response = new PlainTextOutputSpeech {
                                Text = PROMPT_MISUNDERSTOOD
                            };
                            reprompt = Do(engine, AdventureCommandType.Help);
                            break;
                        }
                    }
                    break;

                // skill session ended (no response expected)
                case SessionEndedRequest ended:
                    LogInfo("session ended");
                    return(ResponseBuilder.Empty());

                // exception reported on previous response (no response expected)
                case SystemExceptionRequest error:
                    LogWarn($"skill request exception: {JsonConvert.SerializeObject(skill)}");
                    return(ResponseBuilder.Empty());

                // unknown skill received (no response expected)
                default:
                    LogWarn($"unrecognized skill request: {JsonConvert.SerializeObject(skill)}");
                    return(ResponseBuilder.Empty());
                }

                // check if the player reached the end
                var roomCompleteCounter            = 0;
                Dictionary <string, string> result = new Dictionary <string, string>();
                if (adventure.Places[state.CurrentPlaceId].Finished)
                {
                    // TODO: send completion notification with player statistics
                    state.RoomCount++;
                    LogInfo("Current place at room end: " + state.CurrentPlaceId);
                    LogInfo("STATUS at room end: " + state.Status);
                    LogInfo("TIME at room complete: " + state.StartTime);
                    LogInfo("ROOM COUNT at end: " + state.RoomCount);

                    //if(state.CurrentPlaceId == "end-room-good"){
                    result.Add("rooms", roomCompleteCounter.ToString());
                    await _SNSClient.PublishAsync(_adventurePlayerFinishedTopic, "Rooms completed: " + result["rooms"]);

                    //}
                }

                // create/update player record so we can continue in a future session
                await StoreAdventureState(state);

                // respond with serialized player state
                if (reprompt != null)
                {
                    return(ResponseBuilder.Ask(
                               response,
                               new Reprompt {
                        OutputSpeech = reprompt
                    },
                               new Session {
                        Attributes = new Dictionary <string, object> {
                            [SESSION_STATE_KEY] = state
                        }
                    }
                               ));
                }
                return(ResponseBuilder.Tell(response));
            } catch (Exception e) {
                LogError(e, "exception during skill processing");
                return(ResponseBuilder.Tell(new PlainTextOutputSpeech {
                    Text = PROMPT_OOPS
                }));
            }
        }
Пример #24
0
 public void DeleteAdventure(Adventure myAdventure)
 {
     context.Adventures.Remove(myAdventure);
     context.SaveChanges();
 }
Пример #25
0
        public Adventure Create(int id, int level)
        {
            if (_userAdventures.Count >= MaxAdventures)
            {
                return(null);
            }

            var adventure = new Adventure();

            adventure.Id = id;
            //PRZYGODY(NR,P_X)=ARMIA(A,0,TNOGI)-70
            adventure.Y         = GlobalUtils.Rand(9) + 1;
            adventure.Direction = null;
            adventure.Level     = level;

            switch (id)
            {
            case 1:
            {
                // kopalnia
                adventure.Price   = 20 * level;
                adventure.Terrain = 8;
                adventure.AddReward(RewardType.Money, level * 10000);
            }
            break;

            case 2:
            {
                // kurhan
                adventure.Price         = GlobalUtils.Rand(20 * level);
                adventure.Terrain       = 9;
                adventure.RelatedPerson = NamesGenerator.Generate();
                adventure.AddReward(RewardType.Money, level * 100);

                /*
                 *  adventures.AddReward(RewardType.Weapon, weapon);
                 *  Repeat
                 *      BRON=Rnd(MX_WEAPON)
                 *      BTYP=BRON(BRON,B_TYP)
                 *  Until BRON(BRON,B_CENA)>=1000 and BRON(BRON,BCENA)<100+LEVEL*1000 and BTYP<>5 and BTYP<>8 and BTYP<>13 and BTYP<>14 and BTYP<16
                 *  PRZYGODY(NR,P_BRON)=BRON
                 */
            }
            break;

            case 3:
            {
                // bandyci
                adventure.Price = 0;
                adventure.AddReward(RewardType.Money, 4000 + GlobalUtils.Rand(2000) + level * 100);
            }
            break;

            case 4:
            {
                // córa
                adventure.Price         = 0;
                adventure.RelatedPerson = NamesGenerator.Generate();

                /*
                 *  adventure.AddReward(RewardType.City, city.Id);
                 *  Repeat : MIASTO=Rnd(49) : Until MIASTA(MIASTO,0,M_CZYJE)<>1
                 */
            }
            break;

            default:
                break;
            }

            _userAdventures.Add(adventure);
            return(adventure);
        }
        private void SelectAdventure()
        {
            try
            {
                //LOADS THE ADVENTURE BASED OFF THE SELECTED ITEM
                Adventure selectedAdventure = new Adventure();
                var reconstrucedPath = lvAvailableAdventures.SelectedItem.ToString().ToLower() + "-adventuremeta.xaml";
                using (FileStream fs = File.OpenRead(@AppGlobals.adventureDir + "/" + lvAvailableAdventures.SelectedItem.ToString().ToLower() + "/" + reconstrucedPath))
                {
                    FlowDocument document = (FlowDocument)XamlReader.Load(fs);

                    //BREAK OUT INTO TAGS TO ASSIGN
                    List<Block> docBlocks = document.Blocks.ToList();
                    foreach (Block indivBlock in docBlocks)
                    {
                        TextRange range = new TextRange(indivBlock.ContentStart, indivBlock.ContentEnd);
                        string[] metaTexts = range.Text.Split('[');
                    foreach (string indivString in metaTexts)
                    {
                        if (indivString.Contains("%TITLE%"))
                        {
                            selectedAdventure.Title = indivString.Split(']').Last();
                        }
                        if (indivString.Contains("%AUTHOR%"))
                        {
                            selectedAdventure.Author = indivString.Split(']').Last();
                        }
                        if (indivString.Contains("%PUBLISHDATE%"))
                        {
                            selectedAdventure.PublishDate = indivString.Split(']').Last();
                        }
                        if (indivString.Contains("%SUMMARY%"))
                        {
                            selectedAdventure.Summary = indivString.Split(']').Last();
                        }
                        if (indivString.Contains("%GENRE%"))
                        {
                            selectedAdventure.Genre = indivString.Split(']').Last();
                        }
                        if (indivString.Contains("%THEME%"))
                        {
                            selectedAdventure.Theme = indivString.Split(']').Last();
                        }
                        if (indivString.Contains("%MELEEWEAPON%"))
                        {
                            selectedAdventure.MeleeWeapon = new Weapon();
                            selectedAdventure.MeleeWeapon.WeaponName = indivString.Split(']').Last();
                        }
                        if (indivString.Contains("%RANGEDWEAPON%"))
                        {
                            selectedAdventure.RangedWeapon = new Weapon();
                            selectedAdventure.RangedWeapon.WeaponName = indivString.Split(']').Last();
                        }
                        if (indivString.Contains("%ARMORSET%"))
                        {
                            selectedAdventure.ArmorSet = new Armor();
                            selectedAdventure.ArmorSet.ArmorName = indivString.Split(']').Last();
                        }
                        if (indivString.Contains("%CHARACTERNAME%"))
                        {
                            selectedAdventure.CharacterName = indivString.Split(']').Last();
                        }
                        if (indivString.Contains("%CHARACTERTITLE%"))
                        {
                            selectedAdventure.CharacterTitle = indivString.Split(']').Last();
                        }
                        if (indivString.Contains("%HEALTH%"))
                        {
                            selectedAdventure.Health = Convert.ToInt32(indivString.Split(']').Last());
                        }
                        if (indivString.Contains("%ARMOR%"))
                        {
                            selectedAdventure.Armor = Convert.ToInt32(indivString.Split(']').Last());
                        }
                        if (indivString.Contains("%SPEED%"))
                        {
                            selectedAdventure.Speed = Convert.ToInt32(indivString.Split(']').Last());
                        }
                        if (indivString.Contains("%MAGIC%"))
                        {
                            selectedAdventure.Magic = Convert.ToInt32(indivString.Split(']').Last());
                        }
                        if (indivString.Contains("%LUCK%"))
                        {
                            selectedAdventure.Luck = Convert.ToInt32(indivString.Split(']').Last());
                        }
                        
                    }
                        selectedAdventure.folderPath = AppGlobals.adventureDir + "/" + lvAvailableAdventures.SelectedItem.ToString().ToLower();
                    }
                }
                AppGlobals.currGlobalAdventure = selectedAdventure;
                Story storyPage = new Story(AppGlobals.currGlobalAdventure);
                this.NavigationService.Navigate(storyPage);
            }
            catch (Exception err)
            {
                exHand.LogException(err, "StorySelection-SelectAdventure");
            }
        }