Пример #1
0
	void drawTownIcons(Town town, int townIndex) {
		GameObject townInstance = Instantiate (getTownPrefab(town));
		townInstance.transform.SetParent (this.transform);
		townInstance.transform.position = town._position;
		townInstance.GetComponent<TownController>().setTownIndex(townIndex);
		_townPrefabInstances.Add(townInstance);
	}
 private static void CreateNewTown()
 {
     var context = new SoftUniEntities();
     var town = new Town { Name = "New Town" };
     context.Towns.Add(town);
     context.SaveChanges();
 }
Пример #3
0
 public void OnTownBuild(Town sender)
 {
     _buildedTowns.Add(sender.gameObject);
     sender.OnActivate += new Town.OnActivateContainer(OnTownActivate);
     var cardsTypes = new Dictionary<ResourceType, int>();
     switch (sender.Type) {
         case TownType.Village:
         cardsTypes.Add(ResourceType.Brick,1);
         cardsTypes.Add(ResourceType.Hay,1);
         cardsTypes.Add(ResourceType.Wood,1);
         cardsTypes.Add(ResourceType.Wool,1);
         break;
         case TownType.Town:
         cardsTypes.Add(ResourceType.Hay,2);
         cardsTypes.Add(ResourceType.Stone,3);
         break;
     }
     Debug.Log(cardsTypes.ToString());
     var cards = playerDeck.GetComponent<PlayerDeck>().GetCards(cardsTypes);
     Debug.Log(cards.Count);
     cards.ForEach(delegate(ResourceCard card) {
         var deck = decksController.GetComponent<DecksController>().GetDeck(card.ResourceType);
         card.ReturnCardToDeck(deck);
     });
 }
Пример #4
0
        //Vk vkapi;
        public MainForm()
        {
            happinessStat = new Statistics();
            BuildingInterfacesConsuming();

            /*Config.Workshops.Add(typeof(Factory));
            Config.Barracks.Add(typeof(Barracks));
            Config.Guilds.Add(typeof(ThievesGuild));
            Config.FoodProductions.Add(typeof(Farm));
            Config.Marketplaces.Add(typeof(Market));
            Config.Entertainments.Add(typeof(Tavern));
            Config.Residences.Add(typeof(House));*/

            InitializeComponent();
            DoubleBuffered = true;

            WindowState = FormWindowState.Normal;
            FormBorderStyle = FormBorderStyle.None;
            Bounds = Screen.PrimaryScreen.Bounds;

            town = new Town();

            //Forms
            settingsForm = new SettingsForm();

            //Timer
            animationTimer = new System.Windows.Forms.Timer();
            animationTimer.Interval = 1000 / Config.FPS;
            animationTimer.Enabled = true;
            animationTimer.Tick += AnimationTimer_Tick;
            lastTime = DateTime.Now.Ticks;
        }
Пример #5
0
    void Start()
    {
        gameObject.layer = LayerMask.NameToLayer("Building");

        if(currentTown == null)
            currentTown = FindObjectOfType<Town>();
    }
Пример #6
0
        public frmFort()
        {
            InitializeComponent();

            _town = new Town();
            _armyPurKIds = new Hashtable();
        }
Пример #7
0
	public void setIsNeutral(Town town) {
		_isNeutral = false;

		if(town._controlledBy == ControlledBy.Neutral) {
			_isNeutral = true;
		}
	}
Пример #8
0
 public void SetEvent(int index, World world, Town town)
 {
     eventIndex = index;
     this.world = world;
     this.town = town;
     town.ShowMessage(this);
     newsfeed.PushEvent(this);
 }
Пример #9
0
 void Seek(Town LocTown)
 {
     diff = Person.transform.position - LocTown.Location;
             if (-10 > diff.x || diff.x > 10&&
                 -10 > diff.y || diff.y > 10&&
                 -10 > diff.z || diff.z > 10) {
                     Person.transform.position -= diff.normalized;
             }
 }
Пример #10
0
    void Start()
    {
        currentTown = GameObject.FindObjectOfType<Town>();

        if(transferLocation == null)
        {
            Debug.Log("Missing transfer location on Town Portal");
        }
    }
Пример #11
0
 public World GetWorld(Town town)
 {
     for(int i = 0;i<worlds.Length;i++)
     {
         if (town.transform.IsChildOf(worlds[i].transform))
             return worlds[i];
     }
     throw new System.ArgumentException();
 }
Пример #12
0
 private void buildTowns()
 {
     Random random = new Random();
     for ( int i = 0; i <= numberOfTowns - 1; i++ )
     {
         PointF position = new PointF( random.Next( 5, this.panel1.Width - 15 ), random.Next( 5, this.panel1.Height - 15 ) );
         Town townToBuild = new Town( position, random.Next( averageProducerCount - averageProducerCount / 3, averageProducerCount + averageProducerCount / 3 ) );
         towns.Add( townToBuild );
     }
 }
Пример #13
0
        public static void Seed()
        {
            var context = new ApplicationDbContext();

            var asia = new Continent()
            {
                Name = "Asia"
            };

            var europe = new Continent()
            {
                Name = "Europe"
            };

            context.Continents.Add(asia);
            context.Continents.Add(europe);
            context.SaveChanges();

            var china = new Country()
            {
                Continent = asia,
                Language = "chinese",
                Name = "China",
                Population = 2123452123
            };

            var romania = new Country()
            {
                Continent = europe,
                Language = "romanian",
                Name = "Romania",
                Population = 1000000
            };

            context.Countries.Add(romania);
            context.Countries.Add(china);

            var buku = new Town()
            {
                Name = "Bukuresht",
                Country = romania
            };

            var pekin = new Town()
            {
                Name = "Pekin",
                Country = china
            };

            context.Towns.Add(buku);
            context.Towns.Add(pekin);
            context.SaveChanges();

        }
Пример #14
0
        public TownENodebStat(Town town, IEnumerable<ENodeb> eNodebs, IRegionRepository regionRepository)
        {
            town.CloneProperties(this);
            TownId = town.Id;

            QueryRegionService service = new ByDistrictQueryRegionService(
                regionRepository.GetAll(), town.CityName, town.DistrictName);
            OptimizeRegion region = service.Query();
            RegionName = (region == null) ? "" : region.Region;
            TotalENodebs = eNodebs.Count(x => x.TownId == TownId);
        }
Пример #15
0
 public SmallHouse(Orientation o, int X, int Z, Town t)
 {
     this._o = o;
     if (o == Orientation.NORTH || 0 == Orientation.SOUTH)
         _fp = new Footprint (8, 6);
     else
         _fp = new Footprint (6, 8);
     this._x = X;
     this._z = Z;
     this._id = _idCount++;
     if (!t.IsIDRegisted (2))
         t.RegisterID (2);
 }
Пример #16
0
    public IEnumerator EnterBuilding(PlayerController player)
    {
        Debug.Log("Entered Building");

        currentTown = FindObjectOfType<Town>();
        currentTown.gameObject.SetActive(false);

        player.TeleportTo(entranceLocation.position);

        //interactionSystem.FindInteractables();

        yield return StartCoroutine(FindObjectOfType<GameCamera>().ScreenFade(CameraFadeType.FadeIn, true));
    }
        public ActionResult Create([DataSourceRequest] DataSourceRequest request, TownViewModel town)
        {
            if (town != null && this.ModelState.IsValid)
            {
                if (string.IsNullOrWhiteSpace(town.Name))
                {
                    this.ModelState.AddModelError("TownName", "The name of the town is required.");
                }

                var newTown = new Town() { Name = town.Name };
                this.towns.Add(newTown);
            }

            return this.Json(new[] { town }.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }
Пример #18
0
	/// <summary>
	/// Starts a new trade route.
	/// </summary>
	
	public TradeRoute StartNewTradeRoute (Town town)
	{
		if (mGO == null)
		{
			mGO = new GameObject("Trade Route Creator");
			mRoute = mGO.AddComponent<TradeRoute>();
			mRoute.texture = pathTexture;
		}
		
		if (town != null)
		{
			mRoute.Connect(town);
		}
		return mRoute;
	}
Пример #19
0
    /// <summary>
    /// Dock the ship at the specified town.
    /// </summary>
    void DockShip(Town town)
    {
        int gold = SellCargo(town);

        if (gold > 0)
        {
            mCurrentRevenue += gold;
            Config.Instance.gold += gold;
            ScrollingCombatText.Print(gameObject, "$" + gold, (gold < prefab.price / 10) ? Color.yellow : Color.green);
        }
        LoadCargo(town);

        mStartTime = Time.time + 2f;
        mLastTown = town;
    }
Пример #20
0
 void Seek(Town LocTown)
 {
     Vectordiff = (gameObject.transform.position - LocTown.Location).magnitude;
     if (-1 > Vectordiff|| Vectordiff > 1) {
         diff = transform.position - LocTown.Location;
         gameObject.transform.position -= diff.normalized;
         //transform.right = -(diff);
         //transform.forward = -(diff);
         transform.up = diff*180;
         //transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(new Vector3(gameObject.transform.rigidbody.velocity.x,0,gameObject.transform.rigidbody.velocity.z)), Time.deltaTime);
         }
     else {
         Destroy (gameObject);
         LocTown.Population++;
     }
 }
Пример #21
0
    /// <summary>
    /// Load the town's exported cargo onto the ship.
    /// </summary>
    void LoadCargo(Town town)
    {
        int available = cargoAllowance;
        int stock = 0;

        // Add up the town's exported stockpiles
        foreach (TradeRoute.Item item in tradeRoute.items)
        {
            if (item.town == town)
            {
                Town.ResourceEntry res = town.resources[item.id];
                int amount = Mathf.RoundToInt(res.warehouse);
                stock += amount;
            }
        }

        // If we can carry something, let's load it onto the ship
        if (stock > 0 && available > 0)
        {
            // We want to evenly load all available goods
            float factor = Mathf.Min((float)available / stock, 1f);

            foreach (TradeRoute.Item item in tradeRoute.items)
            {
                if (item.town == town)
                {
                    Town.ResourceEntry res = town.resources[item.id];
                    int amount = Mathf.Min(available, Mathf.RoundToInt(res.warehouse * factor));

                    if (amount > 0)
                    {
                        CargoEntry ce = new CargoEntry();
                        ce.id = item.id;
                        ce.amount = amount;
                        ce.owner = town;
                        res.warehouse -= amount;
                        available -= amount;
                        cargo.Add(ce);

                        // If we reach the limit, we want to end the loading process
                        if (available == 0) break;
                    }
                }
            }
        }
    }
Пример #22
0
    public void Awake()
    {
        Instance = this;

        DataTableManager = new DataTableManager();
        DataTableManager.LoadTownTable(TestData.TownInfoTable);
        DataTableManager.FleetInfo = TestData.Fleet;
        DataTableManager.LoadCommodityTable(TestData.CommodityTable);
        var save = TestData.Saves;

        EntityList = new List<Entity>();

        //创建城镇
        GameDataManager = new GameObject("GameDataManager").AddComponent<GameDataManager>();
        GameDataManager.TownList = new List<Town>();
        foreach (var townInfo in DataTableManager.TownTable.Values)
        {
            var town = new Town();
            town.Info = townInfo;
            var townSave = save.TownList.Find(x => x.ID == townInfo.ID);
            if (null != townSave)
            {
                town.LoadSave(townSave);
            }
            GameDataManager.TownList.Add(town);
            EntityList.Add(town);
            town.Reset();
        }

        Map.Setup(GameDataManager.TownList);

        //创建舰队
        var fleet = new Fleet();
        fleet.Info = DataTableManager.FleetInfo;
        fleet.Position = new Vector2(0, 0);
        fleet.Actor = Map.transform.Find("Fleet").GetComponent<FleetActor>();
        fleet.Actor.Model = fleet;
        fleet.Reset();
        EntityList.Add(fleet);
        FocusedFleet = fleet;

        WorldTime = 0;
        TickCountDownRemaining = 0;
        //CurrentTownSettleSeconds = -1;
    }
Пример #23
0
        public void Edit_ShouldReturn400BadRequestWhenModelIsNull()
        {
            var context = new RestaurantsContext();
            var newTown = new Town()
            {
                Name = "New town"
            };

            context.Towns.Add(newTown);
            context.SaveChanges();

            var newRestaurant = new Restaurant()
            {
                Name = "New restaurant",
                TownId = newTown.Id
            };

            context.Restaurants.Add(newRestaurant);
            context.SaveChanges();

            var newMeal = new Meal()
            {
                Name = "New meal",
                Price = 4.99M,
                RestaurantId = newRestaurant.Id,
                TypeId = 3
            };

            context.Meals.Add(newMeal);
            context.SaveChanges();

            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("name", "aaaaa")
            });

            var response = httpClient.PutAsync(string.Format("api/meals/{0}", newMeal.Id), content).Result;

            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
        }
Пример #24
0
	GameObject getTownPrefab(Town town) {
		switch (town._elementType) {
			case ElementTypes.Air: 
				return AirTown;
				break;
			case ElementTypes.Earth:
				return EarthTown;
				break;
			case ElementTypes.Electric:
				return DeathTown;
				break;
			case ElementTypes.Fire:
				return FireTown;
				break;
			case ElementTypes.Water:
				return WaterTown;
				break;
			default:
				return FireTown;
				break;
		}
	}
    private static void InsertTownAddressEvent()
    {
        var context = new SoftUniEntities();

        var town = new Town();
        town.Name = "Developer City " + DateTime.Now.Ticks;
        context.Towns.Add(town);

        var addr = new Address();
        addr.AddressText = (DateTime.Now.Ticks % 1000) + ", Developer Rd.";
        addr.Town = town;
        context.Addresses.Add(addr);

        var ev = new Event();
        ev.Address = addr;
        ev.Name = "Party";
        ev.Date = new DateTime(2015, 1, 1);
        context.Events.Add(ev);

        Console.WriteLine("Inserting new town, address and event...");
        context.SaveChanges();
        Console.WriteLine("Done.");
    }
Пример #26
0
        // TODO: problem in adding categories to the town in POST method
        public Town Add(string name, ICollection<string> category)
        {
            var currentCategories = this.categories
                .All()
                .Where(c => category
                    .Any(x => x == c.Name.ToString()))
                    .ToList();

            if (currentCategories == null)
            {
                throw new ArgumentException("Current category cannot be found!");
            }

            var newTown = new Town
            {
                Name = name,
                Categories = currentCategories
            };

            this.towns.Add(newTown);
            this.towns.SaveChanges();

            return newTown;
        }
Пример #27
0
        // ModifyUser <username> <property> <new value>
        // For example:
        // ModifyUser <username> Password <NewPassword>
        // ModifyUser <username> BornTown <newBornTownName>
        // ModifyUser <username> CurrentTown <newCurrentTownName>
        // !!! Cannot change username
        public override string Execute(string[] data, PhotoShareContext context)
        {
            string username         = data[0];
            string property         = data[1];
            string propertyNewValue = data[2];

            User currentUser = context.Users
                               .SingleOrDefault(u => u.Username.Equals(username));

            if (currentUser == null)
            {
                throw new ArgumentException($"User {username} not found!");
            }

            if (!Helpers.IsUserTheCurrentlyLoggedOne(currentUser))
            {
                throw new InvalidOperationException("Invalid credentials!");
            }

            PropertyInfo[] userProperties = currentUser.GetType()
                                            .GetProperties(BindingFlags.Public | BindingFlags.Instance);

            if (!userProperties.Any(p => p.Name.Equals(property, StringComparison.InvariantCultureIgnoreCase)))
            {
                throw new ArgumentException($"Property {property} not supported!");
            }

            switch (property.ToLower())
            {
            case "password":
                if (!propertyNewValue.Any(char.IsLower) || !propertyNewValue.Any(char.IsDigit))
                {
                    throw new ArgumentException($"Value {propertyNewValue} not valid. Password must include a lower letter and a digit.{Environment.NewLine}Invalid Password");
                }

                currentUser.Salt     = PasswordHasher.GenerateSalt();
                currentUser.Password = PasswordHasher.GenerateHash(propertyNewValue + currentUser.Salt);
                break;

            case "borntown":
                Town newBornTown = context.Towns.SingleOrDefault(t => t.Name.Equals(propertyNewValue));

                if (newBornTown == null)
                {
                    throw new ArgumentException($"Value {propertyNewValue} not valid.{Environment.NewLine}Town {propertyNewValue} not found!");
                }

                currentUser.BornTown = newBornTown;
                break;

            case "currenttown":
                Town newCurrentTown = context.Towns.SingleOrDefault(t => t.Name.Equals(propertyNewValue));

                if (newCurrentTown == null)
                {
                    throw new ArgumentException($"Value {propertyNewValue} not valid.{Environment.NewLine}Town {propertyNewValue} not found!");
                }

                currentUser.CurrentTown = newCurrentTown;
                break;

            default:
                return($"Property {property} not supported!");
            }

            context.SaveChanges();

            return($"User {username} {property} is {propertyNewValue}.");
        }
Пример #28
0
 public DrawField(Town town)
 {
     Town = town;
     bmp  = new Bitmap(Town.X, Town.Y);
     g    = Graphics.FromImage(bmp);
 }
Пример #29
0
        public static bool EconomyTweak_h_GetSupplyDemandForCategory(Town town, ItemCategory category, float dailySupply, float dailyDemand, float oldSupply, float oldDemand, ref ValueTuple <float, float> __result)
        {
            float num  = dailySupply;
            float num2 = (float)EconomyTweak_h_globalConstants.EconomyTweak_h_OptimalStockPeriodPrice * dailyDemand;
            float item = oldDemand * MathF.Pow(dailyDemand / oldDemand, 0.2f);
            float num3 = MathF.Pow((num2 + dailyDemand + 1f) / (num + dailyDemand + 1f), EconomyTweak_h_globalConstants.EconomyTweak_h_LongtermPriceMultiplierExpValue);
            bool  flag = oldSupply > 10f;

            if (flag)
            {
                oldSupply = MathF.Clamp(oldDemand / oldSupply, 0.5f, 1.5f);
            }
            float num4 = oldSupply * MathF.Pow(num3 / oldSupply, 0.2f);

            num4     = MathF.Clamp(num4, 0.4f, 10f);
            __result = new ValueTuple <float, float>(num4, item);
            bool flag2 = EconomyTweak_h_globalConstants.EconomyTweak_h_DebugLevel > 0;

            if (flag2)
            {
                using (StreamWriter streamWriter = File.AppendText(EconomyTweak_h_globalConstants.EconomyTweak_h_path + "EconomyTweak_h_log.txt"))
                {
                    streamWriter.WriteLine("EconomyTweak_h_GetSupplyDemandForCategory");
                }
                bool economyTweak_h_DebugDisplay = EconomyTweak_h_globalConstants.EconomyTweak_h_DebugDisplay;
                if (economyTweak_h_DebugDisplay)
                {
                    InformationManager.DisplayMessage(new InformationMessage("EconomyTweak_h_GetSupplyDemandForCategory"));
                }
                bool flag3 = EconomyTweak_h_globalConstants.EconomyTweak_h_DebugLevel > 1;
                if (flag3)
                {
                    using (StreamWriter streamWriter2 = File.AppendText(EconomyTweak_h_globalConstants.EconomyTweak_h_path + "EconomyTweak_h_log.txt"))
                    {
                        streamWriter2.WriteLine(string.Concat(new string[]
                        {
                            "town = ",
                            town.ToString(),
                            ", category = ",
                            category.ToString(),
                            ", dailySupply = ",
                            dailySupply.ToString(),
                            ", dailyDemand = ",
                            dailyDemand.ToString(),
                            ", oldSupply = ",
                            oldSupply.ToString(),
                            ", oldDemand = ",
                            oldDemand.ToString(),
                            ", EconomyTweak_h_LongtermPriceMultiplier = ",
                            num3.ToString(),
                            ", newDemand(item) = ",
                            item.ToString(),
                            ", newSupply(num) = ",
                            num4.ToString(),
                            ", EconomyTweak_h_GetSupplyDemandForCategory(result) = ",
                            __result.ToString()
                        }));
                    }
                }
            }
            return(false);
        }
Пример #30
0
 public void SetTownFrom(Town town_)
 {
     townFrom = town_;
 }
Пример #31
0
    void Start()
    {
        players = new List <Player>();

        Player neutralPlayer = (Player)Instantiate(neutralPrefab);

        players.Add(neutralPlayer);
        humanPlayer = (Player)Instantiate(playerPrefab);
        players.Add(humanPlayer);
        Player aiPlayer = (Player)Instantiate(aiSimplePrefab);

        players.Add(aiPlayer);


        humanPlayer.SetColour(Color.green);
        aiPlayer.SetColour(Color.red);

        neutralPlayer.SetColour(Color.grey);

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(100, 0, 10), Quaternion.identity);
            town.SetPlayer(humanPlayer);
            town.SetTownSize(3);
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(100, 0, 41), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(80, 0, 58), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(65, 0, 118), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(5, 0, 105), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(112, 0, 168), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(160, 0, 168), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(178, 0, 104), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(113, 0, 137), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(146, 0, 136), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(113, 0, 73), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(145, 0, 72), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(240, 0, 73), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(273, 0, 41), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(225, 0, 153), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(272, 0, 200), Quaternion.identity);
            town.SetPlayer(aiPlayer);
            town.SetTownSize(3);
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(273, 0, 152), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(162, 0, 41), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }

        {
            Town town = (Town)Instantiate(townPrefab, new Vector3(193, 0, 71), Quaternion.identity);
            town.SetPlayer(neutralPlayer);
            town.SetTownSize(UnityEngine.Random.Range(1, 5));
        }
    }
Пример #32
0
        public static void ShowBuildMaterialWindow(BaseDataBuildingUnit build, NVector pos, Action <Dictionary <string, int> > perform)
        {
            string need = null;
            Town   town = S.Towns().NearestTown(S.ActPlayer(), pos, false);

            //todo support multiple
            //check if material need to replaced?
            foreach (var c in build.cost)
            {
                var res = L.b.res[c.Key];
                if (!string.IsNullOrEmpty(res.combine))
                {
                    need = res.combine;
                    break;
                }
            }

            //how much exist in this town?
            if (string.IsNullOrEmpty(need))
            {
                //nothing found? Build it directly
                perform.Invoke(new Dictionary <string, int>(build.cost));
                return;
            }

            //how much types is known?
            var found = L.b.res.GetAllByCategory(need).Where(r => town.KnowRes(r.id)).ToList();

            //found nothing?
            if (found.Count == 0)
            {
                UIHelper.ShowOk(S.T("constructionMaterial"), TextHelper.RichText(S.T("constructionMaterialNothing",
                                                                                     town.GetTownLevelName(), town.name), TextHelper.Header("material"), TextHelper.CommaSep(L.b.res.GetAllByCategory(need).Select(r => r.Name()).ToArray())));
                return;
            }

            //found one? Build it directly
            if (found.Count == 1)
            {
                Dictionary <string, int> cost = new Dictionary <string, int>(build.cost);
                cost[found[0].id] = (cost.ContainsKey(found[0].id) ? cost[found[0].id] : 0) + cost[need];
                cost.Remove(need);
                perform.Invoke(cost);
                return;
            }

            WindowBuilderSplit wbs = WindowBuilderSplit.Create(S.T("constructionMaterial"), S.T("constructionMaterialUse"));

            foreach (var res in L.b.res.GetAllByCategory(need))
            {
                //have it?
                if (!town.KnowRes(res.id))
                {
                    continue;
                }

                Dictionary <string, int> cost = new Dictionary <string, int>(build.cost);
                cost[res.id] = (cost.ContainsKey(res.id) ? cost[res.id] : 0) + cost[need];
                cost.Remove(need);

                wbs.Add(new MaterialSplitElement(res, build, pos, cost, perform));
            }

            //add self
            wbs.Add(new MaterialSelfSplitElement(L.b.res[need], build, town, pos, new Dictionary <string, int>(build.cost), perform));
            LSys.tem.helps.AddHelp("material", wbs);
            wbs.Finish();
        }
        public void Invoke_ContextSaveChanges_When_ValidationsPass()
        {
            // Arrange
            var fakeAddressText         = "testAddress";
            var fakeTownName            = "testTown";
            var fakeCourierImportModel  = new Mock <ICourierImportModel>();
            var fakeCourierImportModels = new List <ICourierImportModel>()
            {
                fakeCourierImportModel.Object
            };

            var fakeTown = new Town()
            {
                Name = fakeTownName
            };
            var fakeTowns = new List <Town>()
            {
                fakeTown
            }.GetQueryableMockDbSet();

            var fakeAddress = new Address()
            {
                AddressText = fakeAddressText, Town = fakeTown
            };
            var fakeAddresses = new List <Address>()
            {
                fakeAddress
            }.GetQueryableMockDbSet();

            var fakeCourier  = new Mock <Courier>();
            var fakeCouriers = new List <Courier>()
            {
            }.GetQueryableMockDbSet();

            var mockCtx            = new Mock <IOnlineStoreContext>();
            var townServiceStub    = new Mock <ITownService>();
            var addressServiceStub = new Mock <IAddressService>();
            var mapperStub         = new Mock <IMapper>();

            var courierService = new CourierService(mockCtx.Object, townServiceStub.Object, addressServiceStub.Object, mapperStub.Object);

            fakeCourierImportModel
            .SetupGet(cip => cip.Address)
            .Returns(fakeAddressText);

            fakeCourierImportModel
            .SetupGet(cip => cip.Town)
            .Returns(fakeTownName);

            mapperStub
            .Setup(m => m.Map <ICourierImportModel, Courier>(fakeCourierImportModel.Object))
            .Returns(fakeCourier.Object);

            mockCtx
            .Setup(ctx => ctx.Towns)
            .Returns(fakeTowns.Object);

            mockCtx
            .Setup(ctx => ctx.Addresses)
            .Returns(fakeAddresses.Object);

            mockCtx
            .Setup(ctx => ctx.Couriers)
            .Returns(fakeCouriers.Object);

            // Act
            courierService.AddCourierRange(fakeCourierImportModels);

            // Assert
            mockCtx.Verify(c => c.SaveChanges(), Times.Once);
        }
Пример #34
0
        public IHttpActionResult Post(TownSaveModel model)
        {
            var town = this.data.Towns.All().FirstOrDefault(x => x.Name == model.Name);
            if (town != null)
            {
                var id = town.Id;
                var uri = new Uri($"http://localhost:58368/api/towns/{id}");
                return this.Redirect(uri);
            }

            var townToAdd = new Town
            {
                Name = model.Name
            };

            this.data.Towns.Add(townToAdd);
            this.data.Savechanges();

            return this.Created("api/towns", new
            {
                TownId = townToAdd.Id
            });
        }
Пример #35
0
    /// <summary>
    /// Draws the UI for the current town.
    /// </summary>
    void DrawTownUI()
    {
        Vector2 mousePos = UI.GetMousePos();
        Rect rect = new Rect(Screen.width * 0.5f + 130f, Screen.height * 0.5f - 260f, 292f, 270f);

        // Allow the opposite town's resources to be dragged straight to this window for simplicity's sake
        if (mDragResource != -1 && Input.GetMouseButtonUp(0) && rect.Contains(mousePos))
        {
            if (mDragTown == this) mDragTown = null;
            mSelectedRoute.SetExportedResource(mDragTown, mDragResource);
            CancelDrag();
        }

        // Draw the resources
        Rect inner = UI.DrawWindow(rect, name);
        DrawResources(this, inner);

        inner.y += inner.height - 40f;
        inner.height = 40f;

        if (GUI.Button(inner, "Establish a New Trade Route", Config.Instance.skin.button))
        {
            showInfo = false;
            TradeRouteCreator.Instance.StartNewTradeRoute(this);
        }

        if (mSelectedRoute != null)
        {
            rect = new Rect(rect.x, Screen.height * 0.5f + 40f, 292f, 225f);

            // Allow main town's resources to be dragged straight to this window for simplicity's sake
            if (mDragResource != -1 && Input.GetMouseButtonUp(0) && rect.Contains(mousePos))
            {
                if (mDragTown != this) mDragTown = null;
                mSelectedRoute.SetExportedResource(mDragTown, mDragResource);
                CancelDrag();
            }

            Town town = mSelectedRoute.GetConnectedTown(this);
            inner = UI.DrawWindow(rect, town.name);

            // See if we have more than one trade route
            TradeRoute next = TradeRoute.FindNext(mSelectedRoute, this, true);

            // Draw trade route navigation buttons
            if (next != mSelectedRoute)
            {
                if (GUI.Button(new Rect(rect.x + 20f, rect.y - 18f, 40f, 40f), "<<", Config.Instance.skin.button))
                {
                    mSelectedRoute = next;
                }
                else if (GUI.Button(new Rect(rect.x + rect.width - 60f, rect.y - 18f, 40f, 40f), ">>", Config.Instance.skin.button))
                {
                    mSelectedRoute = TradeRoute.FindNext(mSelectedRoute, this, false);
                }
            }
            DrawResources(town, inner);
        }
    }
Пример #36
0
 public void TurnOn(Town destination)
 {
     this.destination = destination;
     gameObject.SetActive(true);
 }
Пример #37
0
 public override int GetHashCode()
 {
     return(FirstName.GetHashCode() ^
            Town.GetHashCode() ^
            Number.GetHashCode());
 }
Пример #38
0
        public static void CreateTown(TownIDValue town)
        {
            Town townInstance = new Town(town, Map.Felucca);

            townInstance.CreateTown();
        }
        static void Main(string[] args)
        {
            using var db = new StudentDbContext();

            db.Database.Migrate();
            //db.Students.Add(new Student
            //{
            //    FirstName = "Aleksandra",
            //    LastName = "Toncheva",
            //    RegistrationDate = DateTime.UtcNow,
            //    Type = StudentType.Enrolled
            //});

            var town = new Town
            {
                Name = "Pleven"
            };
            //db.Towns.Add(town);
            //town.Students.Add(db.Students.First());


            var course = new Course
            {
                Name        = "ASP.NET",
                Description = "ASP.NET MVC"
            };

            //db.Courses.Add(course);

            var studentId = db.Students.Select(st => st.Id).First();
            var courseId  = db.Courses.Select(c => c.Id).First();

            //db.StudentsCourses.Add(new StudentInCourse
            //{
            //    StudentId = studentId,
            //    CourseId = courseId
            //});



            //db.StudentsCourses.Add(new StudentInCourse
            //{
            //    Student = new Student
            //    {
            //        FirstName = "Georgi",
            //        LastName = "Delchev",
            //        RegistrationDate = DateTime.UtcNow,
            //        Town = new Town
            //        {
            //            Name = "Stara Zagora"
            //        }
            //    },
            //    Course = new Course
            //    {
            //        Name = "C# OOP",
            //        Description = "Interfaces, Delegates"
            //    }
            //});
            //db.SaveChanges();

            //db.Homeworks.Add(new Homework
            //{
            //    Content = "Some content for this course",
            //    Score = 5.50,
            //    StudentId = 1,
            //    CourseId = 2,

            //}) ;

            //CoursesInformation(db); - Exception occured

            db.Students.ToList().ForEach(e => Console.WriteLine($"{e.FirstName} {e.LastName} {e.RegistrationDate} {e.Type} {e.TownId}"));
        }
Пример #40
0
        public static void Main()
        {
            //IO
            IReader reader = new ConsoleReader();
            IWriter writer = new ConsoleWriter(Constants.ConsoleHeight, Constants.ConsoleWidth);

            //player
            IPlayer player = new Player("Pesho")
            {
                Inventory = new List <IItem>
                {
                    new Axe(1, "Cepeni4kata", 99, Rarity.Common),
                    new Hammer(2, "Za dinozavrite", 15, Rarity.Epic),
                    new Sword(3, "Me4a na Ahil", 15, Rarity.Epic),
                    new Booklet(4, "Priklu4eniq", 15, Rarity.Epic),
                    new Sneaker(5, "Adidas", 15, Rarity.Epic),
                    new Sneaker(6, "Nike", 15, Rarity.Epic),
                    new Sneaker(7, "Reebok", 15, Rarity.Epic),
                    new Sneaker(8, "Puma", 15, Rarity.Epic),
                    new Sneaker(9, "Guma", 15, Rarity.Epic)
                }
            };

            //MANAGERS AND UTILITIES
            IRandomNumberGenerator   randomNumberGenerator = new RandomNumberGenerator();
            ICustomEventHandler      handler                 = new CustomEventHandler(writer);
            IPlayerManager           playerManager           = new PlayerManager(player);
            ITownsManager            townsManager            = new TownsManager();
            IRandomEncountersManager randomEncountersManager =
                new RandomEncountersManager(playerManager, reader, writer);
            IPlayerActionFactory playerActionFactory =
                new PlayerActionFactory(townsManager, playerManager, reader, writer);

            //SOFIA
            IMap  sofiaMap = new Map(player, writer);
            ITown sofia    = new Town("Sofia", sofiaMap, writer);

            sofia.AddBuilding(new Banicharnitsa(1, "Banicharnica", "Topli zakuski", 10, 50, playerManager));
            sofia.AddBuilding(new PoliceOffice(townsManager, playerManager, randomNumberGenerator, 1, "Police Station",
                                               "Just a police station", 30, 15, handler));
            IBuilding mall = new MallShop(playerManager, 1, "Mall of Sofia", null, 30, 50)
            {
                Inventory = new List <IItem>
                {
                    new Primer(10, "Primer", 55, Rarity.Epic),
                    new Overshoe(11, "Obushta", 60, Rarity.Epic)
                }
            };

            sofia.AddBuilding(mall);
            foreach (var building in Initializer.InitializeBuildings())
            {
                sofia.AddBuilding(building);
            }
            townsManager.AddTown(sofia);
            townsManager.SetCurrentTown(sofia);

            //MONTANA
            IMap  montanaMap = new Map(player, writer);
            ITown montana    = new Town("Montana", montanaMap, writer);

            montana.AddBuilding(new BasicBuilding(10, 10, 3));
            townsManager.AddTown(montana);

            //ENGINE
            IEngine engine = new Engine(playerManager, townsManager, reader, writer, playerActionFactory,
                                        randomEncountersManager, randomNumberGenerator);

            engine.Run();
        }
        public void Invoke_TownServiceCreate_When_CourierModelTown_DoesNotExists_InDatabase()
        {
            // Arrange
            var fakeAddressText         = "testAddress";
            var fakeTownName            = "testTown";
            var fakeCourierImportModel  = new Mock <ICourierImportModel>();
            var fakeCourierImportModels = new List <ICourierImportModel>()
            {
                fakeCourierImportModel.Object
            };

            var fakeTown = new Town()
            {
                Name = fakeTownName
            };
            var fakeTowns = new List <Town>()
            {
            }.GetQueryableMockDbSet();
            var newFakeTowns = new List <Town>()
            {
                fakeTown
            }.GetQueryableMockDbSet();

            var fakeAddress = new Address()
            {
                AddressText = fakeAddressText, Town = fakeTown
            };
            var fakeAddresses = new List <Address>()
            {
            }.GetQueryableMockDbSet();
            var newfakeAddresses = new List <Address>()
            {
                fakeAddress
            }.GetQueryableMockDbSet();

            var fakeCourier  = new Mock <Courier>();
            var fakeCouriers = new List <Courier>()
            {
            }.GetQueryableMockDbSet();

            var ctxStub            = new Mock <IOnlineStoreContext>();
            var mockTownService    = new Mock <ITownService>();
            var addressServiceStub = new Mock <IAddressService>();
            var mapperStub         = new Mock <IMapper>();

            var courierService = new CourierService(ctxStub.Object, mockTownService.Object, addressServiceStub.Object, mapperStub.Object);

            Action addingTownToTowns =
                () =>
                ctxStub
                .Setup(ctx => ctx.Towns)
                .Returns(newFakeTowns.Object);

            Action addingAddressToAddresses =
                () =>
                ctxStub
                .Setup(ctx => ctx.Addresses)
                .Returns(newfakeAddresses.Object);

            fakeCourierImportModel
            .SetupGet(cip => cip.Address)
            .Returns(fakeAddressText);

            fakeCourierImportModel
            .SetupGet(cip => cip.Town)
            .Returns(fakeTownName);

            mapperStub
            .Setup(m => m.Map <ICourierImportModel, Courier>(fakeCourierImportModel.Object))
            .Returns(fakeCourier.Object);

            ctxStub
            .Setup(ctx => ctx.Towns)
            .Returns(fakeTowns.Object);

            ctxStub
            .Setup(ctx => ctx.Addresses)
            .Returns(fakeAddresses.Object);

            ctxStub
            .Setup(ctx => ctx.Couriers)
            .Returns(fakeCouriers.Object);

            mockTownService
            .Setup(ts => ts.Create(fakeTownName))
            .Callback(addingTownToTowns);

            addressServiceStub
            .Setup(addServ => addServ.Create(fakeAddressText, fakeTownName))
            .Callback(addingAddressToAddresses);

            // Act
            courierService.AddCourierRange(fakeCourierImportModels);

            // Assert
            mockTownService.Verify(ts => ts.Create(fakeTownName), Times.Once);
        }
 public Fight2TournamentGame(Town town) : base(town)
 {
     base.Mode = TournamentGame.QualificationMode.IndividualScore;
 }
Пример #43
0
        protected override void Run(Player player)
        {
            //create it
            WindowPanelBuilder p = WindowPanelBuilder.Create("Debug Window");

            p.panel.AddButton("Give 500 gold", () =>
            {
                Town t = S.Towns().GetByActPlayer().First();

                t.AddRes("gold", 500, ResType.Gift);
            });
            p.panel.AddButton("Trade", () =>
            {
                ActionHolder ah  = new ActionHolder();
                ah.data["trade"] = null;
                LClass.s.GetNewAction("trade").PerformCheck(ActionEvent.Direct, S.ActPlayer(), ah);
            });
            p.panel.AddButton("Give research", () =>
            {
                Town t = S.Towns().GetByActPlayer()[0];

                t.AddRes("research", 100, ResType.Gift);
            });
            p.panel.AddButton("Finish all research", () =>
            {
                foreach (Research r in L.b.researches.Values())
                {
                    S.ActPlayer().research.Set(r.id, true);
                }
            });
            p.panel.AddButton("Unfinish all research", () =>
            {
                foreach (Research r in L.b.researches.Values())
                {
                    S.ActPlayer().research.Set(r.id, false);
                }
            });
            p.panel.AddButton("Switch Fog", () =>
            {
                foreach (TileMapConfig16 t in S.ActPlayer().fog.tileMap)
                {
                    t.gameObject.SetActive(!t.gameObject.activeSelf);
                }
            });
            p.panel.AddButton("Show player features", () =>
            {
                WindowPanelBuilder wp = WindowPanelBuilder.Create("features");
                foreach (var fp in L.b.playerOptions.Values())
                {
                    wp.panel.AddLabel(fp.Name() + ": " + S.ActPlayer().GetFeature(fp.id) + " (" + fp.standard + ")");
                }
                wp.Finish();
            });
            p.panel.AddButton("Show game features", () =>
            {
                WindowPanelBuilder wp = WindowPanelBuilder.Create("features");
                foreach (var fp in L.b.gameOptions.Values())
                {
                    wp.panel.AddLabel(fp.Name() + ": " + fp.Value() + " (" + fp.standard + ")");
                }
                wp.Finish();
            });
            p.panel.AddButton("Reload game library", () =>
            {
                GameMgmt.Get().ReloadGameLib();
                p.Close();
            });
            p.panel.AddButton("Give unit", () =>
            {
                WindowPanelBuilder wp = WindowPanelBuilder.Create("units");
                if (S.Towns().GetByActPlayer().Count > 0 && S.Unit().Free(S.Towns().GetByActPlayer()[0].pos))
                {
                    foreach (var du in L.b.units.Values())
                    {
                        wp.panel.AddImageTextButton(du.Name(), du.Sprite(), (() =>
                        {
                            S.Unit().Create(S.ActPlayerID(), du.id, S.Towns().GetByActPlayer()[0].pos).FinishConstruct();
                            wp.Close();
                            p.Close();
                        }));
                    }
                }
                else
                {
                    wp.panel.AddLabel("Field is blocked");
                }
                wp.Finish();
            });
            p.panel.AddButton("Reset round", () =>
            {
                S.Players().ResetRound();
            });
            p.panel.AddLabel("DPI: " + Screen.dpi);
            p.Finish();
        }
        public void EnterDetails(Table table)
        {
            foreach (var row in table.Rows)
            {
                switch (row[0].ToLower())
                {
                case "approved":
                    var approved = Convert.ToBoolean(row[1]);
                    if ((Approved.Selected && !approved) || (!Approved.Selected && approved))
                    {
                        Approved.Click();
                    }
                    break;

                case "emailverified":
                    var emailVerified = Convert.ToBoolean(row[1]);
                    if ((EmailVerified.Selected && !emailVerified) || (!EmailVerified.Selected && emailVerified))
                    {
                        EmailVerified.Click();
                    }
                    break;

                case "enabled":
                    var enabled = Convert.ToBoolean(row[1]);
                    if ((Enabled.Selected && !enabled) || (!Enabled.Selected && enabled))
                    {
                        Enabled.Click();
                    }
                    break;

                case "firstname":
                    FirstName.Clear();
                    FirstName.SendKeys(row[1]);
                    break;

                case "lastname":
                    LastName.Clear();
                    LastName.SendKeys(row[1]);
                    break;

                case "postcode":
                    PostCode.Clear();
                    PostCode.SendKeys(row[1]);
                    break;

                case "skypename":
                    SkypeName.Clear();
                    SkypeName.SendKeys(row[1]);
                    break;

                case "hometelephonenumber":
                    TelNoHome.Clear();
                    TelNoHome.SendKeys(row[1]);
                    break;

                case "mobiletelephonenumber":
                    TelNoMobile.Clear();
                    TelNoMobile.SendKeys(row[1]);
                    break;

                case "worktelephonenumber":
                    TelNoWork.Clear();
                    TelNoWork.SendKeys(row[1]);
                    break;

                case "title":
                    Title.Clear();
                    Title.SendKeys(row[1]);
                    break;

                case "town":
                    Town.Clear();
                    Town.SendKeys(row[1]);
                    break;

                default:
                    throw new Exception(string.Format("Field {0} not defined", row[0]));
                }
            }
        }
Пример #45
0
 public TownMonolith(Town town) : base(town, null)
 {
 }
Пример #46
0
 public BakerBehavior(Agent agent, Town town, EatBehavior eat) : base(agent)
 {
     this.town = town;
     this.eat  = eat;
 }
Пример #47
0
 public void RegisterTown(Town town_)
 {
     GetPlayerTowns(town_.GetPlayer()).Add(town_);
 }
Пример #48
0
    void DrawGUI()
    {
        if (Event.current.type != EventType.Repaint)
        {
            return;
        }
        if (Config.Instance == null || Camera.main == null || !enabled)
        {
            return;
        }
        if (Config.Instance.townNameFont == null)
        {
            return;
        }

        if (mTown == null)
        {
            mTown = Town.Find(gameObject);

            if (mTown == null)
            {
                Debug.LogError("'TownName' expects 'Town' to exist on the GameObject or one of its parents");
                enabled = false;
                return;
            }
        }

        Vector3 v   = transform.position;
        Vector3 pos = Camera.main.WorldToScreenPoint(v);

        if (pos.z < 0f)
        {
            return;
        }

        float targetAlpha = (pos.x > 0.0f && pos.y > 0.0f && pos.x < Screen.width && pos.y < Screen.height) &&
                            Vector3.Distance(v, Camera.main.transform.position) < 60.0f ? 1.0f : 0.0f;

        mAlpha = Mathf.Lerp(mAlpha, targetAlpha, Time.deltaTime * 10.0f);
        if (mAlpha < 0.001f)
        {
            return;
        }

        if (mStyle == null)
        {
            mStyle           = new GUIStyle();
            mStyle.alignment = TextAnchor.MiddleCenter;
        }

        if (mContent == null)
        {
            mContent = new GUIContent();
        }

        mStyle.font   = Config.Instance.townNameFont;
        mContent.text = mTown.name;

        Vector2 size = mStyle.CalcSize(mContent);

        Rect rect = new Rect(pos.x - size.x * 0.5f - mPaddingX,
                             Screen.height - pos.y - size.y * 0.5f - mPaddingY,
                             size.x + mPaddingX * 2.0f, size.y + mPaddingY * 2.0f);

        if (Config.Instance.townNameBackground != null)
        {
            Color prev = GUI.color;
            GUI.color = new Color(1.0f, 1.0f, 1.0f, mAlpha);
            GUI.DrawTexture(rect, Config.Instance.townNameBackground);
            GUI.color = prev;
        }

        rect.xMin += 1.0f;
        rect.xMax += 1.0f;
        rect.yMin += 1.0f;
        rect.yMax += 1.0f;

        mStyle.normal.textColor = new Color(0.0f, 0.0f, 0.0f, mAlpha);
        GUI.Label(rect, mContent, mStyle);

        rect.xMin -= 1.0f;
        rect.xMax -= 1.0f;
        rect.yMin -= 1.0f;
        rect.yMax -= 1.0f;

        mStyle.normal.textColor = new Color(1.0f, 1.0f, 1.0f, mAlpha);
        GUI.Label(rect, mContent, mStyle);
    }
Пример #49
0
        public void CompleteCraft(int quality, bool makersMark, Mobile from, CraftSystem craftSystem, Type typeRes, BaseTool tool)
        {
            string badCraft = craftSystem.CanCraft(from, tool, m_Type);

            if (badCraft != "")
            {
                if (tool != null && !tool.Deleted && tool.UsesRemaining > 0)
                {
                    from.SendGump(new CraftGump(from, craftSystem, tool, badCraft));
                }
                else
                {
                    from.SendAsciiMessage(badCraft);
                }

                return;
            }

            int    checkResHue = 0, checkMaxAmount = 0;
            object checkMessage = null;

            // Not enough resource to craft it
            if (!ConsumeRes(from, typeRes, craftSystem, ref checkResHue, ref checkMaxAmount, ConsumeType.None, ref checkMessage))
            {
                if (tool != null && !tool.Deleted && tool.UsesRemaining > 0)
                {
                    from.SendGump(new CraftGump(from, craftSystem, tool, checkMessage));
                }
                else if (checkMessage is int && (int)checkMessage > 0)
                {
                    from.SendLocalizedMessage((int)checkMessage);
                }
                else if (checkMessage is string)
                {
                    from.SendAsciiMessage((string)checkMessage);
                }

                return;
            }
            else if (!ConsumeAttributes(from, ref checkMessage, false))
            {
                if (tool != null && !tool.Deleted && tool.UsesRemaining > 0)
                {
                    from.SendGump(new CraftGump(from, craftSystem, tool, checkMessage));
                }
                else if (checkMessage is int && (int)checkMessage > 0)
                {
                    from.SendLocalizedMessage((int)checkMessage);
                }
                else if (checkMessage is string)
                {
                    from.SendAsciiMessage((string)checkMessage);
                }

                return;
            }

            bool toolBroken = false;

            int ignored    = 1;
            int endquality = 1;

            bool allRequiredSkills = true;

            if (CheckSkills(from, typeRes, craftSystem, ref ignored, ref allRequiredSkills))
            {
                // Resource
                int resHue    = 0;
                int maxAmount = 0;

                object message = null;

                // Not enough resource to craft it
                if (!ConsumeRes(from, typeRes, craftSystem, ref resHue, ref maxAmount, ConsumeType.All, ref message))
                {
                    if (tool != null && !tool.Deleted && tool.UsesRemaining > 0)
                    {
                        from.SendGump(new CraftGump(from, craftSystem, tool, message));
                    }
                    else if (message is int && (int)message > 0)
                    {
                        from.SendLocalizedMessage((int)message);
                    }
                    else if (message is string)
                    {
                        from.SendMessage((string)message);
                    }

                    return;
                }
                else if (!ConsumeAttributes(from, ref message, true))
                {
                    if (tool != null && !tool.Deleted && tool.UsesRemaining > 0)
                    {
                        from.SendGump(new CraftGump(from, craftSystem, tool, message));
                    }
                    else if (message is int && (int)message > 0)
                    {
                        from.SendLocalizedMessage((int)message);
                    }
                    else if (message is string)
                    {
                        from.SendMessage((string)message);
                    }

                    return;
                }

                tool.UsesRemaining--;

                if (craftSystem is DefBlacksmithy)
                {
                    AncientSmithyHammer hammer = from.FindItemOnLayer(Layer.OneHanded) as AncientSmithyHammer;
                    if (hammer != null && hammer != tool)
                    {
                        hammer.UsesRemaining--;
                        if (hammer.UsesRemaining < 1)
                        {
                            hammer.Delete();
                        }
                    }
                }

                if (tool.UsesRemaining < 1)
                {
                    toolBroken = true;
                }

                if (toolBroken)
                {
                    tool.Delete();
                }

                Item item;
                if (typeof(MapItem).IsAssignableFrom(ItemType) && from.Map != Map.Trammel && from.Map != Map.Felucca)
                {
                    item = new IndecipherableMap();
                    from.SendAsciiMessage("The map you create becomes mysteriously indecipherable.");
                }
                else
                {
                    item = Activator.CreateInstance(ItemType) as Item;
                }

                if (item != null)
                {
                    if (item is ICraftable)
                    {
                        endquality = ((ICraftable)item).OnCraft(quality, makersMark, from, craftSystem, typeRes, tool, this, resHue);
                    }

                    if (item.Hue == 0)
                    {
                        item.Hue = resHue;
                    }

                    if (maxAmount > 0)
                    {
                        item.Amount = maxAmount;
                    }

                    from.AddToBackpack(item);

                    //from.PlaySound( 0x57 );
                }

                int num = craftSystem.PlayEndingEffect(from, false, true, toolBroken, endquality, makersMark, this);

                bool queryFactionImbue    = false;
                int  availableSilver      = 0;
                FactionItemDefinition def = null;
                Faction faction           = null;

                if (item is IFactionItem)
                {
                    def = FactionItemDefinition.Identify(item);

                    if (def != null)
                    {
                        faction = Faction.Find(from);

                        if (faction != null)
                        {
                            Town town = Town.FromRegion(from.Region);

                            if (town != null && town.Owner == faction)
                            {
                                Container pack = from.Backpack;

                                if (pack != null)
                                {
                                    availableSilver = pack.GetAmount(typeof(Silver));

                                    if (availableSilver >= def.SilverCost)
                                    {
                                        queryFactionImbue = Faction.IsNearType(from, def.VendorType, 12);
                                    }
                                }
                            }
                        }
                    }
                }

                // TODO: Scroll imbuing

                if (queryFactionImbue)
                {
                    from.SendGump(new FactionImbueGump(quality, item, from, craftSystem, tool, num, availableSilver, faction, def));
                }
                else if (tool != null && !tool.Deleted && tool.UsesRemaining > 0)
                {
                    from.SendGump(new CraftGump(from, craftSystem, tool, num));
                }
                else if (num > 0)
                {
                    from.SendLocalizedMessage(num);
                }
            }
            else if (!allRequiredSkills)
            {
                if (tool != null && !tool.Deleted && tool.UsesRemaining > 0)
                {
                    from.SendGump(new CraftGump(from, craftSystem, tool, 1044153));
                }
                else
                {
                    from.SendAsciiMessage("You don't have the required skills to attempt this item.");
                }
            }
            else
            {
                ConsumeType consumeType = (UseAllRes ? ConsumeType.Half : ConsumeType.All);
                int         resHue      = 0;
                int         maxAmount   = 0;

                object message = null;

                // Not enough resource to craft it
                if (!ConsumeRes(from, typeRes, craftSystem, ref resHue, ref maxAmount, consumeType, ref message, true))
                {
                    if (tool != null && !tool.Deleted && tool.UsesRemaining > 0)
                    {
                        from.SendGump(new CraftGump(from, craftSystem, tool, message));
                    }
                    else if (message is int && (int)message > 0)
                    {
                        from.SendLocalizedMessage((int)message);
                    }
                    else if (message is string)
                    {
                        from.SendMessage((string)message);
                    }

                    return;
                }

                tool.UsesRemaining--;

                if (tool.UsesRemaining < 1)
                {
                    toolBroken = true;
                }

                if (toolBroken)
                {
                    tool.Delete();
                }

                // SkillCheck failed.
                int num = craftSystem.PlayEndingEffect(from, true, true, toolBroken, endquality, false, this);

                if (tool != null && !tool.Deleted && tool.UsesRemaining > 0)
                {
                    from.SendGump(new CraftGump(from, craftSystem, tool, num));
                }
                else if (num > 0)
                {
                    from.SendLocalizedMessage(num);
                }
            }
        }
Пример #50
0
 public virtual void DailyTick(Town town)
 {
     return;
 }
Пример #51
0
 public BadPerson(string fullName, string dateOfBirth, Town placeOfBirth, int numberId) : base(fullName,
                                                                                               dateOfBirth, placeOfBirth, numberId)
 {
 }
        private void DailyGarrisonRecruitmentEvent(Settlement s)
        {
            try
            {
                if (s.IsCastle || s.IsTown)
                {
                    Town t         = s.Town;
                    var  prisoners = CampaignUtils.GetPrisonersInSettlement(t);
                    if (prisoners.Count > 0)
                    {
                        int   total         = Utils.Utils.GetTotalPrisonerCounts(prisoners);
                        int   totalGarrison = CampaignUtils.GetGarrisonCountInSettlement(t);
                        float recruitChance = 0;
                        float devalueChance = 0;
                        int   capTimes      = 0;

                        Random rand = new Random();

                        recruitChance  = Config.BaseRecruitChance;
                        devalueChance  = Config.BaseDevalueChance;
                        recruitChance += Config.MercifulTraitModifier * (s.OwnerClan.Leader == null ? 0 : s.OwnerClan.Leader.GetTraitLevel(DefaultTraits.Mercy));
                        devalueChance -= Config.MercifulTraitModifier * (s.OwnerClan.Leader == null ? 0 : s.OwnerClan.Leader.GetTraitLevel(DefaultTraits.Mercy));
                        capTimes       = (int)((float)total / ((float)totalGarrison * Config.PrisonerPartyPercentageCap));
                        recruitChance *= (float)Math.Pow(Config.CapReverseFinalCoefficientPerCap, capTimes);

                        List <PrisonerInfo> recruited = new List <PrisonerInfo>();
                        List <PrisonerInfo> devalued  = new List <PrisonerInfo>();
                        foreach (var p in prisoners)
                        {
                            if (p.prisoner.IsHero || p.prisoner.IsPlayerCharacter)
                            {
                                continue;
                            }
                            float particularRecruitChance = recruitChance - (p.prisoner.Level * Config.PrisonerLevelReverseModifierPerLevel);
                            float particularDevalueChance = devalueChance + (p.prisoner.Level * Config.PrisonerLevelDevalueModifierPerLevel);
                            if (p.prisoner.Culture != null && t.Culture != null && p.prisoner.Culture != t.Culture)
                            {
                                particularRecruitChance -= Config.DifferentCultureReverseModifier;
                                particularDevalueChance -= Config.DifferentCultureReverseModifier;
                            }
                            particularRecruitChance  = Math.Max(particularRecruitChance, Config.FinalMinimumChance);
                            particularDevalueChance  = Math.Max(particularDevalueChance, Config.FinalMinimumChance);
                            particularRecruitChance *= Config.GarrisonFinalCoefficient;
                            particularDevalueChance *= Config.GarrisonFinalCoefficient;
                            int troopCount = p.count;

                            int recruitedCount = 0;
                            int devaluedCount  = 0;
                            for (int i = 0; i < troopCount; i++)
                            {
                                if (rand.NextDouble() <= particularRecruitChance)
                                {
                                    //recruit!
                                    recruitedCount++;
                                }
                                if (rand.NextDouble() <= particularDevalueChance)
                                {
                                    //recruit!
                                    devaluedCount++;
                                }
                            }
                            if (recruitedCount > 0)
                            {
                                recruited.Add(new PrisonerInfo()
                                {
                                    count      = recruitedCount,
                                    prisoner   = p.prisoner,
                                    ownerParty = p.ownerParty
                                });
                            }
                            if (devaluedCount > 0)
                            {
                                devalued.Add(new PrisonerInfo()
                                {
                                    count      = devaluedCount,
                                    prisoner   = p.prisoner,
                                    ownerParty = p.ownerParty
                                });
                            }
                        }
                        recruited.ForEach((PrisonerInfo p) => PartyRecruitAndRemovePrisoner(p.ownerParty, p.prisoner, p.count));
                        devalued.ForEach((PrisonerInfo p) => PartyDevaluePrisoner(p.ownerParty, p.prisoner, p.count));
                    }
                }
            }catch (Exception e)
            {
                ErrorHandler.HandleException(e, "daily garrison recruitment event of " + s.StringId);
            }
        }
Пример #53
0
 public override void HandleTurnEnd(Town town, Region region)
 {
 }
Пример #54
0
        private static void CheckEntryStatus(GameDateTime current, string ipAddress, Character chara, string password, CharacterIcon icon, Town town, Country country, bool isCountryFree)
        {
            if (string.IsNullOrEmpty(ipAddress))
            {
                ErrorCode.InvalidIpAddressError.Throw();
            }

            if (string.IsNullOrEmpty(password))
            {
                ErrorCode.LackOfParameterError.Throw();
            }
            if (password.Length < 4 || password.Length > 12)
            {
                ErrorCode.StringLengthError.Throw(new ErrorCode.RangeErrorParameter("password", password.Length, 4, 12));
            }
            if (string.IsNullOrEmpty(chara.Name))
            {
                ErrorCode.LackOfNameParameterError.Throw();
            }
            if (chara.Name.Contains('_'))
            {
                ErrorCode.NotPermissionError.Throw();
            }
            if (chara.Name.Length < 1 || chara.Name.Length > 12)
            {
                ErrorCode.StringLengthError.Throw(new ErrorCode.RangeErrorParameter("name", chara.Name.Length, 1, 12));
            }
            if (string.IsNullOrEmpty(chara.AliasId))
            {
                ErrorCode.LackOfParameterError.Throw();
            }
            if (chara.AliasId.Length < 4 || chara.AliasId.Length > 12)
            {
                ErrorCode.StringLengthError.Throw(new ErrorCode.RangeErrorParameter("aliasId", chara.AliasId.Length, 4, 12));
            }

            if (icon.Type == CharacterIconType.Default)
            {
                var iconIdStr = icon.FileName.Split('.');
                if (uint.TryParse(iconIdStr[0], out uint iconId))
                {
                    if (iconId < 0 || iconId > 99)
                    {
                        ErrorCode.CharacterIconNotFoundError.Throw();
                    }
                }
                else
                {
                    ErrorCode.CharacterIconNotFoundError.Throw();
                }
            }
            else if (icon.Type == CharacterIconType.Gravatar)
            {
                if (string.IsNullOrEmpty(icon.FileName))
                {
                    ErrorCode.LackOfParameterError.Throw();
                }
            }
            else
            {
                ErrorCode.InvalidParameterError.Throw();
            }

            if (chara.From == CharacterFrom.Unknown)
            {
                ErrorCode.LackOfParameterError.Throw();
            }

            var formation = FormationTypeInfoes.Get(chara.FormationType);

            if (formation.HasData)
            {
                if (!formation.Data.IsAvailable)
                {
                    ErrorCode.InvalidParameterError.Throw();
                }
            }

            var attributeMax    = GetAttributeMax(current);
            var attributeSumMax = GetAttributeSumMax(current);

            if (chara.Strong < 5 || chara.Intellect < 5 || chara.Leadership < 5 || chara.Popularity < 5)
            {
                ErrorCode.NumberRangeError.Throw(new ErrorCode.RangeErrorParameter("attribute", 0, 5, attributeMax));
            }
            if (chara.Strong > attributeMax || chara.Intellect > attributeMax || chara.Leadership > attributeMax || chara.Popularity > attributeMax)
            {
                ErrorCode.NumberRangeError.Throw(new ErrorCode.RangeErrorParameter("attribute", 0, 5, attributeMax));
            }
            if (chara.Strong + chara.Intellect + chara.Leadership + chara.Popularity < attributeSumMax - 2) // -2は新規登録情報入力途中に変動した場合の対応
            {
                ErrorCode.NumberRangeError.Throw(new ErrorCode.RangeErrorParameter("sumOfAttribute", 0, attributeSumMax, attributeSumMax));
            }
            if (chara.Strong + chara.Intellect + chara.Leadership + chara.Popularity > attributeSumMax)
            {
                ErrorCode.NumberRangeError.Throw(new ErrorCode.RangeErrorParameter("sumOfAttribute", 0, attributeSumMax, attributeSumMax));
            }

            if (country != null && (!string.IsNullOrEmpty(country.Name) || country.CountryColorId != 0))
            {
                if (country.CountryColorId < 1 || country.CountryColorId > Config.CountryColorMax)
                {
                    ErrorCode.NumberRangeError.Throw(new ErrorCode.RangeErrorParameter("countryColor", country.CountryColorId, 1, Config.CountryColorMax));
                }
                if (string.IsNullOrEmpty(country.Name) || country.Name.Length < 1 || country.Name.Length > 8)
                {
                    ErrorCode.NumberRangeError.Throw(new ErrorCode.RangeErrorParameter("countryName", country.Name.Length, 1, 8));
                }
                if (town.CountryId > 0)
                {
                    ErrorCode.CantPublisAtSuchTownhError.Throw();
                }
            }
            else
            {
                if (town.CountryId <= 0 && !isCountryFree)
                {
                    ErrorCode.CantJoinAtSuchTownhError.Throw();
                }
            }
        }
Пример #55
0
    /// <summary>
    /// Draws the traded resources.
    /// </summary>
    void DrawTradedResourcesUI(List<Vector2> grid, Town town)
    {
        int index = 0;

        foreach (TradeRoute.Item item in mSelectedRoute.items)
        {
            if (item.town == town)
            {
                Vector2 v = grid[index];
                TownResource tr = TownResources.Instance.list[ item.id ];
                if (tr.icon != null) UI.DrawTexture(v.x, v.y, tr.icon);
                Rect iconRect = new Rect(v.x, v.y, 50f, 50f);

                // It should be possible to drag these icons
                if (Input.GetMouseButtonDown(0) && iconRect.Contains(UI.GetMousePos()))
                {
                    CancelDrag();
                    mDragResource = item.id;
                    mDragTown = item.town;
                }

                if (++index >= grid.Count) break;
            }
        }
    }
Пример #56
0
 public override void HandleCreation(Town town, Region region)
 {
     region.IncomeMultiplier += 0.1f;
 }
Пример #57
0
 private int GetMatchedTownId(BtsExcel btsExcel, Town town)
 {
     return (btsExcel.DistrictName == town.DistrictName && btsExcel.TownName == town.TownName) ? town.Id : -1;
 }
 private void RefreshCanGrantFief(Town town)
 {
     RefreshClan();
     RefreshCanGrantFief();
 }
Пример #59
0
 public override void HandleObsoletion(Town town, Region region)
 {
     region.IncomeMultiplier -= 0.1f;
 }
Пример #60
0
    void PlaceBuildings2(List <Vector2> factionPoints, Faction fac)
    {
        GameObject capital = objectToPlace[0]; //one per faction, can hire troops or get resources
        GameObject city    = objectToPlace[1]; //can hire troops here
        GameObject village = objectToPlace[2]; //can get resources here

        fac.SetChallengersToFaction();         //makes sure challengers in list of faction have this faction as their faction
        //Debug.Log(" length is : " + factionPoints.Count);
        var result = PickNPoints(factionPoints, 1);
        //place city
        float posy = Terrain.activeTerrain.SampleHeight(new Vector3(result.GetFirst()[0].x, 0, result.GetFirst()[0].y)); //finds the y given x and z
                                                                                                                         //generate the object
        Vector3    capPos     = new Vector3(result.GetFirst()[0].x, posy + cubeOffset, result.GetFirst()[0].y);
        GameObject capitalObj = (GameObject)Instantiate(capital, capPos, Quaternion.identity);
        Town       capitalRef = capitalObj.GetComponent <Town>();

        //set capital cities properties
        capitalRef.Setup(true, 3, 10, fac, capPos);       //todo randomise as appropr
        capitalRef.buildingName = SpawnManager.AssignName();
        capitalRef.AddTroops(new Unit(troopPic, 10), 10); //10 as setup is 10 above
        fac.capital    = capitalRef;                      //sets capital of faction in class
        factionAPoints = result.GetSecond();
        int            aSize  = factionAPoints.Count;
        int            offset = aSize % 3; //we want every town to have 2 villages so we are splitting array into chunks of 3
        VectorTuple    threePoints;
        List <Vector2> t;
        VectorTuple    t2;
        Vector2        townPoint;
        List <Vector2> villagePoints;
        float          posY;

        //int count = 1;
        for (int i = 0; i < targetPoints / 2; i += 3)
        {
            threePoints    = PickNPoints(factionAPoints, 3);
            factionAPoints = threePoints.GetSecond();
            t             = threePoints.GetFirst();
            t2            = PickNPoints(t, 1);
            townPoint     = t2.GetFirst()[0];                                                             //this is the town, the other 2 are the attached smaller villages
            villagePoints = t2.GetSecond();
            posY          = Terrain.activeTerrain.SampleHeight(new Vector3(townPoint.x, 0, townPoint.y)); //finds the y given x and z
            //placing town
            Vector3    townPos = new Vector3(townPoint.x, posY, townPoint.y);
            GameObject cityObj = (GameObject)Instantiate(city, townPos, Quaternion.identity);
            Town       cityRef = cityObj.GetComponent <Town>();
            //set capital cities properties
            cityRef.Setup(false, 2, 5, fac, townPos); //todo randomise as appropr
            cityRef.buildingName = SpawnManager.AssignName();
            cityRef.AddTroops(new Unit(troopPic, 5), 5);
            fac.towns.Add(cityRef); //adds town
            //place villages
            //Debug.Log("village length (should be 2): " + villagePoints.Count);
            foreach (Vector2 v in villagePoints)
            {
                float      y          = Terrain.activeTerrain.SampleHeight(new Vector3(v.x, 0, v.y)); //finds the y given x and z
                Vector3    pos        = new Vector3(v.x, y + cubeOffset, v.y);
                GameObject villageObj = (GameObject)Instantiate(village, pos, Quaternion.identity);
                //setup village objects (TODO)
                Village vilRef = villageObj.GetComponent <Village>();
                vilRef.buildingName = SpawnManager.AssignName();
                vilRef.Setup(fac, pos);
                fac.villages.Add(vilRef);
            }
            //factionAPoints = threePoints.GetSecond();
            // count += 3;
        }
    }