Purring Pixels Shop System

PHOTO EMBED

Fri Jun 21 2024 07:41:40 GMT+0000 (Coordinated Universal Time)

Saved by @mry2khuu #c# #shopsystem #json

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ShopSystem : MonoBehaviour
{
    public enum ItemStatus
    {
        PURCHASEABLE,
        NOT_IN_USE,
        IN_USE
    }

    [SerializeField] int curr_Wallpaper;
    [SerializeField] int curr_Floor;
    [SerializeField] int curr_Couch;
    [SerializeField] int curr_CatTree;

    [SerializeField] GameManager gm;

    // the in-game items that will change
    [SerializeField] Image WallpaperImage;
    [SerializeField] Image FloorImage;
    [SerializeField] Image CouchImage;
    [SerializeField] Image CatTreeImage;

    [System.Serializable] public class ShopItem
    {
        public Sprite Icon;
        public int Paws;
        public bool IsPurchased = false;
        public ItemStatus status = ItemStatus.PURCHASEABLE;
    }

    // can be edited in the scrollview component of the inspector
    [SerializeField] List<ShopItem> WallpaperList;
    [SerializeField] List<ShopItem> FloorList;
    [SerializeField] List<ShopItem> CouchList;
    [SerializeField] List<ShopItem> CatTreeList;

    GameObject ItemTemplate;
    GameObject g;

    [SerializeField] GameObject Wallpaper;
    [SerializeField] GameObject Floor;
    [SerializeField] GameObject Couch;
    [SerializeField] GameObject CatTree;

    [SerializeField] Transform WallpaperContent;
    [SerializeField] Transform FloorContent;
    [SerializeField] Transform CouchContent;
    [SerializeField] Transform CatTreeContent;

    Button buyButton;

    public enum ShopTabs
    {
        WALLPAPER,
        FLOOR,
        COUCH,
        CAT_TREE
    }

    [SerializeField] Button wallpaperButton;
    [SerializeField] Button floorButton;
    [SerializeField] Button couchButton;
    [SerializeField] Button catTreeButton;

    private string saveFilePath;

    void Awake()
    {
        saveFilePath = Path.Combine(Application.persistentDataPath, "ShopData.json");
    }

    void Start()
    {
        // set up for whenever the tab buttons are pressed
        wallpaperButton.AddEventListener(ShopTabs.WALLPAPER, OnShopTabButtonClicked);
        floorButton.AddEventListener(ShopTabs.FLOOR, OnShopTabButtonClicked);
        couchButton.AddEventListener(ShopTabs.COUCH, OnShopTabButtonClicked);
        catTreeButton.AddEventListener(ShopTabs.CAT_TREE, OnShopTabButtonClicked);

        // call functions to create shop
        LoadShopData(); // reads data from json file
        PopulateShop(); // creates the items

        // allows data from previous play through to be read on game start up
        gm.CloseShopPage();

        // link up assets
        WallpaperImage.sprite = WallpaperList[curr_Wallpaper].Icon;
        FloorImage.sprite = FloorList[curr_Floor].Icon;
        CouchImage.sprite = CouchList[curr_Couch].Icon;
        CatTreeImage.sprite = CatTreeList[curr_CatTree].Icon;
    }

    public void PopulateShop()
    {

        // get the template for reference
        ItemTemplate = WallpaperContent.GetChild(0).gameObject;

        // create specific items for each tab
        curr_Wallpaper = PopulateItems(WallpaperList, WallpaperContent, curr_Wallpaper, WallpaperImage);
        curr_Floor = PopulateItems(FloorList, FloorContent, curr_Floor, FloorImage);
        curr_Couch = PopulateItems(CouchList, CouchContent, curr_Couch, CouchImage);
        curr_CatTree = PopulateItems(CatTreeList, CatTreeContent, curr_CatTree, CatTreeImage);

        // destroy template after creating items
        Destroy(ItemTemplate);
    }

    int PopulateItems(List<ShopItem> itemList, Transform content, int currentItem, Image image)
    {
        // get amount of items in the list that exists
        int amountOfItems = itemList.Count;
        for (int i = 0; i < amountOfItems; i++)
        {
            // use template to create the item
            g = Instantiate(ItemTemplate, content);
            if (itemList[i] != null)
            {
                //set icon of the item being constructed
                g.transform.GetChild(0).GetComponent<Image>().sprite = itemList[i].Icon;
            }
            // set cost of the item
            g.transform.GetChild(1).GetChild(0).GetComponent<TextMeshProUGUI>().text = itemList[i].Paws.ToString();
            // get the buy button
            buyButton = g.transform.GetChild(2).GetComponent<Button>();

            if (itemList[i].status == ItemStatus.PURCHASEABLE)
            {
                // item is interactable if not yet purchased
                buyButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "BUY";
                buyButton.interactable = true;
            }
            else if (itemList[i].status == ItemStatus.NOT_IN_USE)
            {
                // item is also interactable if not currently in use
                buyButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "NOT IN USE";
                buyButton.interactable = true;
            }
            else if (itemList[i].status == ItemStatus.IN_USE)
            {
                // NOT interactable if already being used
                buyButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "IN USE";
                buyButton.interactable = false;
                currentItem = i;
                image.sprite = content.GetChild(currentItem).GetChild(0).GetComponent<Image>().sprite;
            }
            
            int index = i;
            // add a listener to the buy button
            buyButton.onClick.AddListener(() => OnShopItemButtonClicked(index, itemList, content, image, ref currentItem));
        }

        return currentItem;
    }

    void Update()
    {
        if (wallpaperButton.interactable == false)
        {
            // only look at wallpaper section
            Wallpaper.SetActive(true);
            Floor.SetActive(false);
            Couch.SetActive(false);
            CatTree.SetActive(false);
        }
        else if (floorButton.interactable == false)
        {
            // only look at floor section
            Wallpaper.SetActive(false);
            Floor.SetActive(true);
            Couch.SetActive(false);
            CatTree.SetActive(false);
        }
        else if (couchButton.interactable == false)
        {
            // only look at couch section
            Wallpaper.SetActive(false);
            Floor.SetActive(false);
            Couch.SetActive(true);
            CatTree.SetActive(false);

        }
        else if (catTreeButton.interactable == false)
        {
            // only look at cat tree section
            Wallpaper.SetActive(false);
            Floor.SetActive(false);
            Couch.SetActive(false);
            CatTree.SetActive(true);
        }
    }

    void OnShopItemButtonClicked(int itemIndex, List<ShopItem> itemList, Transform content, Image image, ref int curr_item)
    {
        // player has enough paws and item can be bought
        if (gm.GetPaws() >= itemList[itemIndex].Paws && itemList[itemIndex].status == ItemStatus.PURCHASEABLE)
        {
            // charge player paws
            gm.LosePaws(itemList[itemIndex].Paws);
            //purchase item
            itemList[itemIndex].IsPurchased = true;

            // get buy button of the item and change status to reflect action
            buyButton = content.GetChild(itemIndex).GetChild(2).GetComponent<Button>();
            buyButton.interactable = true;
            buyButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "NOT IN USE";
            itemList[itemIndex].status = ItemStatus.NOT_IN_USE;
        }
        else if (itemList[itemIndex].status == ItemStatus.NOT_IN_USE)
        {
            // revert the status for the one previously in use
            for (int i = 0; i < itemList.Count; i++)
            {
                // if it says in use and is not the one player just picked
                if (itemList[i].status == ItemStatus.IN_USE)
                {
                    itemList[i].status = ItemStatus.NOT_IN_USE;
                    // change button settings
                    buyButton = content.GetChild(i).GetChild(2).GetComponent<Button>();
                    buyButton.interactable = true;
                    buyButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "NOT IN USE";
                }
            }

            // set the item to IN USE
            itemList[itemIndex].status = ItemStatus.IN_USE;
            buyButton = content.GetChild(itemIndex).GetChild(2).GetComponent<Button>();
            // player can no longer interact with this button
            buyButton.interactable = false;
            buyButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "IN USE";
            curr_item = itemIndex;
            // change wallpaper of the game
            // get the Icon image of the item listing
            image.sprite = content.GetChild(itemIndex).GetChild(0).GetComponent<Image>().sprite;
            SaveShopData();
        }
    }

    void OnShopTabButtonClicked(ShopTabs tabNum)
    {
        if (tabNum == ShopTabs.WALLPAPER)
        {
            wallpaperButton.interactable = false;
            floorButton.interactable = true;
            couchButton.interactable = true;
            catTreeButton.interactable = true;
        }
        else if (tabNum == ShopTabs.FLOOR)
        {
            wallpaperButton.interactable = true;
            floorButton.interactable = false;
            couchButton.interactable = true;
            catTreeButton.interactable = true;
        }
        else if (tabNum == ShopTabs.COUCH)
        {
            wallpaperButton.interactable = true;
            floorButton.interactable = true;
            couchButton.interactable = false;
            catTreeButton.interactable = true;
        }
        else if (tabNum == ShopTabs.CAT_TREE)
        {
            wallpaperButton.interactable = true;
            floorButton.interactable = true;
            couchButton.interactable = true;
            catTreeButton.interactable = false;
        }
    }

    // save data into json file
    public void SaveShopData()
    {
        ShopData data = new ShopData();

        // which item is currently in use
        data.curr_Wallpaper = curr_Wallpaper;
        data.curr_Floor = curr_Floor;
        data.curr_Couch = curr_Couch;
        data.curr_CatTree = curr_CatTree;

        foreach (var item in WallpaperList)
        {
            data.WallpaperList.Add(new ShopItemData(GetIconPath(ShopTabs.WALLPAPER, item.Icon), item.Paws, item.IsPurchased, item.status));
        }
        foreach (var item in FloorList)
        {
            data.FloorList.Add(new ShopItemData(GetIconPath(ShopTabs.FLOOR, item.Icon), item.Paws, item.IsPurchased, item.status));
        }
        foreach (var item in CouchList)
        {
            data.CouchList.Add(new ShopItemData(GetIconPath(ShopTabs.COUCH, item.Icon), item.Paws, item.IsPurchased, item.status));
        }
        foreach (var item in CatTreeList)
        {
            data.CatTreeList.Add(new ShopItemData(GetIconPath(ShopTabs.CAT_TREE, item.Icon), item.Paws, item.IsPurchased, item.status));
        }

        // write all the lists into json file
        string shopData = JsonUtility.ToJson(data, true);
        File.WriteAllText(saveFilePath, shopData);
    }

    private string GetIconPath(ShopTabs itemType, Sprite icon)
    {
        if (icon != null)
        {
            if (itemType == ShopTabs.WALLPAPER)
            {
                return "Shop_Wallpaper/" + icon.name;
            }
            else if (itemType == ShopTabs.FLOOR)
            {
                return "Shop_Floor/" + icon.name;
            }
            else if (itemType == ShopTabs.COUCH)
            {
                return "Shop_Couch/" + icon.name;
            }
            else if (itemType == ShopTabs.CAT_TREE)
            {
                return "Shop_CatTree/" + icon.name;
            }
        }
        return "";
    }

    // load in shop data 
    public void LoadShopData()
    {
        // check if file exists to pull from
        if (File.Exists(saveFilePath))
        {
            //read in pre-existing data if it exists
            string json = File.ReadAllText(saveFilePath);
            ShopData data = JsonUtility.FromJson<ShopData>(json);

            curr_Wallpaper = data.curr_Wallpaper;
            curr_Floor = data.curr_Floor;
            curr_Couch = data.curr_Couch;
            curr_CatTree = data.curr_CatTree;

            // fill in for wallpaper list
            WallpaperList = new List<ShopItem>();
            foreach (var itemData in data.WallpaperList)
            {
                // load the sprite in using the icon path
                var sprite = Resources.Load<Sprite>(itemData.IconPath);
                var item = new ShopItem() { Icon = sprite, Paws = itemData.Paws, IsPurchased = itemData.IsPurchased, status = (ItemStatus)System.Enum.Parse(typeof(ItemStatus), itemData.Status) };
                WallpaperList.Add(item);
            }

            // fill in for floor list
            FloorList = new List<ShopItem>();
            foreach (var itemData in data.FloorList)
            {
                // load the sprite in using the icon path
                var sprite = Resources.Load<Sprite>(itemData.IconPath);
                var item = new ShopItem() { Icon = sprite, Paws = itemData.Paws, IsPurchased = itemData.IsPurchased, status = (ItemStatus)System.Enum.Parse(typeof(ItemStatus), itemData.Status) };
                FloorList.Add(item);
            }

            CouchList = new List<ShopItem>();
            foreach (var itemData in data.CouchList)
            {
                var sprite = Resources.Load<Sprite>(itemData.IconPath);
                var item = new ShopItem() { Icon = sprite, Paws = itemData.Paws, IsPurchased = itemData.IsPurchased, status = (ItemStatus)System.Enum.Parse(typeof(ItemStatus), itemData.Status) };
                CouchList.Add(item);
            }

            CatTreeList = new List<ShopItem>();
            foreach (var itemData in data.CatTreeList)
            {
                var sprite = Resources.Load<Sprite>(itemData.IconPath);
                var item = new ShopItem() { Icon = sprite, Paws = itemData.Paws, IsPurchased = itemData.IsPurchased, status = (ItemStatus)System.Enum.Parse(typeof(ItemStatus), itemData.Status) };
                CatTreeList.Add(item);
            }
        }
        else
        {
            // create json file if it doesnt exist
            SaveShopData();
        }
    }

    void OnApplicationQuit()
    {
        // save current data to json file
        SaveShopData();
    }
}
content_copyCOPY