Inheritance: MonoBehaviour
Exemplo n.º 1
0
 static public BindingContext CreateInstance(
         CSemanticChecker pSemanticChecker,
         ExprFactory exprFactory,
         OutputContext outputContext,
         NameGenerator nameGenerator,
         bool bflushLocalVariableTypesForEachStatement,
         bool bAllowUnsafeBlocks,
         bool bIsOptimizingSwitchAndArrayInit,
         bool bShowReachability,
         bool bWrapNonExceptionThrows,
         bool bInRefactoring,
         KAID aidLookupContext
     )
 {
     return new BindingContext(
         pSemanticChecker,
         exprFactory,
         outputContext,
         nameGenerator,
         bflushLocalVariableTypesForEachStatement,
         bAllowUnsafeBlocks,
         bIsOptimizingSwitchAndArrayInit,
         bShowReachability,
         bWrapNonExceptionThrows,
         bInRefactoring,
         aidLookupContext);
 }
Exemplo n.º 2
0
        protected BindingContext(
            CSemanticChecker pSemanticChecker,
            ExprFactory exprFactory,
            OutputContext outputContext,
            NameGenerator nameGenerator,
            bool bflushLocalVariableTypesForEachStatement,
            bool bAllowUnsafeBlocks,
            bool bIsOptimizingSwitchAndArrayInit,
            bool bShowReachability,
            bool bWrapNonExceptionThrows,
            bool bInRefactoring,
            KAID aidLookupContext
            )
        {
            m_ExprFactory = exprFactory;
            m_outputContext = outputContext;
            m_pNameGenerator = nameGenerator;
            m_pInputFile = null;
            m_pParentDecl = null;
            m_pContainingAgg = null;
            m_pCurrentSwitchType = null;
            m_pOriginalConstantField = null;
            m_pCurrentFieldSymbol = null;
            m_pImplicitlyTypedLocal = null;
            m_pOuterScope = null;
            m_pFinallyScope = null;
            m_pTryScope = null;
            m_pCatchScope = null;
            m_pCurrentScope = null;
            m_pSwitchScope = null;
            m_pCurrentBlock = null;
            m_UnsafeState = UNSAFESTATES.UNSAFESTATES_Unknown;
            m_FinallyNestingCount = 0;
            m_bInsideTryOfCatch = false;
            m_bInFieldInitializer = false;
            m_bInBaseConstructorCall = false;
            m_bAllowUnsafeBlocks = bAllowUnsafeBlocks;
            m_bIsOptimizingSwitchAndArrayInit = bIsOptimizingSwitchAndArrayInit;
            m_bShowReachability = bShowReachability;
            m_bWrapNonExceptionThrows = bWrapNonExceptionThrows;
            m_bInRefactoring = bInRefactoring;
            m_bInAttribute = false;
            m_bRespectSemanticsAndReportErrors = true;
            m_bflushLocalVariableTypesForEachStatement = bflushLocalVariableTypesForEachStatement;
            m_ppamis = null;
            m_pamiCurrent = null;
            m_pInitType = null;
            m_returnErrorSink = null;

            Debug.Assert(pSemanticChecker != null);
            this.SemanticChecker = pSemanticChecker;
            this.SymbolLoader = SemanticChecker.GetSymbolLoader();
            m_outputContext.m_pThisPointer = null;
            m_outputContext.m_pCurrentMethodSymbol = null;

            m_aidExternAliasLookupContext = aidLookupContext;
            CheckedNormal = false;
            CheckedConstant = false;
        }
Exemplo n.º 3
0
    void Update()
    {
        if (NewCustomerTimer <= 0)
        {
            Customer newguy = new Customer(NameGenerator.GrabRandomName(), "Food", "Drink", 1.05f, BaseNewCustomerTimer);
            CustomerList.Add(newguy);
            Debug.Log("Customer Name: " + newguy.Name);
            Debug.Log("Customer Count: " + CustomerList.Count);
            NewCustomerTimer = BaseNewCustomerTimer;
            SetSlider(1);

            SetPanelContents();
        }
        else
        {
            NewCustomerTimer -= Time.deltaTime;
            SetSlider(NewCustomerTimer / BaseNewCustomerTimer);
        }
    }
Exemplo n.º 4
0
        public string GetClrNamespace(string xmlNamespace)
        {
            string clrNamespace = string.Empty;

            if (xmlNamespace == null)
            {
                return(clrNamespace);
            }

            if (namespaceMapping.TryGetValue(xmlNamespace, out clrNamespace))
            {
                return(clrNamespace);
            }

            clrNamespace = NameGenerator.MakeValidCLRNamespace(
                xmlNamespace, this.NameMangler2);
            namespaceMapping.Add(xmlNamespace, clrNamespace);
            return(clrNamespace);
        }
Exemplo n.º 5
0
        public IActionResult Register(RegisterViewModel register)
        {
            if (!ModelState.IsValid)
            {
                return(View(register));
            }


            if (_userService.IsExistUserName(register.UserName))
            {
                ModelState.AddModelError("UserName", "نام کاربری معتبر نمی باشد");
                return(View(register));
            }

            if (_userService.IsExistEmail(FixedText.FixEmail(register.Email)))
            {
                ModelState.AddModelError("Email", "ایمیل معتبر نمی باشد");
                return(View(register));
            }


            DataLayer.Entities.User.User user = new DataLayer.Entities.User.User()
            {
                ActiveCode   = NameGenerator.GenerateUniqCode(),
                Email        = FixedText.FixEmail(register.Email),
                IsActive     = false,
                Password     = PasswordHelper.EncodePasswordMd5(register.Password),
                RegisterDate = DateTime.Now,
                UserAvatar   = "Defult.jpg",
                UserName     = register.UserName
            };
            _userService.AddUser(user);

            #region Send Activation Email

            string body = _viewRender.RenderToStringAsync("_ActiveEmail", user);
            SendEmail.Send(user.Email, "فعالسازی", body);

            #endregion

            return(View("SuccessRegister", user));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Will create and return a Kobold of the level passed into the method.
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        public static Kobold Create(int level)
        {
            int    health = Dice.Roll("2D5");
            Kobold kobold = new Kobold
            {
                Attack        = Dice.Roll("1D3") + level / 3,
                AttackChance  = Dice.Roll("25D3"),
                Awareness     = 10,
                Color         = Colors.DbBrightWood,
                Defense       = Dice.Roll("1D3") + level / 3,
                DefenseChance = Dice.Roll("10D4"),
                Gold          = Dice.Roll("5D5"),
                Health        = health,
                MaxHealth     = health,
                Name          = NameGenerator.GenerateMonsterName() + ", Kobold",
                Speed         = 14,
                Symbol        = 'k'
            };

            // Low chance they'll have a healing potion.
            if (Dice.Roll("1D6") >= 5)
            {
                kobold.items.Add(new HealingPotion());
            }
            // Give some Kobolds helmets
            if (Dice.Roll("1D6") >= 5)
            {
                kobold.Head = HeadEquipment.GenerateNextLowLevel();
            }
            // Give some Kobolds body armor
            if (Dice.Roll("1D6") >= 5)
            {
                kobold.Body = BodyEquipment.GenerateNextLowLevel();
            }
            // Give some Kobolds feet and hand armor rarely
            if (Dice.Roll("1D6") > 5)
            {
                kobold.Feet = FeetEquipment.GenerateNextLowLevel();
                kobold.Hand = HandEquipment.GenerateNextLowLevel();
            }
            return(kobold);
        }
Exemplo n.º 7
0
        private static SyntaxNode GetNewMethodDeclaration(
            IMethodSymbol method,
            TArgumentSyntax argument,
            SeparatedSyntaxList <TArgumentSyntax> argumentList,
            SyntaxGenerator generator,
            SyntaxNode declaration,
            ISemanticFactsService semanticFacts,
            string argumentName,
            SyntaxNode expression,
            SemanticModel semanticModel,
            ITypeSymbol parameterType)
        {
            if (!string.IsNullOrWhiteSpace(argumentName))
            {
                var newParameterSymbol = CodeGenerationSymbolFactory.CreateParameterSymbol(
                    attributes: default(ImmutableArray <AttributeData>),
                    refKind: RefKind.None,
                    isParams: false,
                    type: parameterType,
                    name: argumentName);

                var newParameterDeclaration = generator.ParameterDeclaration(newParameterSymbol);
                return(generator.AddParameters(declaration, new[] { newParameterDeclaration }));
            }
            else
            {
                var name       = semanticFacts.GenerateNameForExpression(semanticModel, expression);
                var uniqueName = NameGenerator.EnsureUniqueness(name, method.Parameters.Select(p => p.Name));

                var newParameterSymbol = CodeGenerationSymbolFactory.CreateParameterSymbol(
                    attributes: default(ImmutableArray <AttributeData>),
                    refKind: RefKind.None,
                    isParams: false,
                    type: parameterType,
                    name: uniqueName);

                var argumentIndex           = argumentList.IndexOf(argument);
                var newParameterDeclaration = generator.ParameterDeclaration(newParameterSymbol);
                return(generator.InsertParameters(
                           declaration, argumentIndex, new[] { newParameterDeclaration }));
            }
        }
Exemplo n.º 8
0
        public static void NamesFromRulepack()
        {
            IEnumerable <RulePackDef> first = from f in DefDatabase <FactionDef> .AllDefsListForReading
                                              select f.factionNameMaker;
            IEnumerable <RulePackDef> second = from f in DefDatabase <FactionDef> .AllDefsListForReading
                                               select f.settlementNameMaker;
            IEnumerable <RulePackDef> second2 = from f in DefDatabase <FactionDef> .AllDefsListForReading
                                                select f.playerInitialSettlementNameMaker;
            IEnumerable <RulePackDef> second3 = from f in DefDatabase <FactionDef> .AllDefsListForReading
                                                select f.pawnNameMaker;
            IEnumerable <RulePackDef> second4 = from d in DefDatabase <RulePackDef> .AllDefsListForReading
                                                where d.defName.Contains("Namer")
                                                select d;
            IOrderedEnumerable <RulePackDef> orderedEnumerable = from d in (from d in first.Concat(second).Concat(second2).Concat(second3)
                                                                            .Concat(second4)
                                                                            where d != null
                                                                            select d).Distinct()
                                                                 orderby d.defName
                                                                 select d;
            List <FloatMenuOption> list = new List <FloatMenuOption>();

            foreach (RulePackDef item2 in orderedEnumerable)
            {
                RulePackDef     localNamer = item2;
                FloatMenuOption item       = new FloatMenuOption(localNamer.defName, delegate
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.AppendLine("Testing RulePack " + localNamer.defName + " as  a name generator:");
                    for (int i = 0; i < 200; i++)
                    {
                        string text = (i % 2 != 0) ? null : "Smithee";
                        StringBuilder stringBuilder2 = stringBuilder;
                        RulePackDef rootPack         = localNamer;
                        string testPawnNameSymbol    = text;
                        stringBuilder2.AppendLine(NameGenerator.GenerateName(rootPack, null, appendNumberIfNameUsed: false, null, testPawnNameSymbol));
                    }
                    Log.Message(stringBuilder.ToString());
                });
                list.Add(item);
            }
            Find.WindowStack.Add(new FloatMenu(list));
        }
        public ActionResult ActiveAccount(string tokenstring)
        {
            var activecookie = Request.Cookies["activeacount"];
            int repeatnumber = (activecookie != null ? int.Parse(activecookie) : 0);

            if (repeatnumber > 3)
            {
                ViewBag.status  = "Error";
                ViewBag.message = "بیش از حد از این لینک استفاده کرده اید";
                repeatnumber   += 1;

                return(View());
            }

            var user = db.tbl_user.Where(a => a.Tokenstring == tokenstring).SingleOrDefault();

            if (user == null)
            {
                ViewBag.status  = "Error";
                ViewBag.message = "چنین کاربری وجود ندارد";
                repeatnumber   += 1;
                Response.Cookies.Append("activeacount", repeatnumber.ToString(), new CookieOptions()
                {
                    Expires = DateTime.Now.AddMinutes(10)
                });

                return(View());
            }
            user.status      = true;
            user.Tokenstring = NameGenerator.GenerateUniqCode();
            db.SaveChanges();
            _userservices.GiveAccessMenuToUser(user.id);
            ViewBag.status  = "Success";
            ViewBag.message = "حساب کاربری شما فعال گردید.";
            repeatnumber   += 1;
            Response.Cookies.Append("activeacount", repeatnumber.ToString(), new CookieOptions()
            {
                Expires = DateTime.Now.AddMinutes(10)
            });

            return(View());
        }
    public void showMessage(string bodyText)
    {
        Debug.Log("show start message with body: " + bodyText);
        textBack.fadeInBack();
        this.transform.localScale = startScale;
        fadeOutTimer  = 0f;
        textKeyTimer  = 0f;
        charCount     = -1;
        isTriggered   = true;
        displayString = "";
        contentString = "";
        txtMesh.text  = "";
        //displayString = bodyText;
        beginningString = "It is over for us.\nThis is " + NameGenerator.getNewName() + "'s final transmission...\n";
        contentString  += beginningString + bodyText + "\n...............end";
        charThreshold   = contentString.Length;

        Debug.Log("content length:" + contentString.Length);
        Debug.Log("char:" + charThreshold);
    }
Exemplo n.º 11
0
    void Start()
    {
        instance       = this;
        storyGenerator = new StoryGenerator();
        nameGenerator  = new NameGenerator();
        Peace firstState = new Peace();

        WorldEvents.Add(firstState);
        for (int i = 0; i < countryAmount; i++)
        {
            countries.Add(new Country(firstState));
            countries[i].name = GenerateName();
        }
        countries[1].AllActions.Remove("DeclareWar");
        countries[1].AllActions.Remove("Battle");
        foreach (Country c in countries)
        {
            c.Countries = countries;
        }
    }
Exemplo n.º 12
0
        private void button1_Click(object sender, EventArgs e)
        {
            INameGenerating nameGenerator = new NameGenerator(_threadRandom);
            var             network       = new FsmNetwork(nameGenerator);
            var             ensemble      = network.AddFsmEnsemble();
            var             fsmInput      = ensemble.AddFsmInput();

            fsmInput.AddStateValue("Papper");
            fsmInput.AddStateValue("Sten");
            fsmInput.AddStateValue("Påse");
            var fsmOutput = ensemble.AddFsmOutput();

            fsmOutput.AddStateValue("Äpple");
            fsmOutput.AddStateValue("Päron");
            fsmOutput.AddStateValue("Apelsin");
            var fsm = ensemble.AddFsm();

            fsm.ReceiveSignalFrom(fsmInput);
            fsm.SendSignalTo(fsmOutput);
        }
Exemplo n.º 13
0
    private IEnumerator SpawnCubes()
    {
        cubes = new List <GameObject>();
        Vector3 centerOfSphere = Vector3.zero;

        for (int i = 0; i < numberOfCubes; i++)
        {
            var cube = Instantiate(cubePrefab) as GameObject;
            cube.GetComponent <CubeBehaviour>().cubeMesh.transform.localPosition += new Vector3(0, 0, -sphereRadius);
            cube.GetComponent <CubeBehaviour>().Name = NameGenerator.GetRandomFirstName() + " " + NameGenerator.GetRandomLastName();

            cube.transform.parent = transform;
            Vector3 placementPosition = cube.transform.position;

            Vector3 normal = (placementPosition - centerOfSphere).normalized;
            cube.transform.LookAt(Random.onUnitSphere * sphereRadius);
            cubes.Add(cube);
            yield return(new WaitForSeconds(0.2f));
        }
    }
Exemplo n.º 14
0
        public override void PostSpawnSetup()
        {
            base.PostSpawnSetup();
            this.psykerPowerManager = new PsykerPowerManager(this);
            ChaosFollowerPawnKindDef pdef = this.psyker.kindDef as ChaosFollowerPawnKindDef;

            if (pdef != null && pdef.RenamePawns)
            {
                string rawName = NameGenerator.GenerateName(pdef.OverridingNameRulePack, delegate(string x)
                {
                    NameTriple nameTriple4 = NameTriple.FromString(x);
                    nameTriple4.ResolveMissingPieces(null);
                    return(!nameTriple4.UsedThisGame);
                }, false);
                NameTriple nameTriple = NameTriple.FromString(rawName);
                nameTriple.CapitalizeNick();
                nameTriple.ResolveMissingPieces(null);
                psyker.Name = nameTriple;
            }
        }
Exemplo n.º 15
0
        public override CILExpression ToCILExpression(CIntermediateLang cil)
        {
            var type    = TryInferType(cil).Clone(PointerDepth - 1, false);
            var @sizeof = new CILSizeof(SourceInfo, string.Format("{0}{1}", type.CName, new string('*', type.PointerDepth)));
            var size    = new CILBinaryOp(SourceInfo, Expression.ToCILExpression(cil), CILBinaryOp.OpType.Mul, @sizeof);
            var alloc   = new CILCall(SourceInfo, new CILIdent(SourceInfo, "malloc"), new List <CILExpression> {
                size
            });
            var tmpName = NameGenerator.NewTemp();
            var tmp     = new CILVariableDecl(SourceInfo, cil.SymTable.LookupType(type.CName), PointerDepth, tmpName, alloc);
            var rewrite = new CILRewriteExpression(SourceInfo, new List <CILNode>
            {
                tmp,
                new CILIdent(SourceInfo, tmp.Name)
            });

            return(rewrite);

            throw new NotImplementedException("TODO: Implement AstNewArrayOp");
        }
        private IEnumerable <MemberDeclarationSyntax> CreateDeclarations(ConstructorDeclarationSyntax constructor, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(constructor, cancellationToken);

            if (methodSymbol != null)
            {
                INamedTypeSymbol containingType = methodSymbol.ContainingType;

                if (containingType != null)
                {
                    ImmutableArray <ISymbol> members = containingType.GetMembers();

                    return(Infos
                           .Where(f => NameGenerator.IsUniqueName(f.Name, members, isCaseSensitive: true))
                           .Select(f => f.CreateDeclaration()));
                }
            }

            return(Infos.Select(f => f.CreateDeclaration()));
        }
        protected static SyntaxToken GenerateUniqueFieldName(
            SemanticDocument document,
            TExpressionSyntax expression,
            bool isConstant,
            CancellationToken cancellationToken)
        {
            var syntaxFacts   = document.Document.GetLanguageService <ISyntaxFactsService>();
            var semanticFacts = document.Document.GetLanguageService <ISemanticFactsService>();

            var semanticModel = document.SemanticModel;
            var baseName      = semanticFacts.GenerateNameForExpression(
                semanticModel, expression, isConstant, cancellationToken);

            // A field can't conflict with any existing member names.
            var declaringType = semanticModel.GetEnclosingNamedType(expression.SpanStart, cancellationToken);
            var reservedNames = declaringType.GetMembers().Select(m => m.Name);

            return(syntaxFacts.ToIdentifierToken(
                       NameGenerator.EnsureUniqueness(baseName, reservedNames, syntaxFacts.IsCaseSensitive)));
        }
Exemplo n.º 18
0
        public void TestGenerateUniqueName()
        {
            var a = NameGenerator.GenerateUniqueName("ABC", "txt", _ => true);

            Assert.True(a.StartsWith("ABC", StringComparison.Ordinal));
            Assert.True(a.EndsWith(".txt", StringComparison.Ordinal));
            Assert.False(a.EndsWith("..txt", StringComparison.Ordinal));

            var b = NameGenerator.GenerateUniqueName("ABC", ".txt", _ => true);

            Assert.True(b.StartsWith("ABC", StringComparison.Ordinal));
            Assert.True(b.EndsWith(".txt", StringComparison.Ordinal));
            Assert.False(b.EndsWith("..txt", StringComparison.Ordinal));

            var c = NameGenerator.GenerateUniqueName("ABC", "\u0640.txt", _ => true);

            Assert.True(c.StartsWith("ABC", StringComparison.Ordinal));
            Assert.True(c.EndsWith(".\u0640.txt", StringComparison.Ordinal));
            Assert.False(c.EndsWith("..txt", StringComparison.Ordinal));
        }
Exemplo n.º 19
0
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            var op = GetOpString();

            Expr.Codegen(cil, sb);
            var tmp    = cil.LastUsedVar;
            var result = NameGenerator.NewTemp();
            var fmt    = GetOpSide() == Side.Pre
                ? "{0} {1} = ({2}({3}));"
                : "{0} {1} = (({3}){2});";

            sb.LineDecl(SourceInfo);
            sb.AppendLine(string.Format(
                              fmt,
                              TryInferType(cil),
                              result,
                              op,
                              tmp));
            cil.LastUsedVar = result;
        }
Exemplo n.º 20
0
        /// <summary>
        /// It generates add member using REST service where expiration date is equal to system date
        /// </summary>
        /// </summary>
        /// <returns>Date</returns>
        public Memberm GenerateAddMemberForRESTWhereExpirationDateEqualsToSysDate()
        {
            Memberm member = new Memberm();

            member.firstName = "REST1_" + RandomString(9) + "_" + NameGenerator.GenerateFirstName(Gender.Male);
            member.lastName  = "REST1_" + RandomString(9) + "_" + NameGenerator.GenerateFirstName(Gender.Male);
            member.Username  = member.firstName;
            member.Password  = "******";
            member.email     = member.firstName + "@test.com";
            member.cards     = new List <card>();
            Logger.Info(member.firstName);
            card vc = new card();

            vc.cardNumber     = new System.Random().Next(1, 99999999).ToString();
            vc.dateIssued     = string.Format("{0:s}", DateTime.Now.AddDays(-10));
            vc.dateRegistered = vc.dateIssued;
            vc.expirationDate = string.Format("{0:s}", DateTime.Now.AddSeconds(10));
            member.cards.Add(vc);
            return(member);
        }
        public Task <SyntaxList <MemberDeclarationSyntax> > GenerateAsync(TransformationContext context, IProgress <Diagnostic> progress, CancellationToken cancellationToken)
        {
            var results = SyntaxFactory.List <MemberDeclarationSyntax>();

            MemberDeclarationSyntax copy = null;
            var applyToClass             = context.ProcessingNode as MethodDeclarationSyntax;

            if (applyToClass != null)
            {
                copy = applyToClass
                       .WithIdentifier(SyntaxFactory.Identifier(NameGenerator.Combine(applyToClass.Identifier.ValueText, this.suffix)));
            }

            if (copy != null)
            {
                results = results.Add(copy);
            }

            return(Task.FromResult(results));
        }
Exemplo n.º 22
0
        public List <User> GenerateUsers()
        {
            List <User> users = new List <User>();

            for (int i = 0; i < Rnd.Next(1, 10); i++)
            {
                User user = new User
                {
                    Login    = NameGenerator.GenerateLastName().ToLower(),
                    Password = "******",
                    //Project = projects[Rnd.Next(0, projects.Count)]
                };
                users.Add(user);
            }
            List <Admin> admins = new List <Admin>();

            for (int i = 0; i < Rnd.Next(1, 10); i++)
            {
                Admin admin = new Admin
                {
                    Login    = NameGenerator.GenerateLastName().ToLower(),
                    Password = "******"
                };
                admins.Add(admin);
            }
            XmlSerializer xmlUser = new XmlSerializer(typeof(List <User>));

            using (FileStream fs = new FileStream("Users.xml", FileMode.OpenOrCreate))
            {
                xmlUser.Serialize(fs, users);
            }

            XmlSerializer xmlAdmin = new XmlSerializer(typeof(List <Admin>));

            using (FileStream fs = new FileStream("Admins.xml", FileMode.OpenOrCreate))
            {
                xmlAdmin.Serialize(fs, admins);
            }

            return(users);
        }
        public static bool Prefix(FactionDef facDef, ref Faction __result)
        {
            if (Controller.Settings.usingFactionControl.Equals(true))
            {
                return(true);
            }
            Faction faction = new Faction();

            faction.def               = facDef;
            faction.loadID            = Find.UniqueIDsManager.GetNextFactionID();
            faction.colorFromSpectrum = FactionGenerator.NewRandomColorFromSpectrum(faction);
            if (!facDef.isPlayer)
            {
                if (facDef.fixedName == null)
                {
                    faction.Name = NameGenerator.GenerateName(facDef.factionNameMaker,
                                                              from fac in Find.FactionManager.AllFactionsVisible
                                                              select fac.Name, false, null);
                }
                else
                {
                    faction.Name = facDef.fixedName;
                }
            }
            faction.centralMelanin = Rand.Value;
            foreach (Faction allFactionsListForReading in Find.FactionManager.AllFactionsListForReading)
            {
                faction.TryMakeInitialRelationsWith(allFactionsListForReading);
            }
            faction.GenerateNewLeader();
            if (!facDef.hidden && !facDef.isPlayer)
            {
                Settlement settlement = (Settlement)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Settlement);
                settlement.SetFaction(faction);
                settlement.Tile = TileFinder.RandomSettlementTileFor(faction, false, null);
                settlement.Name = SettlementNameGenerator.GenerateSettlementName(settlement, null);
                Find.WorldObjects.Add(settlement);
            }
            __result = faction;
            return(false);
        }
Exemplo n.º 24
0
        private static async Task RenameFieldAccordingToPropertyNameAsync(
            RefactoringContext context,
            IdentifierNameSyntax identifierName)
        {
            if (!IsQualified(identifierName) ||
                IsQualifiedWithThis(identifierName))
            {
                PropertyDeclarationSyntax propertyDeclaration = identifierName.FirstAncestor <PropertyDeclarationSyntax>();

                if (propertyDeclaration != null)
                {
                    SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                    var fieldSymbol = semanticModel.GetSymbol(identifierName, context.CancellationToken) as IFieldSymbol;

                    if (fieldSymbol?.IsPrivate() == true)
                    {
                        IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, context.CancellationToken);

                        if (propertySymbol != null &&
                            fieldSymbol.IsStatic == propertySymbol.IsStatic &&
                            fieldSymbol.ContainingType == propertySymbol.ContainingType)
                        {
                            string newName = StringUtility.ToCamelCase(propertySymbol.Name, context.Settings.PrefixFieldIdentifierWithUnderscore);

                            if (!string.Equals(fieldSymbol.Name, newName, StringComparison.Ordinal) &&
                                await NameGenerator.IsUniqueMemberNameAsync(
                                    newName,
                                    fieldSymbol,
                                    context.Solution,
                                    cancellationToken: context.CancellationToken).ConfigureAwait(false))
                            {
                                context.RegisterRefactoring(
                                    $"Rename '{fieldSymbol.Name}' to '{newName}'",
                                    cancellationToken => Renamer.RenameSymbolAsync(context.Solution, fieldSymbol, newName, default(OptionSet), cancellationToken));
                            }
                        }
                    }
                }
            }
        }
        public async Task <bool> EditProfile(string username, EditProfileViewModel model)
        {
            User user = await _db.Users.FirstAsync(user => user.Username == username);

            //if(await EmailExists(model.Email.FixEmail()))
            //{
            //    return false;
            //}
            var imagepath = "";

            if (model.UserAvatar != null)
            {
                if (user.UserImage != "Default.jpg")
                {
                    imagepath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/UserImages", user.UserImage);
                    if (File.Exists(imagepath))
                    {
                        File.Delete(imagepath);
                    }
                }

                model.UserImage = NameGenerator.GenerateUniqueString() + Path.GetExtension(model.UserAvatar.FileName);
                imagepath       = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/UserImages", model.UserImage);
                try
                {
                    using (var stream = new FileStream(imagepath, FileMode.Create))
                    {
                        await model.UserAvatar.CopyToAsync(stream);
                    }
                }
                catch (Exception ex)
                {
                }
            }

            user.Email     = model.Email.FixEmail();
            user.Name      = model.Name.FixUsername();
            user.Family    = model.Family.FixUsername();
            user.UserImage = model.UserImage;
            return(await Save());
        }
        public string GetMonoSignature()
        {
            var mono = new StringBuilder(Constructor.Name);

            mono.Append('(');

            var end = FirstDefaultParameter == -1 ? Parameters.Length : FirstDefaultParameter;

            for (int n = 0; n < end; ++n)
            {
                if (n > 0)
                {
                    mono.Append(',');
                }
                mono.Append(NameGenerator.GetMonoName(Parameters[n].ParameterType));
            }

            mono.Append(')');

            return(mono.ToString());
        }
Exemplo n.º 27
0
    public void Awake()
    {
        SimpleSpawner spawner     = new SimpleSpawner();
        IGridBuilder  gridBuilder = new GridBuilder();

        Vector3[,,] positions = gridBuilder
                                .SetElementSize(elementPrefab.transform.localScale)
                                .SetGridData(gridData)
                                .BuildGrid();

        INameGenerator nameGenerator = new NameGenerator()
                                       .SetBaseName("tile")
                                       .SetIndex(100)
                                       .SetNameSort(NamingSort.DECREMENTAL);

        spawner
        .SetElement(elementPrefab)
        .SetNaming(nameGenerator)
        .SetParent(gameObject.transform)
        .SpawnElements <GameObject>(positions);
    }
        public override bool TryExecute(IncidentParms parms)
        {
            IntVec3 intVec = DropCellFinder.RandomDropSpot();

            Find.LetterStack.ReceiveLetter("LetterLabelRefugeePodCrash".Translate(), "RefugeePodCrash".Translate(),
                                           LetterType.BadNonUrgent, intVec);
            Faction faction = Find.FactionManager.FirstFactionOfDef(FactionDefOf.Spacer);
            Pawn    pawn    = PawnGenerator.GeneratePawn(Verse.PawnKindDef.Named("MechanoidCovert"), faction);

            pawn.gender = Gender.Female;
            FixBackstory(pawn);
            FixHair(pawn);

            pawn.Name = NameGenerator.GenerateName(pawn);
            HealthUtility.GiveInjuriesToForceDowned(pawn);
            DropPodUtility.MakeDropPodAt(intVec,
                                         new DropPodInfo {
                SingleContainedThing = pawn, openDelay = 180, leaveSlag = true
            });
            return(true);
        }
        protected static SyntaxToken GenerateUniqueLocalName(
            SemanticDocument document,
            TExpressionSyntax expression,
            bool isConstant,
            SyntaxNode container,
            CancellationToken cancellationToken)
        {
            var syntaxFacts   = document.Document.GetLanguageService <ISyntaxFactsService>();
            var semanticFacts = document.Document.GetLanguageService <ISemanticFactsService>();

            var semanticModel   = document.SemanticModel;
            var existingSymbols = GetExistingSymbols(semanticModel, container, cancellationToken);

            var baseName      = semanticFacts.GenerateNameForExpression(semanticModel, expression, capitalize: isConstant);
            var reservedNames = semanticModel.LookupSymbols(expression.SpanStart)
                                .Select(s => s.Name)
                                .Concat(existingSymbols.Select(s => s.Name));

            return(syntaxFacts.ToIdentifierToken(
                       NameGenerator.EnsureUniqueness(baseName, reservedNames, syntaxFacts.IsCaseSensitive)));
        }
Exemplo n.º 30
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

                var userAddress = new AddAddressRequest
                {
                    StudentId   = Guid.NewGuid().ToString(), /* To Be replaced with Students's Id*/
                    Name        = NameGenerator.GenerateName(12),
                    FullAddress = AddressGenerator.GenerateAddress(),
                    Enrollment  = Constants.AddressConstants.EnrollmentTypes[RandomNumberGenerator.GetRandomValue(1, 4)]
                };

                var newAddress = await _client.AddAddressAsync(userAddress);

                Console.WriteLine($"Address Data with Id: {newAddress.Id}");

                await Task.Delay(_config.GetValue <int>("RPCService:DelayInterval"), stoppingToken);
            }
        }
Exemplo n.º 31
0
        private void CodegenAnd(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            var tmpResult = NameGenerator.NewTemp();

            sb.LineDecl(SourceInfo);
            sb.AppendLine(string.Format("int {0} = 0;", tmpResult));
            var true_     = new CILInteger(SourceInfo, 1);
            var false_    = new CILInteger(SourceInfo, 0);
            var lhsBranch = new CILBranch(SourceInfo, Lhs);

            lhsBranch.AddTrueBranchStmt(new CILAssignment(SourceInfo, new CILIdent(SourceInfo, tmpResult), true_));
            lhsBranch.AddFalseBranchStmt(new CILAssignment(SourceInfo, new CILIdent(SourceInfo, tmpResult), false_));
            var rhsBranch = new CILBranch(SourceInfo, Rhs);

            rhsBranch.AddTrueBranchStmt(new CILAssignment(SourceInfo, new CILIdent(SourceInfo, tmpResult), true_));
            rhsBranch.AddFalseBranchStmt(new CILAssignment(SourceInfo, new CILIdent(SourceInfo, tmpResult), false_));
            lhsBranch.AddTrueBranchStmt(rhsBranch);
            lhsBranch.Codegen(cil, sb);

            cil.LastUsedVar = tmpResult;
        }
Exemplo n.º 32
0
        public string GetClrNamespace(string xmlNamespace)
        {
            string str;
            string clrNamespace = string.Empty;

            if (xmlNamespace == null)
            {
                str = clrNamespace;
            }
            else if (!this.namespaceMapping.TryGetValue(xmlNamespace, out clrNamespace))
            {
                clrNamespace = NameGenerator.MakeValidCLRNamespace(xmlNamespace, this.NameMangler2);
                this.namespaceMapping.Add(xmlNamespace, clrNamespace);
                str = clrNamespace;
            }
            else
            {
                str = clrNamespace;
            }
            return(str);
        }
Exemplo n.º 33
0
 // Use this for initialization
 public void Start()
 {
     SetRole (defaultRole);
     nameGenerator = new NameGenerator ();
     staffName = Helper.GenerateName (male, Random.Range (2,3));
     TakeOwnership ();
     myPath = GetComponent<AIPath>();
     myWaypoint = GetComponentInChildren<StaffWaypoint>();
 }
Exemplo n.º 34
0
 public static string GenerateName(bool gender, int length)
 {
     nameGen = new NameGenerator();
     return nameGen.CreateName(gender, length);
 }
Exemplo n.º 35
0
 // Use this for initialization
 public static string GenerateConditionName()
 {
     nameGen = new NameGenerator();
     return nameGen.CreateCondition();
 }
Exemplo n.º 36
0
 static void Awake()
 {
     nameGen = new NameGenerator();
 }
Exemplo n.º 37
0
 /// <summary>
 /// Reset sets the counter to zero and sets the name to a new name
 /// </summary>
 /// <param name="nameBase"></param>
 public static void Reset(string baseName) { m_nameGenerator = new NameGenerator(baseName); }
Exemplo n.º 38
0
		public Terrain( SceneManager sm )
			: base()
		{
			SceneManager = sm;
			ResourceGroup = string.Empty;

			this.mRootNode = sm.RootSceneNode.CreateChildSceneNode();
			SceneManager.PreFindVisibleObjects += new FindVisibleObjectsEvent( _preFindVisibleObjects );
			SceneManager.SceneManagerDestroyed += new SceneManagerDestroyedEvent( _sceneManagerDestroyed );
			msBlendTextureGenerator = new NameGenerator<Texture>( "TerrBlend" );

			var wq = Root.Instance.WorkQueue;
			this.workQueueChannel = wq.GetChannel( "AxiomTerrain" );
			wq.AddRequestHandler( this.workQueueChannel, this );
			wq.AddResponseHandler( this.workQueueChannel, this );

			// generate a material name, it's important for the terrain material
			// name to be consistent & unique no matter what generator is being used
			// so use our own pointer as identifier, use FashHash rather than just casting
			// the pointer to a long so we support 64-bit pointers
			this.mMaterialName = "AxiomTerrain/" + GetHashCode();
		}
Exemplo n.º 39
0
 /// <summary>
 /// Default Constructor.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="manager"></param>
 public PageWorld(string name, PageManager manager)
 {
     mName = name;
     mManger = manager;
     mSectionNameGenerator = new NameGenerator<PagedWorldSection>("Section");
 }
Exemplo n.º 40
0
				/// <summary>
				/// Helper for ResolveRecognizedPhrases. Returns true is parent processing is complete.
				/// </summary>
				private bool TestResolvePhraseDataForCollection(RecognizedPhraseData phraseData, ref NamePart singleName, ref List<NamePart> nameCollection, int collectionIndex, NameGenerator generator)
				{
					Debug.Assert(nameCollection != null);
					string[] matchNames = phraseData.OriginalNames;
					int matchLength = matchNames.Length;
					int i = 0;
					int firstExplicitPart = -1;
					int explicitPartCount = 0;
					for (; i < matchLength; ++i) // Note the bound on this is already verified by RecognizedPhraseData.Populate
					{
						NamePart testPart = nameCollection[collectionIndex + i];
						bool currentPartExplicit = 0 != (testPart.Options & NamePartOptions.ExplicitCasing);
						if (0 != string.Compare(testPart, matchNames[i], currentPartExplicit ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase) ||
							(matchLength == 1 && 0 != (testPart.Options & NamePartOptions.ReplacementOfSelf)))
						{
							break;
						}
						if (currentPartExplicit && firstExplicitPart == -1)
						{
							++explicitPartCount;
							firstExplicitPart = i;
						}
					}
					if (i == matchLength)
					{
						// We have a valid replacement, apply it and recurse
						string[] explicitlyCasedNames = null;
						string singleMatchName = (matchLength == 1) ? matchNames[0] : null;
						if (explicitPartCount != 0)
						{
							explicitlyCasedNames = new string[explicitPartCount];
							int nextExplicitName = 0;
							for (int j = collectionIndex + firstExplicitPart; ; ++j)
							{
								NamePart testPart = nameCollection[j];
								if (0 != (testPart.Options & NamePartOptions.ExplicitCasing))
								{
									explicitlyCasedNames[nextExplicitName] = testPart;
									if (++nextExplicitName == explicitPartCount)
									{
										break;
									}
								}
							}
							if (explicitPartCount > 1)
							{
								Array.Sort<string>(explicitlyCasedNames, StringComparer.CurrentCulture);
							}
						}
						nameCollection.RemoveRange(collectionIndex, matchLength);
						int startingCollectionSize = nameCollection.Count;
						string[] replacements = phraseData.ReplacementNames;
						for (i = 0; i < replacements.Length; ++i)
						{
							// Recognized phrases do not record casing priority and phrases are
							// generally treated as case insensitive. However, if any replacement
							// word exactly matches an explicitly cased word in the original names
							// then case the replacement as well.
							NamePartOptions options = NamePartOptions.None;
							string replacement = replacements[i];
							if (explicitlyCasedNames != null && 0 <= Array.BinarySearch<string>(explicitlyCasedNames, replacement, StringComparer.CurrentCulture))
							{
								options |= NamePartOptions.ExplicitCasing;
								if (matchLength == 1)
								{
									options |= NamePartOptions.ReplacementOfSelf;
								}
							}
							else if (singleMatchName != null && 0 == string.Compare(singleMatchName, replacement, StringComparison.CurrentCultureIgnoreCase))
							{
								options |= NamePartOptions.ExplicitCasing;
							}
							AddToNameCollection(ref singleName, ref nameCollection, new NamePart(replacement, options), collectionIndex + nameCollection.Count - startingCollectionSize, true);
						}
						ResolveRecognizedPhrases(ref singleName, ref nameCollection, generator);
						return true;
					}
					return false;
				}
Exemplo n.º 41
0
				private void ResolveRecognizedPhrases(ref NamePart singleName, ref List<NamePart> nameCollection, NameGenerator generator)
				{
					ORMModel model = ContextModel;
					if (model != null)
					{
						if (nameCollection != null)
						{
							int nameCount = nameCollection.Count;
							int remainingParts = nameCount;
							for (int i = 0; i < nameCount; ++i, --remainingParts)
							{
								// For each part, collection possible replacement phrases beginning with that name
								NamePart currentPart = nameCollection[i];
								RecognizedPhraseData singlePhrase = new RecognizedPhraseData();
								List<RecognizedPhraseData> phraseList = null;
								bool possibleReplacement = false;
								foreach (NameAlias alias in model.GetRecognizedPhrasesStartingWith(currentPart, generator))
								{
									RecognizedPhraseData phraseData;
									if (RecognizedPhraseData.Populate(alias, remainingParts, out phraseData))
									{
										if (phraseList == null)
										{
											possibleReplacement = true;
											if (singlePhrase.IsEmpty)
											{
												singlePhrase = phraseData;
											}
											else
											{
												phraseList = new List<RecognizedPhraseData>();
												phraseList.Add(singlePhrase);
												phraseList.Add(phraseData);
												singlePhrase = new RecognizedPhraseData();
											}
										}
										else
										{
											phraseList.Add(phraseData);
										}
									}
								}
								// If we have possible replacements, then look farther to see
								// if the multi-part phrases match. Start by searching the longest
								// match possible.
								if (possibleReplacement)
								{
									if (phraseList != null)
									{
										phraseList.Sort(delegate(RecognizedPhraseData left, RecognizedPhraseData right)
										{
											return right.OriginalNames.Length.CompareTo(left.OriginalNames.Length);
										});
										int phraseCount = phraseList.Count;
										for (int j = 0; j < phraseCount; ++j)
										{
											if (TestResolvePhraseDataForCollection(phraseList[j], ref singleName, ref nameCollection, i, generator))
											{
												return;
											}
										}
									}
									else
									{
										if (TestResolvePhraseDataForCollection(singlePhrase, ref singleName, ref nameCollection, i, generator))
										{
											return;
										}
									}
								}
							}
						}
						else if (!singleName.IsEmpty)
						{
							LocatedElement element = model.RecognizedPhrasesDictionary.GetElement(singleName);
							RecognizedPhrase phrase;
							NameAlias alias;
							if (null != (phrase = element.SingleElement as RecognizedPhrase) &&
								null != (alias = generator.FindMatchingAlias(phrase.AbbreviationCollection)))
							{
								RecognizedPhraseData phraseData;
								if (RecognizedPhraseData.Populate(alias, 1, out phraseData))
								{
									string[] replacements = phraseData.ReplacementNames;
									int replacementLength = replacements.Length;
									NamePart startingPart = singleName;
									singleName = new NamePart();
									if (replacementLength == 0)
									{
										// Highly unusual, but possible with collapsing phrases and omitted readings
										singleName = new NamePart();
									}
									else
									{
										string testForEqual = singleName;
										bool caseIfEqual = 0 != (singleName.Options & NamePartOptions.ExplicitCasing);
										singleName = new NamePart();
										if (replacementLength == 1)
										{
											string replacement = replacements[0];
											NamePartOptions options = NamePartOptions.None;
											if ((caseIfEqual && 0 == string.Compare(testForEqual, replacement, StringComparison.CurrentCulture)) ||
												(0 == string.Compare(testForEqual, replacement, StringComparison.CurrentCultureIgnoreCase)))
											{
												// Single replacement for same string
												return;
											}
											AddToNameCollection(ref singleName, ref nameCollection, new NamePart(replacement, options));
										}
										else
										{
											for (int i = 0; i < replacementLength; ++i)
											{
												string replacement = replacements[i];
												NamePartOptions options = NamePartOptions.None;
												if (caseIfEqual && 0 == string.Compare(testForEqual, replacement, StringComparison.CurrentCulture))
												{
													options |= NamePartOptions.ExplicitCasing | NamePartOptions.ReplacementOfSelf;
												}
												else if (0 == string.Compare(testForEqual, replacement, StringComparison.CurrentCultureIgnoreCase))
												{
													options |= NamePartOptions.ReplacementOfSelf;
												}
												AddToNameCollection(ref singleName, ref nameCollection, new NamePart(replacement, options));
											}
										}
										ResolveRecognizedPhrases(ref singleName, ref nameCollection, generator);
									}
									return;
								}
							}
						}
					}
				}
Exemplo n.º 42
0
    // Use this for initialization
    void Start()
    {
        endScreen.gameObject.SetActive (false);

        win = false;
        lose = false;

        folkInitialPartySize = _gameController.folk.Count;

        _nameGenerator = GetComponent<NameGenerator> ();
    }
Exemplo n.º 43
0
        private void Reset()
        {
            _controller = new RuntimeBinderController();
            _semanticChecker = new LangCompiler(_controller, new NameManager());

            BSYMMGR bsymmgr = _semanticChecker.getBSymmgr();
            NameManager nameManager = _semanticChecker.GetNameManager();

            InputFile infile = bsymmgr.GetMiscSymFactory().CreateMDInfile(nameManager.Lookup(""), (mdToken)0);
            infile.SetAssemblyID(bsymmgr.AidAlloc(infile));
            infile.AddToAlias(KAID.kaidThisAssembly);
            infile.AddToAlias(KAID.kaidGlobal);

            _symbolTable = new SymbolTable(
                bsymmgr.GetSymbolTable(),
                bsymmgr.GetSymFactory(),
                nameManager,
                _semanticChecker.GetTypeManager(),
                bsymmgr,
                _semanticChecker,
                infile);
            _semanticChecker.getPredefTypes().Init(_semanticChecker.GetErrorContext(), _symbolTable);
            _semanticChecker.GetTypeManager().InitTypeFactory(_symbolTable);
            SymbolLoader.getPredefinedMembers().RuntimeBinderSymbolTable = _symbolTable;
            SymbolLoader.SetSymbolTable(_symbolTable);

            _exprFactory = new ExprFactory(_semanticChecker.GetSymbolLoader().GetGlobalSymbolContext());
            _outputContext = new OutputContext();
            _nameGenerator = new NameGenerator();
            _bindingContext = BindingContext.CreateInstance(
                _semanticChecker,
                _exprFactory,
                _outputContext,
                _nameGenerator,
                false,
                true,
                false,
                false,
                false,
                false,
                0);
            _binder = new ExpressionBinder(_bindingContext);
        }
Exemplo n.º 44
0
				private string GetFinalName(NamePart singleName, List<NamePart> nameCollection, NameGenerator generator)
				{
					ResolveRecognizedPhrases(ref singleName, ref nameCollection, generator);
					NameGeneratorCasingOption casing = generator.CasingOption;
					string space = GetSpacingReplacement(generator);
					string finalName;
					if (null == nameCollection)
					{
						if (singleName.IsEmpty)
						{
							return "";
						}
						if (casing == NameGeneratorCasingOption.None)
						{
							finalName = singleName;
						}
						else
						{
							finalName = DoFirstWordCasing(singleName, casing, CultureInfo.CurrentCulture.TextInfo);
						}
					}
					else
					{
						TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;

						string name;
						if (casing == NameGeneratorCasingOption.None)
						{
							name = nameCollection[0];
						}
						else
						{
							name = DoFirstWordCasing(nameCollection[0], casing, textInfo);
						}

						//we already know there are at least two name entries, so use a string builder
						StringBuilder builder = new StringBuilder(name);

						//we already have the first entry, so mark camel as pascal
						NameGeneratorCasingOption tempCasing = casing;
						if (tempCasing == NameGeneratorCasingOption.Camel)
						{
							tempCasing = NameGeneratorCasingOption.Pascal;
						}

						//add each entry with proper spaces and casing
						int count = nameCollection.Count;
						for (int i = 1; i < count; ++i)
						{
							builder.Append(space);
							if (casing == NameGeneratorCasingOption.None)
							{
								name = nameCollection[i];
							}
							else
							{
								name = DoFirstWordCasing(nameCollection[i], tempCasing, textInfo);
							}
							builder.Append(name);
						}
						finalName = builder.ToString();
					}

					return finalName;
				}
Exemplo n.º 45
0
    void Start()
    {
        Instance = this;

        english_ports = File.ReadAllLines("Assets/Text/EnglishPorts.txt");
        spanish_ports = File.ReadAllLines("Assets/Text/SpanishPorts.txt");
        dutch_ports = File.ReadAllLines("Assets/Text/DutchPorts.txt");
        french_ports = File.ReadAllLines("Assets/Text/FrenchPorts.txt");

        ship_name_adjectives = File.ReadAllLines("Assets/Text/ShipNameAdjectives.txt");
        ship_name_nouns = File.ReadAllLines("Assets/Text/ShipNameNouns.txt");
    }
Exemplo n.º 46
0
		public PagedWorld( string name, PageManager manager )
			: base()
		{
			this.mName = name;
			this.mManager = manager;
			this.mSectionNameGenerator = new NameGenerator<PagedWorldSection>( "Section" );
		}
Exemplo n.º 47
0
				private static string GetSpacingReplacement(NameGenerator generator)
				{
					string retVal;
					switch (generator.SpacingFormat)
					{
						case NameGeneratorSpacingFormat.ReplaceWith:
							retVal = generator.SpacingReplacement;
							break;
						case NameGeneratorSpacingFormat.Retain:
							retVal = " ";
							break;
						// case NameGeneratorSpacingFormat.Remove:
						default:
							retVal = "";
							break;
					}
					return retVal;
				}
Exemplo n.º 48
0
    /*** Public ***/
    // Standard constructor: needs to have a paried config file name
    // which should implement all of the groups and key-value pairs
    // found in the ship demo config file
    public BaseShip(String ConfigFileName)
    {
        // Load the ship's properties
        this.ConfigFileName = ConfigFileName;
        ConfigFile Info = new ConfigFile(ConfigFileName);

        /*** General Init. ***/

        // Save the health components
        ShieldHealth = ShieldMaxHealth = Info.GetKey_Int("General", "Shield");
        HullHealth = HullMaxHealth = Info.GetKey_Int("General", "Hull");

        // Save velicity limit and default pos to center
        MaxVelocity = Info.GetKey_Vector2("General", "MaxVelocity");
        ShipAcceleration = new Vector2();
        ShipVelocity = new Vector2();
        ShipPosition = new Vector3();

        // Get all group names to load up specialty geometry
        String TextureName = Info.GetKey_String("General", "Texture");
        String[] GroupNames = Info.GetGroupNames();

        /*** Frame, Shield & Hull ***/

        // For each group, look just for "Frame" and "Shield"
        foreach(String GroupName in GroupNames)
        {
            // If shield
            if(GroupName.ToLower().StartsWith("shield") == true)
            {
                // Get animation / frame info
                ShieldAnimation = LoadHullType(Info, GroupName);

                // Register the sprite with the sprite manager
                ShieldSprite = new Sprite("Textures/" + TextureName);
                ShieldSprite.SetAnimation(ShieldAnimation.Pos, ShieldAnimation.Size, ShieldAnimation.FrameCount, ShieldAnimation.FrameTime);
                ShieldSprite.SetGeometrySize(ShieldSprite.GetSpriteSize());
                ShieldSprite.SetRotationCenter(ShieldSprite.GetGeometrySize() / 2.0f);
                ShieldSprite.SetDepth(Globals.ShieldDepth);
                Globals.WorldView.SManager.AddSprite(ShieldSprite);
            }
            // Elif base frame
            else if(GroupName.ToLower().StartsWith("frame") == true)
            {
                // Get animation / frame info
                FrameAnimation = LoadHullType(Info, GroupName);

                // Register the sprite with the sprite manager
                FrameSprite = new Sprite("Textures/" + TextureName);
                FrameSprite.SetAnimation(FrameAnimation.Pos, FrameAnimation.Size, FrameAnimation.FrameCount, FrameAnimation.FrameTime);
                FrameSprite.SetGeometrySize(FrameSprite.GetSpriteSize());
                FrameSprite.SetRotationCenter(FrameSprite.GetGeometrySize() / 2.0f);
                FrameSprite.SetDepth(Globals.FrameDepth);
                Globals.WorldView.SManager.AddSprite(FrameSprite);
            }
        }

        // Load all the hulls
        HullList = new List<BaseShip_Hull>();
        foreach(String GroupName in GroupNames)
        {
            if(GroupName.ToLower().StartsWith("hull") == true)
            {
                BaseShip_Hull Hull = LoadHullType(Info, GroupName);
                HullList.Add(Hull);
            }
        }

        // Default to initial hull
        HullSprite = new Sprite("Textures/" + TextureName);
        HullSkinIndex = 0; // Index grows while health goes down
        BaseShip_Hull HullAnimation = HullList[HullSkinIndex];

        HullSprite.SetAnimation(HullAnimation.Pos, HullAnimation.Size, HullAnimation.FrameCount, HullAnimation.FrameTime);
        HullSprite.SetGeometrySize(HullSprite.GetSpriteSize());
        HullSprite.SetRotationCenter(HullSprite.GetGeometrySize() / 2.0f);
        HullSprite.SetDepth(Globals.HullDepth);
        Globals.WorldView.SManager.AddSprite(HullSprite);

        /*** Contrails ***/

        // Load all contrails
        ContrailList = new List<BaseShip_Contrail>();
        foreach(String GroupName in GroupNames)
        {
            BaseShip_Contrail NewContrail = LoadContrail(Info, GroupName);
            if(NewContrail != null)
                ContrailList.Add(NewContrail);
        }

        /*** Weapons ***/

        // Load all weapons
        WeaponsList = new List<BaseShip_Weapon>();
        foreach(String GroupName in GroupNames)
        {
            BaseShip_Weapon NewWeapon = LoadWeapon(Info, GroupName);
            if(NewWeapon != null)
                WeaponsList.Add(NewWeapon);
        }

        /*** Animation Entities ***/

        // Load all animations
        DetailsList = new List<BaseShip_Detail>();
        foreach(String GroupName in GroupNames)
        {
            BaseShip_Detail Detail = LoadDetail(Info, GroupName);
            if(Detail != null)
                DetailsList.Add(Detail);
        }

        /*** Misc. ***/

        // Chunk count
        foreach(String GroupName in GroupNames)
        {
            if(GroupName.ToLower().StartsWith("chunk"))
                ChunkCount++;
        }

        // Generate unique ship name
        NameGenerator NameGen = new NameGenerator();
        ShipName = NameGen.generateName();
    }