123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330 |
- using Newtonsoft.Json;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using Unity.VisualScripting;
- using UnityEngine;
- using UnityEngine.SceneManagement;
- using UnityEngine.SocialPlatforms.Impl;
- using UnityEngine.UIElements;
- /* 这个controller 是用于控制 Shopping UI菜单的
- */
- public class ShoppingController : MonoBehaviour
- {
- // Start is called before the first frame update
- // 主页面元素
- private Button foodButton, toyButton, otherButton, backButton;
- private Label coinQty;
- private List<ItemInShop> shoppingItems = new();
- private VisualElement itemListView;
- //弹窗元素
- private Button yesButton, noButton;
- private Label msgBody;
- private VisualElement msgRoot, msgField;
- // 选中的产品
- private string selectedItemId, selectedItemDesc, selectedItemPrice;
- void OnEnable()
- {
- // 基层元素获取
- var root = GetComponent<UIDocument>().rootVisualElement;
- var mainManu = root.Q<VisualElement>("mainManu");
- itemListView = root.Q<VisualElement>("itemListView");
- foodButton = mainManu.Q<Button>("food");
- foodButton.clicked += () => TabSwitch(foodButton);
- toyButton = mainManu.Q<Button>("toy");
- toyButton.clicked += () => TabSwitch(toyButton);
- otherButton = mainManu.Q<Button>("other");
- otherButton.clicked += () => TabSwitch(otherButton);
- var coinArea = root.Q<VisualElement>("coinArea");
- coinQty = coinArea.Q<Label>("coinQty");
- backButton = root.Q<Button>("back");
- // 绑定事件
- backButton.clicked += BackBtnClick;
- // 弹窗元素获取
- msgRoot = root.Q<VisualElement>("msgRoot");
- msgField = msgRoot.Q<VisualElement>("msgField");
- msgBody = msgField.Q<Label>("msgBody");
- yesButton = msgField.Q<Button>("msgYes");
- noButton = msgField.Q<Button>("msgNo");
- noButton.clicked += MsgNoClick;
- yesButton.clicked += MsgYesClick;
- //初始化设定
- LanguageSetting();
- DataLoading();
- GetItemList("food");
- foodButton.transform.scale = new Vector3(1.2f, 1.2f);
- InstallItems("food");
- }
- private void OnDisable()
- {
- shoppingItems.Clear(); // 因为启动时候调用OnEable数据会被重复加载
- }
- // Update is called once per frame
- //void Update()
- //{
- //}
- //菜单语言设定
- void LanguageSetting()
- {
- // 设置 shopping UI界面里面label和按键的语言显示
- string textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "shoppingUI", "button", "food", EnviromentSetting.languageCode });
- foodButton.text = textValue;
- textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "shoppingUI", "button", "toy", EnviromentSetting.languageCode });
- toyButton.text = textValue;
- textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "shoppingUI", "button", "other", EnviromentSetting.languageCode });
- otherButton.text = textValue;
- textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "shoppingUI", "button", "back", EnviromentSetting.languageCode });
- backButton.text = textValue;
- textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "shoppingUI", "button", "yes", EnviromentSetting.languageCode });
- yesButton.text = textValue;
- textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "shoppingUI", "button", "no", EnviromentSetting.languageCode });
- noButton.text = textValue;
- }
- /*获取所有产品列表,切换商品分类之后,需要重新读取和加载
- */
- void GetItemList(string type)
- {
- // 按照类别获取shopping items
- shoppingItems.Clear();
- string itemRawData = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "item", type});
- Dictionary<string, object> itemDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(itemRawData);
- foreach (string _item in itemDict.Keys)
- {
- var itemDetail = JsonConvert.DeserializeObject<Dictionary<string, object>>(itemDict[_item].ToString());
- string price = itemDetail["price"].ToString();
- string picture = itemDetail["picture"].ToString();
- var desc = JsonConvert.DeserializeObject<Dictionary<string, object>>(itemDetail["description"].ToString());
- string description = desc[EnviromentSetting.languageCode].ToString();
- // 检测toy是否达到最大可以拥有的数量,如果达到就不再添加
- if (type == "toy")
- {
- if(!UserProperty.toy.TryGetValue(_item, out int qty))
- {
- // 如果用户没有这个道具,就商品里面添加这个道具
-
- ItemInShop SearchedItem = new(_item, description, price, picture);
- shoppingItems.Add(SearchedItem);
- }
- else
- {
- // 如果用户有这个,并且拥有数量小于最大值,就商品里面添加这个道具
- if (qty < int.Parse(itemDetail["max qty"].ToString()))
- {
- ItemInShop SearchedItem = new(_item, description, price, picture);
- shoppingItems.Add(SearchedItem);
- }
- }
- }
- // 检测food是否达到最大可以拥有的数量,如果达到就不再添加
- if (type == "food")
- {
- if (!UserProperty.food.TryGetValue(_item, out int qty))
- {
- // 如果用户没有这个道具,就商品里面添加这个道具
- ItemInShop SearchedItem = new(_item, description, price, picture);
- shoppingItems.Add(SearchedItem);
- }
- else
- {
- // 如果用户有这个,并且拥有数量小于最大值,就商品里面添加这个道具
- if (qty < int.Parse(itemDetail["max qty"].ToString()))
- {
- ItemInShop SearchedItem = new(_item, description, price, picture);
- shoppingItems.Add(SearchedItem);
- }
- }
- }
- // 检测other是否达到最大可以拥有的数量,如果达到就不再添加
- if (type == "other")
- {
- if (!UserProperty.other.TryGetValue(_item, out int qty))
- {
- // 如果用户没有这个道具,就商品里面添加这个道具
- ItemInShop SearchedItem = new(_item, description, price, picture);
- shoppingItems.Add(SearchedItem);
- }
- else
- {
- // 如果用户有这个,并且拥有数量小于最大值,就商品里面添加这个道具
- if (qty < int.Parse(itemDetail["max qty"].ToString()))
- {
- ItemInShop SearchedItem = new(_item, description, price, picture);
- shoppingItems.Add(SearchedItem);
- }
- }
- }
- }
- }
- // 将items装载到菜单中,切换商品分类之后,需要重新读取和加载
- void InstallItems(string type)
- {
- var root = GetComponent<UIDocument>().rootVisualElement;
- itemListView.Clear();
- VisualTreeAsset itemResource = Resources.Load<VisualTreeAsset>("Shopping/Item");
- List<ItemInShop> items = new();
- foreach(var item in shoppingItems)
- {
- var itemFrame = new VisualElement();
- itemFrame = itemResource.CloneTree();
- var description = itemFrame.Q<Label>("description");
- description.text = item.description;
- var price = itemFrame.Q<Label>("price");
- price.text = "$ "+item.price;
- var texture = Resources.Load<Texture2D>(item.picture);
- var picture = itemFrame.Q<VisualElement>("picture");
- picture.style.backgroundImage = new StyleBackground(texture);
- itemFrame.RegisterCallback<ClickEvent>(e => ItemClick(e, item.id, item.description, item.price));
- itemListView.Add(itemFrame);
- }
- }
- // 点击商品后跳出确认窗口
- void ItemClick(ClickEvent clickEvent, string itemId, string description, string price)
- {
- selectedItemId = itemId;
- selectedItemDesc = description;
- selectedItemPrice = price;
- msgBody.text = description;
- msgRoot.visible = true;
- }
- // 数据读取
- void DataLoading()
- {
- // 游戏金币数量读取
- coinQty.text = UserProperty.coin.ToString();
- }
-
- void TabSwitch(Button btn)
- {
- itemListView.style.backgroundColor = btn.resolvedStyle.backgroundColor;
- foodButton.transform.scale = new Vector3(1f, 1f, 1);
- toyButton.transform.scale = new Vector3(1f, 1f, 1);
- otherButton.transform.scale = new Vector3(1f, 1f, 1);
- btn.transform.scale = new Vector3(1.2f, 1.2f, 1);
- itemListView.Clear();
- HomeSoundEffectController.Instance.PlaySoundEffect(0);
- // 这里btn.name必须和json里面商品类别完全匹配
- GetItemList(btn.name);
- InstallItems(btn.name);
-
- }
- // msg no button 点击
- void MsgNoClick()
- {
- msgRoot.visible = false;
- }
- // msg yes button 点击
- void MsgYesClick()
- {
-
- Debug.Log("msg yes clicked");
- msgRoot.visible = false;
- // 检测用户金币是否足够
- if (UserProperty.coin > int.Parse(selectedItemPrice))
- {
- PurchaseItemRequest(selectedItemId);
- }
- else
- {
- string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "shoppingUI", "message", "not_enough_coin", EnviromentSetting.languageCode });
- MessageBoxController.ShowMessage(msg);
- }
- }
- void BackBtnClick()
- {
- HomeSoundEffectController.Instance.PlaySoundEffect(2);
- var uiPlaceholder = GameObject.Find("UI Placeholder");
- if (uiPlaceholder != null)
- {
- var shoppingUI = uiPlaceholder.transform.Find("ShoppingUI").gameObject;
- var vamUI = uiPlaceholder.transform.Find("VoiceAndMenu").gameObject;
- shoppingUI.SetActive(false);
- vamUI.SetActive(true);
- }
- }
- // 购物request
- void PurchaseItemRequest(string itemId)
- {
- Debug.Log("Purchase item request");
- string url = "/api/item/puchase/";
- WWWForm form = new();
- form.AddField("user_id", UserProperty.userId);
- form.AddField("item_id", itemId);
- form.AddField("qty", 1);
- StartCoroutine(WebController.PostRequest(url, form, callback: PurchaseItemCallback));
- }
- void PurchaseItemCallback(string json)
- {
- var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
- if (data != null && data["status"].ToString() == "success")
- {
- HomeSoundEffectController.Instance.PlaySoundEffect(3);
- // 重新写入用户数据
- string userInfo = data["user_info"].ToString();
- UserProperty.FreshUserInfo(userInfo);
- // TODO 然后重新写入道具数据
- UserProperty.food.Clear();
- UserProperty.toy.Clear();
- UserProperty.other.Clear();
- // 弹出窗户提示购买成功
- string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "shoppingUI", "message", "purchase_success", EnviromentSetting.languageCode });
- msg = msg.Replace("<<item_name>>", selectedItemDesc);
- MessageBoxController.ShowMessage(msg);
- }
- else
- {
- Debug.Log(data["message"]);
- }
- }
- }
- public class ItemInShop
- {
- public string id;
- public string description;
- public string picture;
- public string price;
- public ItemInShop(string id, string desc, string price, string picture) {
- this.id = id;
- this.description = desc;
- this.price = price;
- this.picture = picture;
- }
- }
|