Unity 防沉迷逻辑

下面两个类放到项目中,实现IAntiAddictedServices接口就能用
1.AntiAddictedController .cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Achonor.AntiAddicted
{
    public class AntiAddictedController : MonoBehaviour
    {
        public static AntiAddictedController Instance = null;

        private IAntiAddictedServices _antiAddictedServices;

        private DateTime _birthTime = DateTime.MinValue;

        private DateTime _lastCheckHolidayTime = DateTime.MinValue;
        private bool _isHolidayChecking = false;
        private bool _isHoliday = false;

        private DateTime _startGameTime;

        private float _onlineCheckInterval = 0;

        private const string PLAYER_IDCARD = "Player_IDCard";

        private const string PLAYER_NAME = "Player_Name";

        private const string PLAYER_BIRTH = "Player_Birth";

        private const string PLAYER_ONLINE_DURATION = "Player_Online_Duration";

        private const string PLAYER_TODAY_ONLINE_DURATION = "Player_Today_Online_Duration";

        private const string PLAYER_LAST_ONLINE_DATE = "Player_Last_Online_Date";

        private const float ONlINECHECKINTERVAL = 60;

        private string PlayerIDCard {
            get {
                return PlayerPrefs.GetString(PLAYER_IDCARD);
            }
        }

        private string PlayerName {
            get {
                return PlayerPrefs.GetString(PLAYER_NAME);
            }
        }

        private int  PlayerAge {
            get {
                if (DateTime.MinValue == _birthTime) {
                    string birthStr = PlayerPrefs.GetString(PLAYER_BIRTH);
                    if (string.IsNullOrEmpty(birthStr)) {
                        return -1;
                    }
                    DateTime birthTime = new DateTime();
                    if (!DateTime.TryParse(birthStr, out birthTime)) {
                        return -1;
                    }
                    _birthTime = birthTime;
                }
                int year = DateTime.Now.Year - _birthTime.Year;
                if (DateTime.Now < _birthTime.AddYears(year)) {
                    return year - 1;
                }
                return year;
            }
        }

        private bool IsHoliday{
            get {
                if (DateTime.MinValue == _lastCheckHolidayTime) {
                    if (!_isHolidayChecking) {
                        StartCoroutine(RequestHoliday());
                    }
                    return false;
                }
                if (!DateTime.Now.Date.Equals(_lastCheckHolidayTime.Date)) {
                    //重新检测
                    StartCoroutine(RequestHoliday());
                }
                return _isHoliday;
            }
        }

        private float UnderageDurationMax {
            get {
                return _isHoliday ? 10800 : 5400;
            }
        }

        private void Awake() {
            Instance = this;
            DontDestroyOnLoad(this);
        }

        private void Start() {
            _onlineCheckInterval = 0;
            _startGameTime = DateTime.Now;
            StartCoroutine(RequestHoliday());
        }

        private void OnApplicationPause(bool pause) {
            OnApplicationFocus(!pause);
        }

        private void OnApplicationFocus(bool focus) {
            Debug.Log("OnApplicationPause focus = " + focus);
            if (true == focus) {
                //记录开始时间
                _startGameTime = DateTime.Now;
            }
            else if (DateTime.MinValue != _startGameTime) {
                int onlineSeconds = (int)(DateTime.Now - _startGameTime).TotalSeconds;
                Debug.Log("onlineSeconds = " + onlineSeconds);
                Debug.Log("PLAYER_ONLINE_DURATION = " + PlayerPrefs.GetInt(PLAYER_ONLINE_DURATION, 0));
                PlayerPrefs.SetInt(PLAYER_ONLINE_DURATION, PlayerPrefs.GetInt(PLAYER_ONLINE_DURATION, 0) + onlineSeconds);
                DateTime lastOnlineDate = DateTime.Parse(PlayerPrefs.GetString(PLAYER_LAST_ONLINE_DATE, "1970-01-01"));
                if (lastOnlineDate.Date.Equals(DateTime.Now.Date)) {
                    PlayerPrefs.SetInt(PLAYER_TODAY_ONLINE_DURATION, PlayerPrefs.GetInt(PLAYER_TODAY_ONLINE_DURATION, 0) + onlineSeconds);
                }
                else {
                    //今天刚上线
                    PlayerPrefs.SetString(PLAYER_LAST_ONLINE_DATE, DateTime.Now.ToString("yyyy-MM-dd"));
                    PlayerPrefs.SetInt(PLAYER_TODAY_ONLINE_DURATION, onlineSeconds);
                }
                _startGameTime = DateTime.MinValue;
            }
        }


        private void Update() {
            _onlineCheckInterval += Time.unscaledDeltaTime;
            if (_onlineCheckInterval < ONlINECHECKINTERVAL) {
                return;
            }
            _onlineCheckInterval = 0;
            OnlineCheck();
        }


        public void Login<IServices>(Action callback) where IServices : IAntiAddictedServices, new(){
            _antiAddictedServices = new IServices();
            string IDCard = PlayerPrefs.GetString(PLAYER_IDCARD, string.Empty);
            if (OnlineCheck()) {
                if (!string.IsNullOrEmpty(IDCard)) {
                    CallCallback(callback);
                    return;
                }
                OpenLoginUI(callback);
            }
        }

        public void OpenLoginUI(Action callback = null) {
            _antiAddictedServices.OpenLoginUI(delegate(LoginResultType resultType) {
                if (LoginResultType.Register == resultType) {
                    _antiAddictedServices.CloseLoginUI();
                    OpenVerificationUI((result)=> {
                        if (!result) {
                            OpenLoginUI(callback);
                        } else {
                            callback();
                        }
                    });
                }
                else if (LoginResultType.Tourists == resultType) {
                    _antiAddictedServices.CloseLoginUI();
                    CallCallback(callback);
                }
            });
        }

        public void OpenVerificationUI(Action<bool> callback = null) {
            _antiAddictedServices.OpenVerificationUI((VerificationResultType resultType, string IDCard, string name, Action<bool> callback1) => {
                if (VerificationResultType.Closed == resultType) {
                    _antiAddictedServices.CloseVerificationUI();
                    CallCallback(callback, false);
                    CallCallback(callback1, true);
                }
                else if (VerificationResultType.Verification == resultType) {
                    Verification(IDCard, name, (result) => {
                        if (result) {
                            SaveInfo(IDCard, name);
                            _antiAddictedServices.CloseVerificationUI();
                            CallCallback(callback, true);
                            CallCallback(callback1, true);
                        }
                        else {
                            CallCallback(callback1, false);
                        }
                    });
                }
            });
        }

        private bool OnlineCheck() {
            int playerAge = PlayerAge;
            Debug.Log("OnlineCheck playerAge = " + playerAge);
            if (18 <= playerAge) {
                return true;
            }
            int onlineSeconds = (int)(DateTime.Now - _startGameTime).TotalSeconds;
            if (-1 == playerAge) {
                //游客
                int onlineSumDuration = PlayerPrefs.GetInt(PLAYER_ONLINE_DURATION, 0) + onlineSeconds;
                if (3600 < onlineSumDuration) {
                    //需要实名注册
                    OpenVerificationUI();
                    return false;
                }
            }
            else {
                //未成年
                int onlineTodaySumDuration = PlayerPrefs.GetInt(PLAYER_TODAY_ONLINE_DURATION, 0) + onlineSeconds;
                if (UnderageDurationMax < onlineTodaySumDuration) {
                    //达到时长上限
                    _antiAddictedServices.OpenRemindUI(()=> {
                        Application.Quit();
                    });
                    return false;
                }
            }
            return true;
        }

        private void Verification(string IDCard, string name, Action<bool> callback) {
            bool result = false;
            if (15 == IDCard.Length) {
                result = CheckIDCard15(IDCard);
            }
            else if (18 == IDCard.Length) {
                result = CheckIDCard18(IDCard);
            }
            callback(result);
        }

        private void SaveInfo(string IDCard, string name) {
            PlayerPrefs.SetString(PLAYER_IDCARD, IDCard);
            PlayerPrefs.SetString(PLAYER_NAME, name);
            string birthStr = string.Empty;
            if (15 == IDCard.Length) {
                birthStr = IDCard.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            }
            else if (18 == IDCard.Length) {
                birthStr = IDCard.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            }
            PlayerPrefs.SetString(PLAYER_BIRTH, birthStr);
        }


        string _IDAddress = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
        private bool CheckIDCard15(string IDCard) {
            long IDNumber;
            if (long.TryParse(IDCard, out IDNumber) == false || IDNumber < Math.Pow(10, 14)) {
                return false;//数字验证
            }
            if (_IDAddress.IndexOf(IDCard.Remove(2)) == -1) {
                return false;//省份验证
            }
            string birth = IDCard.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false) {
                return false;//生日验证
            }
            return true;//符合15位身份证标准
        }
        private bool CheckIDCard18(string IDCard) {
            long IDNumber = 0;
            if (long.TryParse(IDCard.Remove(17), out IDNumber) == false || IDNumber < Math.Pow(10, 16) 
                || long.TryParse(IDCard.Replace('x', '0').Replace('X', '0'), out IDNumber) == false) {
                return false;//数字验证
            }
            if (_IDAddress.IndexOf(IDCard.Remove(2)) == -1) {
                return false;//省份验证
            }
            string birth = IDCard.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false) {
                return false;//生日验证
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = IDCard.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++) {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != IDCard.Substring(17, 1).ToLower()) {
                return false;//校验码验证
            }
            return true;//符合GB11643-1999标准
        }

        private IEnumerator RequestHoliday() {
            _isHoliday = false;
            _isHolidayChecking = true;
            string dateStr = DateTime.Now.ToString("yyyyMMdd");
            WWW www = new WWW("http://www.easybots.cn/api/holiday.php?d=" + dateStr);
            yield return www;
            _isHolidayChecking = false;
            if (null != www.error) {
                Debug.LogError("PreventAddictedController.RequestHoliday error = " + www.error);
            }
            else {
                _lastCheckHolidayTime = DateTime.Parse(dateStr.Insert(6, "-").Insert(4, "-"));
                Debug.Log(www.text);
                if (-1 == www.text.IndexOf("\"0\"")) {
                    //休息日
                    _isHoliday = true;
                }
            }
        }

        private void CallCallback(Action callback) {
            if (null != callback) {
                callback();
            }
        }
        private void CallCallback(Action<bool> callback, bool value) {
            if (null != callback) {
                callback(value);
            }
        }
    }
}

2.IAntiAddictedServices.cs

using System;
using System.Collections;
using System.Collections.Generic;

namespace Achonor.AntiAddicted {
    public enum LoginResultType {
        Register = 0,   //注册
        Tourists        //游客登陆
    }

    public enum VerificationResultType {
        Closed = 0,
        Verification,
    }

    public interface IAntiAddictedServices{
        void OpenLoginUI(Action<LoginResultType> callback);
        void CloseLoginUI();

        void OpenVerificationUI(Action<VerificationResultType, string, string, Action<bool>> callback);

        void CloseVerificationUI();

        void OpenRemindUI(Action callback);
    }
}
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
/** * 初始化SDK */ private static void initSDK(String appid, String appkey) { ProxySelector defaultProxySelector = ProxySelector.getDefault(); Proxy proxy = null; List<Proxy> proxyList = null; try { proxyList = defaultProxySelector.select(new URI( "http://www.google.it")); } catch (URISyntaxException e) { e.printStackTrace(); } if (proxyList != null && proxyList.size() > 0) { proxy = proxyList.get(0); Log.d(TAG, "Current Proxy Configuration: " + proxy.toString()); } AppInfo appInfo = new AppInfo(); appInfo.setAppId(appid);// 应用ID appInfo.setAppKey(appkey);// 应用Key appInfo.setCtx(ctx); /* * VersionCheckLevelNormal 版本检查失败可以继续进行游戏 VersionCheckLevelStrict * 版本检查失败则不能进入游戏 默认取值为VersionCheckLevelStrict */ appInfo.setVersionCheckStatus(AppInfo.VERSION_CHECK_LEVEL_STRICT); // 初始化SDK Commplatform.getInstance().Init(0, appInfo, new CallbackListener<Integer>() { @Override public void callback(final int paramInt, Integer paramT) { ctx.runOnUiThread(new Runnable() { @Override public void run() { Log.i(TAG, "Init paramInt = " + paramInt); // ok.setEnabled(true); LogUtil.send("初始化: " + paramInt); } }); } }); } /** * 用户登录 * */ public static void loginEx(Context context) { Bundle bundle = new Bundle(); bundle.putString("nounce", UUID.randomUUID().toString() .replace("-", "")); Commplatform.getInstance().LoginEx(context, bundle, new CallbackListener<Bundle>() { @Override public void callback(int resultCode, Bundle bundle) { if (resultCode == ErrorCode.COM_PLATFORM_SUCCESS) { // 完成参数验签 // 处理登录成功逻辑 // HomeActivity.show(ctx); // String uin= bundle.getString("uin"); LogUtil.send("登录成功 :"); // String uin= bundle.get("nounce").toString(); String uin = Commplatform.getInstance() .getLoginUin(); LogUtil.send("登录成功 uin :" + uin); UnityPlayer.UnitySendMessage("MainScript", "HuaweiLoginBack", uin); } else { // 处理登录失败逻辑 LogUtil.send("登录失败"); } } }); } /** * 充值 * */ public static int pay(String currency) { isPaying = true; Payment payment = new Payment(); ProductBean productBean = productMap.get(currency); makeSerial(); payment.setTradeNo(orderKen); payment.setProductId(productBean.getProductId()); payment.setSubject(productBean.getTitle()); payment.setDesc(productBean.getDescription()); payment.setAmount(productBean.getPrice_amount()); payment.setCurrency(productBean.getPrice_currency_code()); payment.setNote(""); payment.setNotifyURL(""); payment.setThirdAppId(id); payment.setThirdAppName("Spot Battle"); payment.setThirdAppPkgname("com.testcrecool.mi"); final String tradeNo = payment.getTradeNo(); final String productId = payment.getProductId(); // 将订单的详细信息插入数据库 PaymentTableAdapter.insert(ctx, payment); int res = Commplatform.getInstance().UniPayExt(payment, ctx, new CallbackListener<PayResult>() { @Override public void callback(final int code, final PayResult arg1) { ctx.runOnUiThread(new Runnable() { public void run() { // 回调结果,即支付过程结束 isPaying = false; LogUtil.send("回调结果,即支付过程结束 code: " + code); if (code == ErrorCode.COM_PLATFORM_SUCCESS) { // TODO Example 1 // 根据final 的 productID 或者 orderId // 去处理商品,比如查询道具,发放道具等 // TODO Example 2 // 可以根据订单号查询订单详细信息,在做订单的处理,比如查询道具,发放道具等 // 如下: Payment payment = PaymentTableAdapter .queryByOrderId(ctx, orderKen); // 购买有结果,即删除此订单号 PaymentTableAdapter.deleteByOrderId(ctx, orderKen); Log.i(TAG, "COM_PLATFORM_SUCCESS"); LogUtil.send("成功"); UnityPlayer.UnitySendMessage("MainScript", "hwPayCallback", orderKen); } else if (code == ErrorCode.COM_PLATFORM_ERROR_PAY_FAILURE) { Log.i(TAG, "COM_PLATFORM_ERROR_PAY_FAILURE"); } else if (code == ErrorCode.COM_PLATFORM_ERROR_PAY_CANCEL) { // 购买失败 // 购买有结果,即删除此订单号 PaymentTableAdapter.deleteByOrderId(ctx, tradeNo); Log.i(TAG, "COM_PLATFORM_ERROR_PAY_CANCEL"); UnityPlayer.UnitySendMessage("MainScript", "hwPayCallback", "error"); } else if (code == ErrorCode.COM_PLATFORM_ERROR_PAY_CANCEL) { LogUtil.send("取消购买"); // 取消购买 // 购买有结果,即删除此订单号 PaymentTableAdapter.deleteByOrderId(ctx, tradeNo); UnityPlayer.UnitySendMessage("MainScript", "hwPayCallback", "error"); } else { LogUtil.send("Purchase failed. Error code:" + code); Log.i(TAG, "COM_PLATFORM_ERROR_UNKNOWN"); } } }); } }); if (res == 0) { LogUtil.send("000"); return 0; } else { // 返回错误,即支付过程结束 isPaying = false; LogUtil.send("返回错误,即支付过程结束"); return -1; } } /** * 获取应用内商品信息 **/ public static void querySkuDetail() { Commplatform.getInstance().getSkuDetails(ctx, new CallbackListener<List<SkuDetail>>() { @Override public void callback(int errorCode, List<SkuDetail> skuDetails) { if (errorCode == ErrorCode.COM_PLATFORM_SUCCESS && skuDetails != null) { for (SkuDetail detail : skuDetails) { ProductBean prBean = new ProductBean(); prBean.setProductId(detail.productId); prBean.setPrice(detail.price); prBean.setPrice_amount(detail.price_amount); prBean.setPrice_currency_code(detail.price_currency_code); prBean.setTitle(detail.title); prBean.setDescription(detail.description); productMap.put(detail.productId, prBean); } // showText.setText(buffer.toString()); LogUtil.send("获取应用内商品信息"); } else { // showText.setText("query error"); LogUtil.send("query error"); } } }); } /** * 生成订单号 * */ private static String makeSerial() { // 生成订单号 orderKen = UUID.randomUUID().toString().replaceAll("-", ""); return orderKen; } // 同步支付订单的漏单查询接口调用 private static void checkPay(final Payment paymentSerial) { QueryPayment queryPayment = new QueryPayment(); queryPayment.setTradeNo(paymentSerial.getTradeNo()); queryPayment.setThirdAppId(paymentSerial.getThirdAppId()); final String tradeNo= queryPayment.getTradeNo(); Commplatform.getInstance().queryPayment(queryPayment, ctx, new CallbackListener<PaymentState>() { @Override public void callback(int paramInt, PaymentState paramT) { if (paramInt == ErrorCode.COM_PLATFORM_SUCCESS) { // Step2:订单查询成功 从数据库删除此订单号 PaymentTableAdapter.deleteByOrderId(ctx,tradeNo); // 订单支付成功,可以根据订单号查询订单详细信息,在做订单的处理,比如查询道具,发放道具等 // TODO… 游戏代码 LogUtil.send("漏单查询成功!!!"); UnityPlayer.UnitySendMessage("MainScript", "hwPayCallback", orderKen); } else if (paramInt == ErrorCode.COM_PLATFORM_ERROR_UNEXIST_ORDER) { // Step2:订单不存在 从数据库删除此订单号 PaymentTableAdapter.deleteByOrderId(ctx, tradeNo); // 根据游戏自身的体验决定如何处理 UnityPlayer.UnitySendMessage("MainScript", "hwPayCallback", "error"); } else if (paramInt == ErrorCode.COM_PLATFORM_ERROR_PAY_FAILURE) { // Step2:订单支付失败 从数据库删除此订单号 PaymentTableAdapter.deleteByOrderId(ctx, tradeNo); // 根据游戏自身的体验决定如何处理 UnityPlayer.UnitySendMessage("MainScript", "hwPayCallback", "error"); } else if (paramInt == ErrorCode.COM_PLATFORM_ERROR_SERVER_RETURN_ERROR) { // Step2:服务端返回错误 从数据库删除此订单号 PaymentTableAdapter.deleteByOrderId(ctx, tradeNo); // 根据游戏自身的体验决定如何处理 UnityPlayer.UnitySendMessage("MainScript", "hwPayCallback", "error"); } else if (paramInt == ErrorCode.COM_PLATFORM_ERROR_PAY_REQUEST_SUBMITTED) { // 订单已提交 // 根据游戏自身的体验决定如何处理 // 后续还需要继续查询 UnityPlayer.UnitySendMessage("MainScript", "hwPayCallback", "error"); } else { // 未知错误 // 根据游戏自身的体验决定如何处理 // 后续还需要继续查询 } } }); }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

achonor

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值