Beispiel #1
0
 public Tool(WorldTile type, Texture2D texture)
 {
     this.type = type;
     this.texture = texture;
     this.isObstacle = type.isObstacle();
     this.cost = type.GetCost();
 }
Beispiel #2
0
    public static WorldTile createTile(int tileID, Vector2 position)
    {
        string key = getKey(position);
        if (!tiles.ContainsKey(key)) {
            Debug.Log("Wrong tile");
            return null;
        }

        if (tiles[key] != null) {
            Debug.Log("Tile not empty");
            return null;
        }

        DataTile tile = WorldData.tiles[tileID];
        if (tile.result == null || tile.result.id < 0) {
            Debug.Log("Result not defined");
            return null;
        }

        tiles[key] = new WorldTile(tile.result.id, position);

        if (OnTileCreate != null) OnTileCreate();

        return tiles[key];
    }
        public WorldRegion(int width, int height)
        {
            tiles = new WorldTile[width][];

            for (int i = 0; i < width; i++)
                tiles[i] = new WorldTile[height];

            Width = width;
            Height = height;
        }
Beispiel #4
0
    internal void Initialize( GameObject thisParent, int worldWidth, int worldHeight )
    {
        parent = thisParent;
        worldTiles = new WorldTile[worldWidth, worldHeight];
        season = GameObject.FindGameObjectWithTag ( "Manager" ).GetComponent<TimeManager>().currentSeason ();
        Color[,] heightmap = GeneratePerlinNoise ( 1.0f, 1.0f, worldWidth, worldHeight );

        int widthIndex = 0;
        int heightIndex = 0;

        while ( heightIndex < worldTiles.GetLength ( 1 ))
        {

            while ( heightIndex < worldHeight )
            {

                while ( widthIndex < worldWidth )
                {

                    float localHeight = 0;
                    if ( heightmap[ widthIndex, heightIndex ].grayscale > 0.5f )
                    {

                        localHeight = 5;
                    }

                    WorldTile newTile = new WorldTile ();
                    newTile.Initialize ( this, widthIndex, localHeight, heightIndex);

                    worldTiles[widthIndex, heightIndex] = newTile;

                    widthIndex += 1;
                }

                widthIndex = 0;
                heightIndex += 1;
            }
        }
    }
    //gets the neighbours of the coords passed in
    public List <WorldTile> getNeighbours(int x, int y, int width, int height)
    {
        List <WorldTile> myNeighbours = new List <WorldTile>();

        //needs the width & height to work out if a tile is not on the edge, also needs to check if the nodes is null due to the accounting for odd shapes


        if (x > 0 && x < width - 1)
        {
            //can get tiles on both left and right of the tile

            if (y > 0 && y < height - 1)
            {
                //top and bottom
                if (nodes[x + 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt1 = nodes[x + 1, y].GetComponent <WorldTile>();
                    if (wt1 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt1);
                    }
                }

                if (nodes[x - 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt2 = nodes[x - 1, y].GetComponent <WorldTile>();

                    if (wt2 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt2);
                    }
                }

                if (nodes[x, y + 1] == null)
                {
                }
                else
                {
                    WorldTile wt3 = nodes[x, y + 1].GetComponent <WorldTile>();
                    if (wt3 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt3);
                    }
                }

                if (nodes[x, y - 1] == null)
                {
                }
                else
                {
                    WorldTile wt4 = nodes[x, y - 1].GetComponent <WorldTile>();
                    if (wt4 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt4);
                    }
                }
            }
            else if (y == 0)
            {
                //just top
                if (nodes[x + 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt1 = nodes[x + 1, y].GetComponent <WorldTile>();
                    if (wt1 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt1);
                    }
                }

                if (nodes[x - 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt2 = nodes[x - 1, y].GetComponent <WorldTile>();

                    if (wt2 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt2);
                    }
                }
                if (nodes[x, y + 1] == null)
                {
                }
                else
                {
                    WorldTile wt3 = nodes[x, y + 1].GetComponent <WorldTile>();
                    if (wt3 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt3);
                    }
                }
            }
            else if (y == height - 1)
            {
                //just bottom
                if (nodes[x, y - 1] == null)
                {
                }
                else
                {
                    WorldTile wt4 = nodes[x, y - 1].GetComponent <WorldTile>();
                    if (wt4 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt4);
                    }
                }
                if (nodes[x + 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt1 = nodes[x + 1, y].GetComponent <WorldTile>();
                    if (wt1 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt1);
                    }
                }

                if (nodes[x - 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt2 = nodes[x - 1, y].GetComponent <WorldTile>();

                    if (wt2 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt2);
                    }
                }
            }
        }
        else if (x == 0)
        {
            //can't get tile on left
            if (y > 0 && y < height - 1)
            {
                //top and bottom

                if (nodes[x + 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt1 = nodes[x + 1, y].GetComponent <WorldTile>();
                    if (wt1 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt1);
                    }
                }

                if (nodes[x, y - 1] == null)
                {
                }
                else
                {
                    WorldTile wt4 = nodes[x, y - 1].GetComponent <WorldTile>();
                    if (wt4 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt4);
                    }
                }
                if (nodes[x, y + 1] == null)
                {
                }
                else
                {
                    WorldTile wt3 = nodes[x, y + 1].GetComponent <WorldTile>();
                    if (wt3 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt3);
                    }
                }
            }
            else if (y == 0)
            {
                //just top
                if (nodes[x + 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt1 = nodes[x + 1, y].GetComponent <WorldTile>();
                    if (wt1 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt1);
                    }
                }

                if (nodes[x, y + 1] == null)
                {
                }
                else
                {
                    WorldTile wt3 = nodes[x, y + 1].GetComponent <WorldTile>();
                    if (wt3 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt3);
                    }
                }
            }
            else if (y == height - 1)
            {
                //just bottom
                if (nodes[x + 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt1 = nodes[x + 1, y].GetComponent <WorldTile>();
                    if (wt1 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt1);
                    }
                }
                if (nodes[x, y - 1] == null)
                {
                }
                else
                {
                    WorldTile wt4 = nodes[x, y - 1].GetComponent <WorldTile>();
                    if (wt4 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt4);
                    }
                }
            }
        }
        else if (x == width - 1)
        {
            //can't get tile on right
            if (y > 0 && y < height - 1)
            {
                //top and bottom
                if (nodes[x - 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt2 = nodes[x - 1, y].GetComponent <WorldTile>();

                    if (wt2 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt2);
                    }
                }

                if (nodes[x, y + 1] == null)
                {
                }
                else
                {
                    WorldTile wt3 = nodes[x, y + 1].GetComponent <WorldTile>();
                    if (wt3 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt3);
                    }
                }
                if (nodes[x, y - 1] == null)
                {
                }
                else
                {
                    WorldTile wt4 = nodes[x, y - 1].GetComponent <WorldTile>();
                    if (wt4 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt4);
                    }
                }
            }
            else if (y == 0)
            {
                //just top
                if (nodes[x - 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt2 = nodes[x - 1, y].GetComponent <WorldTile>();

                    if (wt2 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt2);
                    }
                }
                if (nodes[x, y + 1] == null)
                {
                }
                else
                {
                    WorldTile wt3 = nodes[x, y + 1].GetComponent <WorldTile>();
                    if (wt3 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt3);
                    }
                }
            }
            else if (y == height - 1)
            {
                //just bottom
                if (nodes[x - 1, y] == null)
                {
                }
                else
                {
                    WorldTile wt2 = nodes[x - 1, y].GetComponent <WorldTile>();

                    if (wt2 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt2);
                    }
                }
                if (nodes[x, y - 1] == null)
                {
                }
                else
                {
                    WorldTile wt4 = nodes[x, y - 1].GetComponent <WorldTile>();
                    if (wt4 == null)
                    {
                    }
                    else
                    {
                        myNeighbours.Add(wt4);
                    }
                }
            }
        }


        return(myNeighbours);
    }
Beispiel #6
0
    // Update is called once per frame
    void Update()
    {
        if (_workingTile != null) {
            _workingTime += Time.smoothDeltaTime;
            if (_workingTime > _workingTile.workingTime) {
                _workingTile.endWork();
                _workingTile = null;
                _workingTime = 0f;
                if (instrument != null) {
                    instrument.GetComponent<SpriteRenderer>().enabled = false;
                }

            }
            return;
        }

        if (Input.GetKeyDown(KeyCode.I)) {
            if (inventory.activeSelf) {
                inventory.SetActive(false);
            } else {
                inventory.SetActive(true);
            }
            return;
        }

        WorldTile tile;

        float ix = Input.GetAxis ("Horizontal");
        float iy = Input.GetAxis ("Vertical");

        if (ix != 0f || iy != 0f) {

            //Debug.Log(transform.position);
            //Debug.Log(World.alignPos(transform.position ));

            RaycastHit2D hit;

            float tileSpeed = 1f;

            tile = World.getTile(transform.position );
            if (tile != null) tileSpeed = tile.speed;

            Vector2 direction = new Vector2(ix, iy) * speed * Time.smoothDeltaTime * tileSpeed;
            Vector3 newPos = transform.position + new Vector3(direction.x, direction.y);
            if (newPos.x < 0 || newPos.y < 0) return;

            Vector2 dir = Vector2.zero;
            if (boxCollider == null) {
                transform.Translate(direction.x, direction.y, 0);
                dir = direction;
            } else {
                //boxCollider.
                Vector2 center = new Vector2(transform.position.x, transform.position.y) + boxCollider.offset;
                hit = Physics2D.BoxCast(center, boxCollider.size, 0, new Vector2(0, direction.y), Mathf.Abs(direction.y),terrainLayer);
                //Debug.DrawRay(transform.position, direction * 10, Color.yellow);

                if (hit.collider == null) {
                    transform.Translate(0, direction.y, 0);
                    dir.y = iy;
                } else {

                }

                hit = Physics2D.BoxCast(center, boxCollider.size, 0, new Vector2(direction.x,0), Mathf.Abs(direction.x),terrainLayer);
                if (hit.collider == null) {
                    transform.Translate(direction.x, 0, 0);
                    dir.x = ix;
                }

            }
            Debug.Log(dir);
            if (dir.y > 0) {
                character.SetInteger("direction",3);
            } else if (dir.x > 0) {
                character.SetInteger("direction",2);
            } else if (dir.x < 0) {
                character.SetInteger("direction",1);
            } else {
                character.SetInteger("direction",0);
            }
        } else {
            character.SetInteger("direction",0);
        }

        if (Input.GetAxis("Mouse ScrollWheel") > 0) {
            if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) {
                if (Camera.main.orthographicSize > 1) Camera.main.orthographicSize--;
            } else {
                nextWeapon();
            }
        }
        if (Input.GetAxis("Mouse ScrollWheel") < 0) {
            if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) {
                //if (Camera.main.orthographicSize < 12)
                    Camera.main.orthographicSize++;
            } else {
                nextWeapon(-1);
            }
        }

        Vector3 currentPos = new Vector3(transform.position.x, transform.position.y);
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        Vector2 alignMouse = World.alignPos(mousePos);

        float dist = Vector2.Distance(currentPos,alignMouse);
        bool working = dist < workDistance;

        cursor.inArea = working;

        if (Input.GetMouseButtonDown(1) && CursorControler.reward.id > -1) {
            if (Inventory.addReward(CursorControler.reward)) {
                putinHand(-1,0);
            }
            return;
        }

        tile = World.getTile(mousePos);
        if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject()) {

            if (tile == null) {//&& hand.itemID > -1
                if (working ) {
                     tile = World.createTile(hand.itemID, alignMouse);
                     if (tile != null) {
                        if (hand.count > 1) {
                            int cnt = hand.count - 1;
                            hand.setReward(hand.itemID, cnt);
                            cursor.setReward(hand.itemID, cnt);
                        } else {
                            hand.setReward(-1);
                            cursor.setReward(-1,0);
                        }
                        _workingTime = 0f;
                        _workingTile = tile;
                        instrument.GetComponent<SpriteRenderer>().enabled = true;
                    }
                }
            } else {
                if (tile.doWork(working)) {
                    _workingTime = 0f;
                    _workingTile = tile;
                    instrument.GetComponent<SpriteRenderer>().enabled = true;
                }
            }
        }
    }
Beispiel #7
0
 protected abstract int OnApply(WorldTile target);
Beispiel #8
0
 public abstract int Predict(WorldTile target);
Beispiel #9
0
 private void highlightTile(Dictionary <Vector3, WorldTile> tiles, Vector3 coords, WorldTile worldTile, Color color)
 {
     if (tiles.TryGetValue(coords, out worldTile))
     {
         worldTile.TilemapMember.SetTileFlags(worldTile.LocalPlace, TileFlags.None);
         worldTile.TilemapMember.SetColor(worldTile.LocalPlace, color);
     }
 }
Beispiel #10
0
    public void EndTurn()
    {
        // Loop through all tiles in the game
        foreach (Vector3Int cell in gameTiles.cellBounds.allPositionsWithin)
        {
            // Base tile type
            WorldTile tile = GetTileAtPoint(cell);

            // Position in data matrix
            int x = cell[0] - xMin;
            int y = cell[1] - yMin;
            // Tile has been alive for one more turn
            worldTilesData[x, y].AdvanceTurn();

            // Growing / decaying / dying logic
            if (worldTilesData[x, y].WaterAmount() >= tile.waterToTransform)
            {
                if (tile.turnsInto)
                {
                    worldTilesData[x, y].SetOpenForPlacement(true);
                    PlaceTile(tile.turnsInto, cell);
                }
            }

            if (worldTilesData[x, y].WaterAmount() <= tile.waterToDegrade)
            {
                if (tile.degradesInto)
                {
                    worldTilesData[x, y].SetOpenForPlacement(true);
                    PlaceTile(tile.degradesInto, cell);
                }
            }

            if (tile.lifeTime > 0)
            {
                if (worldTilesData[x, y].turnsAlive > tile.lifeTime)
                {
                    if (tile.diesInto)
                    {
                        worldTilesData[x, y].SetOpenForPlacement(true);
                        PlaceTile(tile.diesInto, cell);
                    }
                }
            }

            // Water drain / leak logic
            // Get neighbors
            List <Vector2Int> indexNeighbors = GetIndexNeighbors(TilePointToIndex(cell));
            // Then drain / leak into each one
            foreach (Vector2Int neighbor in indexNeighbors)
            {
                // draining from
                int drainAmount   = tile.waterDrain;
                int amountDrained = worldTilesData[neighbor[0], neighbor[1]].DrainWater(drainAmount);
                worldTilesData[x, y].AddWater(drainAmount);
            }
            // leaking to neighbors
            for (int l = 0; l < tile.waterLeak; l++)
            {
                Vector2Int neighbor = indexNeighbors[Random.Range(0, indexNeighbors.Count)];
                if (worldTilesData[x, y].WaterAmount() > worldTilesData[neighbor[0], neighbor[1]].WaterAmount())
                {
                    worldTilesData[neighbor[0], neighbor[1]].AddWater(1);
                    worldTilesData[x, y].DrainWater(1);
                }
            }
        }

        // Place random danger tiles - TODO, adjustment for how often, type
        if (weedSpawnProbability > Random.Range(0f, 1f))
        {
            PlaceTileRandomly(weedTiles[0]);
            audioSource.clip = weedAlert;
            audioSource.Play();
        }

        // Plant spreading

        // Update turns used
        turnsUsed++;
        actionPointsLeft = baseActionPoints;

        // Play audio
        audioSource.clip = endTurn;
        audioSource.Play();

        // Update HUD
        hud.UpdateStatusIndicators(actionPointsLeft, turnsUsed, waterAvailable);
    }
Beispiel #11
0
 public Texture2D getTexture(WorldTile type)
 {
     return this.texmap[type.GetTexture()];
 }
Beispiel #12
0
 private static MemberInfo ForValue(WorldTile p)
 {
     return typeof(WorldTile).GetField(Enum.GetName(typeof(WorldTile), p));
 }
Beispiel #13
0
    public void FillFields(Building selectedBuilding)
    {
        nameText.text = "District Name";

        int population = 0;

        int[] preferences = new int[4];
        int[] incomes     = new int[3];

        int maxIngredientNum = System.Enum.GetValues(typeof(RecipeIngredient)).Cast <int>().Max();

        int[] favorites = new int[maxIngredientNum + 1];
        int[] hates     = new int[maxIngredientNum + 1];

        int district            = selectedBuilding.tile.district;
        List <GameObject> tiles = selectedBuilding.world.allTiles;

        foreach (GameObject tile in tiles)
        {
            try
            {
                WorldTile tileScript = tile.GetComponent <WorldTile>();
                if (tileScript.district != district)
                {
                    continue;
                }
                if (tileScript.building.GetType() != typeof(BuildingResidential))
                {
                    continue;
                }
                BuildingResidential building = (BuildingResidential)tileScript.building;
                foreach (Pop resident in building.residents)
                {
                    population++;
                    switch (resident.preference)
                    {
                    case FoodPreference.AMERICAN:
                        preferences[0]++;
                        break;

                    case FoodPreference.ITALIAN:
                        preferences[1]++;
                        break;

                    case FoodPreference.MEXICAN:
                        preferences[2]++;
                        break;

                    default:
                        preferences[3]++;
                        break;
                    }

                    switch (resident.income)
                    {
                    case IncomeLevel.LOW:
                        incomes[0]++;
                        break;

                    case IncomeLevel.MIDDLE:
                        incomes[1]++;
                        break;

                    case IncomeLevel.HIGH:
                        incomes[2]++;
                        break;
                    }


                    if (resident.favoriteIngredient != RecipeIngredient.EMPTY)
                    {
                        favorites[(int)resident.favoriteIngredient]++;
                    }


                    if (resident.hatedIngredient != RecipeIngredient.EMPTY)
                    {
                        hates[(int)resident.hatedIngredient]++;
                    }
                }
            }
            catch
            {
                //Do nothing
            }
        }
        populationText.text = "Population: " + population;

        float popCount = population;

        ameriPref.text = "American: " + (100 * preferences[0] / popCount).ToString("F0") + "%";
        italPref.text  = "Italian: " + (100 * preferences[1] / popCount).ToString("F0") + "%";
        mexiPref.text  = "Mexican: " + (100 * preferences[2] / popCount).ToString("F0") + "%";
        noPref.text    = "None: " + (100 * preferences[3] / popCount).ToString("F0") + "%";
        prefChart.SetChart(preferences);

        lowIncome.text  = "Low: " + (100 * incomes[0] / popCount).ToString("F0") + "%";
        midIncome.text  = "Middle: " + (100 * incomes[1] / popCount).ToString("F0") + "%";
        highIncome.text = "High: " + (100 * incomes[2] / popCount).ToString("F0") + "%";
        incomeChart.SetChart(incomes);

        List <IngredientRank> rankedFavorites = new List <IngredientRank>();
        List <IngredientRank> rankedHates     = new List <IngredientRank>();

        for (int i = 0; i < favorites.Length; i++)
        {
            rankedFavorites.Add(new IngredientRank(i, favorites[i]));
            rankedHates.Add(new IngredientRank(i, hates[i]));
        }

        rankedFavorites.Sort();
        rankedFavorites.Reverse();
        for (int i = 0; i < likes.Count(); i++)
        {
            try
            {
                string ingredient = Ingredient.IngredientToString(rankedFavorites[i].ingredient);
                if (ingredient.Length > 8)
                {
                    ingredient = ingredient.Substring(0, 8);
                }
                likes[i].text = (i + 1) + ". " + ingredient + ": " + (100 * rankedFavorites[i].count / popCount).ToString("F0") + "%";
            }
            catch
            {
                likes[i].text = "";
            }
        }

        rankedHates.Sort();
        rankedHates.Reverse();
        for (int i = 0; i < dislikes.Count(); i++)
        {
            try
            {
                string ingredient = Ingredient.IngredientToString(rankedFavorites[i].ingredient);
                if (ingredient.Length > 8)
                {
                    ingredient = ingredient.Substring(0, 8);
                }
                dislikes[i].text = (i + 1) + ". " + ingredient + ": " + (100 * rankedHates[i].count / popCount).ToString("F0") + "%";
            }
            catch
            {
                dislikes[i].text = "";
            }
        }
    }
 public override List <WorldTile> GetTilesInArea(Board board, Point pos)
 {
     tile = board.GetTile(pos);
     return(board.Search(tile, ExpandSearch));
 }
 bool ExpandSearch(WorldTile from, WorldTile to)
 {
     return((from.distance + 1) <= horizontal);
     //return (from.distance + 1) <= horizontal && Mathf.Abs(to.height - tile.height) <= vertical;
 }
Beispiel #16
0
 public SelectedWorldTile(WorldTile worldTile)
 {
     Tile = worldTile;
 }
Beispiel #17
0
    // Ok, what's a tweener? is this some sort of sorcery?
	IEnumerator Walk(WorldTile target)
	{
		Tweener tweener = transform.MoveTo(target.LocalPlace, 0.5f, EasingEquations.Linear);
		while (tweener != null)
			yield return null;
	}
Beispiel #18
0
        public ToolMap(int x, int y, Texture2D pixel, Dictionary<String,Texture2D> texmap, WorldTile[] tiles, SpriteFont font, IntPtr handle)
        {
            this.handle = handle;
            combobox = new System.Windows.Forms.ComboBox();
            combobox.Location = new System.Drawing.Point(542, 50);
            combobox.Size = new System.Drawing.Size(200, 25);
            combobox.BackColor = System.Drawing.Color.White;
            combobox.ForeColor = System.Drawing.Color.Black;
            combobox.SelectedIndexChanged +=
            new System.EventHandler(ComboBox1_SelectedIndexChanged);

            this.texmap = texmap;
            this.pixel = pixel;
            this.font = font;
            /*Color[] colors = new Color[]{Color.White, Color.Red, Color.Goldenrod,
                Color.Green, Color.Blue, Color.Chocolate, Color.Orange, Color.DarkGray,
            Color.Purple, Color.Black};
            */
            xmin = x;
            ymin = y;

            int[] col = {x,x+90};
            xmax = col[1] + 32;
            int yinterval = 44;
            ymax = y + 3 * yinterval + 32;

            xcolwidth = (xmax - xmin) / 2;
            yrowheight = (ymax - ymin) / 4;

            toolmap = new Dictionary<WorldTile, Tool>();
            for (int i = 0; i < tiles.Length; i++)
            {
                if (tiles[i] != WorldTile.SELECT)
                {
                    try
                    {
                        toolmap.Add(tiles[i], new Tool(tiles[i], texmap[tiles[i].GetTexture()]));
                    }
                    catch (KeyNotFoundException e)
                    { }
                }
            }

            for (int i = 0; i < tiles.Length; i++)
                combobox.Items.Add(tiles[i]);

            /*tools = new Tile[2][];
            for(int j = 0; j < col.Length; j++)
            {
                tools[j] = new Tile[4];
                for (int i = 0; i < 4; i++)
                {
                    tools[j][i] = new Tile(j, i, col[j] + 1, 1 + y + yinterval * i, 32, tooltextures[j][i]);
                }

            }*/
            selected = null;
            selectedtop = new Rectangle(-40,-40,36,2);
            selectedbottom = new Rectangle(-40,-40,36,2);
            selectedleft = new Rectangle(-40,-40,2,36);
            selectedright = new Rectangle(-40,-40,2,36);
            //updateSelected(selected.getX(), selected.getY(), selected.getLength(), selected.getLength());

            addeventbutton = new Rectangle(xmin, ymax, 142, 30);
            editbutton = new Rectangle(xmin, ymax + 10, 122, 30);
            astarbutton = new Rectangle(xmin, ymax + 60, 122, 30);
            playbutton = new Rectangle(xmin, ymax + 110, 122, 30);
            savebutton = new Rectangle(xmin, ymax + 160, 122, 30);
            loadbutton = new Rectangle(xmin, ymax + 210, 122, 30);
        }
    void createNodes()
    {
        int gridX = 0; //use these to work out the size and where each node should be in the 2d array we'll use to store our nodes so we can work out neighbours and get paths
        int gridY = 0;

        bool foundTileOnLastPass = false;

        //scan tiles and create nodes based on where they are
        for (int x = scanStartX; x < scanFinishX; x++)
        {
            for (int y = scanStartY; y < scanFinishY; y++)
            {
                //go through our world bounds in increments of 1
                TileBase tb = floor.GetTile(new Vector3Int(x, y, 0)); //check if we have a floor tile at that world coords
                if (tb == null)
                {
                }
                else
                {
                    //if we do we go through the obstacle layers and check if there is also a tile at those coords if so we set founObstacle to true
                    bool foundObstacle = false;
                    foreach (Tilemap t in obstacleLayers)
                    {
                        TileBase tb2 = t.GetTile(new Vector3Int(x, y, 0));

                        if (tb2 == null)
                        {
                        }
                        else
                        {
                            foundObstacle = true;
                        }

                        //if we want to add an unwalkable edge round our unwalkable nodes then we use this to get the neighbours and make them unwalkable
                        if (unwalkableNodeBorder > 0)
                        {
                            List <TileBase> neighbours = getNeighbouringTiles(x, y, t);
                            foreach (TileBase tl in neighbours)
                            {
                                if (tl == null)
                                {
                                }
                                else
                                {
                                    foundObstacle = true;
                                }
                            }
                        }
                    }

                    if (foundObstacle == false)
                    {
                        //if we havent found an obstacle then we create a walkable node and assign its grid coords
                        GameObject node = (GameObject)Instantiate(nodePrefab, new Vector3(x + 0.5f + gridBase.transform.position.x, y + 0.5f + gridBase.transform.position.y, -.5f), Quaternion.Euler(0, 0, 0), walkableNodesParent);
                        WorldTile  wt   = node.GetComponent <WorldTile>();
                        wt.gridX            = gridX;
                        wt.gridY            = gridY;
                        foundTileOnLastPass = true; //say that we have found a tile so we know to increment the index counters
                        unsortedNodes.Add(node);

                        node.name = gridX.ToString() + " : " + gridY.ToString() + " - NODE";
                    }
                    else
                    {
                        //if we have found an obstacle then we do the same but make the node unwalkable
                        GameObject node = (GameObject)Instantiate(nodePrefab, new Vector3(x + 0.5f + gridBase.transform.position.x, y + 0.5f + gridBase.transform.position.y, -.5f), Quaternion.Euler(0, 0, 0), nonWalkableNodesParent);
                        //we add the gridBase position to ensure that the nodes are ontop of the tile they relate too
                        //node.GetComponentInChildren<SpriteRenderer>().color = Color.red;
                        WorldTile wt = node.GetComponent <WorldTile>();
                        wt.gridX            = gridX;
                        wt.gridY            = gridY;
                        wt.walkable         = false;
                        foundTileOnLastPass = true;
                        unsortedNodes.Add(node);
                        node.name = gridX.ToString() + " : " + gridY.ToString() + " - UNWALKABLE NODE";
                    }
                    gridY++; //increment the y counter


                    if (gridX > gridBoundX)
                    { //if the current gridX/gridY is higher than the existing then replace it with the new value
                        gridBoundX = gridX;
                    }

                    if (gridY > gridBoundY)
                    {
                        gridBoundY = gridY;
                    }
                }
            }
            if (foundTileOnLastPass == true)
            {//since the grid is going from bottom to top on the Y axis on each iteration of the inside loop, if we have found tiles on this iteration we increment the gridX value and
             //reset the y value
                gridX++;
                gridY = 0;
                foundTileOnLastPass = false;
            }
        }

        //put nodes into 2d array based on the
        nodes = new GameObject[gridBoundX + 1, gridBoundY + 1]; //initialise the 2d array that will store our nodes in their position
        foreach (GameObject g in unsortedNodes)
        {                                                       //go through the unsorted list of nodes and put them into the 2d array in the correct position
            WorldTile wt = g.GetComponent <WorldTile>();
            //Debug.Log (wt.gridX + " " + wt.gridY);
            nodes[wt.gridX, wt.gridY] = g;
        }

        //assign neighbours to nodes
        for (int x = 0; x < gridBoundX; x++)
        { //go through the 2d array and assign the neighbours of each node
            for (int y = 0; y < gridBoundY; y++)
            {
                if (nodes[x, y] == null)
                { //check if the coords in the array contain a node
                }
                else
                {
                    WorldTile wt = nodes[x, y].GetComponent <WorldTile>(); //if they do then assign the neighbours
                                                                           //if (wt.walkable == true) {
                    wt.myNeighbours = getNeighbours(x, y, gridBoundX, gridBoundY);
                    //}
                }
            }
        }

        //after this we have our grid of nodes ready to be used by the astar algorigthm
    }
Beispiel #20
0
 private static WorldTileAttribute GetAttribute(WorldTile p)
 {
     return (WorldTileAttribute)Attribute.GetCustomAttribute(ForValue(p), typeof(WorldTileAttribute));
 }
Beispiel #21
0
    // Update is called once per frame
    void Update()
    {
        if (_workingTile != null)
        {
            _workingTime += Time.smoothDeltaTime;
            if (_workingTime > _workingTile.workingTime)
            {
                _workingTile.endWork();
                _workingTile = null;
                _workingTime = 0f;
                if (instrument != null)
                {
                    instrument.GetComponent <SpriteRenderer>().enabled = false;
                }
            }
            return;
        }

        if (Input.GetKeyDown(KeyCode.I))
        {
            if (inventory.activeSelf)
            {
                inventory.SetActive(false);
            }
            else
            {
                inventory.SetActive(true);
            }
            return;
        }

        WorldTile tile;

        float ix = Input.GetAxis("Horizontal");
        float iy = Input.GetAxis("Vertical");

        if (ix != 0f || iy != 0f)
        {
            //Debug.Log(transform.position);
            //Debug.Log(World.alignPos(transform.position ));

            RaycastHit2D hit;

            float tileSpeed = 1f;

            tile = World.getTile(transform.position);
            if (tile != null)
            {
                tileSpeed = tile.speed;
            }

            Vector2 direction = new Vector2(ix, iy) * speed * Time.smoothDeltaTime * tileSpeed;
            Vector3 newPos    = transform.position + new Vector3(direction.x, direction.y);
            if (newPos.x < 0 || newPos.y < 0)
            {
                return;
            }

            Vector2 dir = Vector2.zero;
            if (boxCollider == null)
            {
                transform.Translate(direction.x, direction.y, 0);
                dir = direction;
            }
            else
            {
                //boxCollider.
                Vector2 center = new Vector2(transform.position.x, transform.position.y) + boxCollider.offset;
                hit = Physics2D.BoxCast(center, boxCollider.size, 0, new Vector2(0, direction.y), Mathf.Abs(direction.y), terrainLayer);
                //Debug.DrawRay(transform.position, direction * 10, Color.yellow);

                if (hit.collider == null)
                {
                    transform.Translate(0, direction.y, 0);
                    dir.y = iy;
                }
                else
                {
                }

                hit = Physics2D.BoxCast(center, boxCollider.size, 0, new Vector2(direction.x, 0), Mathf.Abs(direction.x), terrainLayer);
                if (hit.collider == null)
                {
                    transform.Translate(direction.x, 0, 0);
                    dir.x = ix;
                }
            }
            Debug.Log(dir);
            if (dir.y > 0)
            {
                character.SetInteger("direction", 3);
            }
            else if (dir.x > 0)
            {
                character.SetInteger("direction", 2);
            }
            else if (dir.x < 0)
            {
                character.SetInteger("direction", 1);
            }
            else
            {
                character.SetInteger("direction", 0);
            }
        }
        else
        {
            character.SetInteger("direction", 0);
        }

        if (Input.GetAxis("Mouse ScrollWheel") > 0)
        {
            if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
            {
                if (Camera.main.orthographicSize > 1)
                {
                    Camera.main.orthographicSize--;
                }
            }
            else
            {
                nextWeapon();
            }
        }
        if (Input.GetAxis("Mouse ScrollWheel") < 0)
        {
            if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
            {
                //if (Camera.main.orthographicSize < 12)
                Camera.main.orthographicSize++;
            }
            else
            {
                nextWeapon(-1);
            }
        }


        Vector3 currentPos = new Vector3(transform.position.x, transform.position.y);
        Vector3 mousePos   = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        Vector2 alignMouse = World.alignPos(mousePos);

        float dist    = Vector2.Distance(currentPos, alignMouse);
        bool  working = dist < workDistance;

        cursor.inArea = working;

        if (Input.GetMouseButtonDown(1) && CursorControler.reward.id > -1)
        {
            if (Inventory.addReward(CursorControler.reward))
            {
                putinHand(-1, 0);
            }
            return;
        }


        tile = World.getTile(mousePos);
        if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
        {
            if (tile == null)              //&& hand.itemID > -1
            {
                if (working)
                {
                    tile = World.createTile(hand.itemID, alignMouse);
                    if (tile != null)
                    {
                        if (hand.count > 1)
                        {
                            int cnt = hand.count - 1;
                            hand.setReward(hand.itemID, cnt);
                            cursor.setReward(hand.itemID, cnt);
                        }
                        else
                        {
                            hand.setReward(-1);
                            cursor.setReward(-1, 0);
                        }
                        _workingTime = 0f;
                        _workingTile = tile;
                        instrument.GetComponent <SpriteRenderer>().enabled = true;
                    }
                }
            }
            else
            {
                if (tile.doWork(working))
                {
                    _workingTime = 0f;
                    _workingTile = tile;
                    instrument.GetComponent <SpriteRenderer>().enabled = true;
                }
            }
        }
    }
Beispiel #22
0
    private void SimulateCustomers()
    {
        Debug.Log("Buying dishes");
        List <WorldTile> residentTiles   = new List <WorldTile>();
        List <WorldTile> restaurantTiles = new List <WorldTile>();

        foreach (GameObject tile in world.allTiles)
        {
            try
            {
                WorldTile tileScript = tile.GetComponent <WorldTile>();
                if (tileScript.building.GetType() == typeof(BuildingResidential))
                {
                    residentTiles.Add(tileScript);
                }
                else if (tileScript.building.GetType() == typeof(BuildingRestaurant))
                {
                    restaurantTiles.Add(tileScript);
                }
            }
            catch
            {
                //tile was deleted
            }
        }
        foreach (WorldTile residential in residentTiles)
        {
            foreach (Pop customer in ((BuildingResidential)residential.building).residents)
            {
                int[] scores        = new int[restaurantTiles.Count];
                int   favoriteScore = 0;
                //Determines favorite restaurant
                for (int i = 0; i < restaurantTiles.Count; i++)
                {
                    //Restrict buying to same district for now
                    if (restaurantTiles[i].building.tile.district == residential.district)
                    {
                        List <DishCategory>     foodCategories = new List <DishCategory>();
                        List <RecipeIngredient> ingredients    = new List <RecipeIngredient>();
                        List <RestaurantRecipe> recipes        = ((BuildingRestaurant)restaurantTiles[i].building).recipes;
                        double averageDishCost = 0;
                        for (int j = 0; j < recipes.Count; j++)
                        {
                            averageDishCost += recipes[j].sellingPrice;
                            if (!foodCategories.Contains(recipes[j].recipe.dishCategory))
                            {
                                foodCategories.Add(recipes[j].recipe.dishCategory);
                            }
                            foreach (TieredIngredient ti in recipes[j].recipe.ingredients)
                            {
                                if (!ingredients.Contains(ti.ingredient))
                                {
                                    ingredients.Add(ti.ingredient);
                                }
                                if (ti.ingredient == customer.favoriteIngredient)
                                {
                                    favoriteScore++;
                                }
                            }

                            if (((BuildingRestaurant)restaurantTiles[i].building).GetTechUpgrades().Contains(Tech.RECIPE_BOOST))
                            {
                                favoriteScore++;
                            }
                        }
                        averageDishCost = averageDishCost / recipes.Count;

                        //Score based off customer preference
                        int prefScore = 0;
                        if (customer.preference == FoodPreference.NONE)
                        {
                            prefScore = 2;
                        }
                        else if (!foodCategories.Contains(Pop.ToCategory(customer.preference)))
                        {
                            prefScore = 1;
                        }
                        else if (foodCategories.Contains(Pop.ToCategory(customer.preference)) && foodCategories.Count == 1)
                        {
                            prefScore = 4;
                        }
                        else
                        {
                            prefScore = 3;
                        }

                        //Income vs price
                        int         priceScore = 0;
                        IncomeLevel restaurantCost;
                        if (priceScore <= moderateDishCostThreshold)
                        {
                            restaurantCost = IncomeLevel.LOW;
                        }
                        else if (priceScore <= expensiveDishCostThreshold)
                        {
                            restaurantCost = IncomeLevel.MIDDLE;
                        }
                        else
                        {
                            restaurantCost = IncomeLevel.HIGH;
                        }

                        if (restaurantCost == customer.income)
                        {
                            if (restaurantCost == IncomeLevel.MIDDLE)
                            {
                                priceScore = 3;
                            }
                            else
                            {
                                priceScore = 4;
                            }
                        }
                        else if ((restaurantCost == IncomeLevel.HIGH && customer.income == IncomeLevel.LOW) || (restaurantCost == IncomeLevel.LOW && customer.income == IncomeLevel.HIGH))
                        {
                            priceScore = 0;
                        }
                        else
                        {
                            priceScore = 1;
                        }
                        if (((BuildingRestaurant)restaurantTiles[i].building).GetTechUpgrades().Contains(Tech.EXPENSIVE_CLIENTLE))
                        {
                            priceScore += 4;
                        }

                        //todo - accurate distance
                        int distScore = 0;
                        if (restaurantTiles[i].building.tile.district == residential.district)
                        {
                            distScore += 4;
                        }
                        else
                        {
                            if (((BuildingRestaurant)restaurantTiles[i].building).GetTechUpgrades().Contains(Tech.SAUCE_BAR))
                            {
                                distScore += 2;
                            }
                            if (((BuildingRestaurant)restaurantTiles[i].building).GetTechUpgrades().Contains(Tech.CATERING))
                            {
                                distScore += 2;
                            }
                        }

                        int aversionScore = 0;
                        if (customer.hatedIngredient != RecipeIngredient.EMPTY && ingredients.Contains(customer.hatedIngredient))
                        {
                            aversionScore -= 4;
                        }
                        if (((BuildingRestaurant)restaurantTiles[i].building).GetTechUpgrades().Contains(Tech.AMBIENT_MUSIC))
                        {
                            aversionScore += 2;
                        }

                        scores[i] = Mathf.Max(0, favoriteScore + prefScore + priceScore + distScore + aversionScore + Mathf.RoundToInt((float)((BuildingRestaurant)restaurantTiles[i].building).GetRating()));
                    }
                }

                /*
                 #region temporary winner selection
                 * int bestScore = -100;
                 * int bestIndex = -1;
                 * for (int i = 0; i < score.Length; i++)
                 * {
                 *  if (score[i] > bestScore)
                 *  {
                 *      bestIndex = i;
                 *      bestScore = score[i];
                 *  }
                 * }
                 #endregion
                 */

                #region Chance-based winner selection
                int baseStayIn  = 22;
                int totalPoints = baseStayIn;
                foreach (int sc in scores)
                {
                    totalPoints += sc;
                }

                int bestIndex = -1;
                int roll      = Random.Range(0, totalPoints) + 1;


                int cumulativeSeek = 0;
                for (int i = 0; i < scores.Length; i++)
                {
                    cumulativeSeek += scores[i];
                    if (cumulativeSeek >= roll)
                    {
                        bestIndex = i;
                    }
                }
                #endregion



                if (bestIndex > -1)
                {
                    List <RestaurantRecipe> winners = ((BuildingRestaurant)restaurantTiles[bestIndex].building).recipes;
                    //Added 0.1 tech per customer due to upgrade
                    if (((BuildingRestaurant)restaurantTiles[bestIndex].building).GetTechUpgrades().Contains(Tech.PLACE_HOLDER))
                    {
                        GameController.Instance().activePlayer.AddTechPointRate(1);
                    }
                    //Perhaps fixes permanent "please wait"
                    if (winners.Count > 0)
                    {
                        int buy = Random.Range(0, winners.Count);
                        if (((BuildingRestaurant)restaurantTiles[bestIndex].building).GetTechUpgrades().Contains(Tech.SUPER_SIZE))
                        {
                            if (Random.Range(1, 5) == 4)
                            {
                                winners[buy].quantitySold++;
                                Debug.Log("You got an extra sold from Super size tech");
                            }
                        }
                        //calculate review then add it to the restaurant
                        ((BuildingRestaurant)restaurantTiles[bestIndex].building).AddReview(winners[buy].CalculateReview());
                        winners[buy].quantitySold++;
                        Debug.Log("bought " + winners[buy].recipe.name);
                    }
                }
            }
        }
    }
Beispiel #23
0
 public TileInfo(TileState _state, WorldTile _tile, Vector2 pos)
 {
     m_tile  = _tile;
     m_state = _state;
     m_pos   = pos;
 }