| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- using System;
- using System.Collections.Generic;
- namespace Fateforge
- {
- public sealed class RewardedSlotCoordinator : IDisposable
- {
- readonly IRewardedAdService ads;
- readonly Func<Game> current;
- readonly Action save;
- readonly HashSet<string> closed = new HashSet<string>();
- string opportunityRun;
- AdPurpose opportunityPurpose;
- bool receivedReward;
- public AdRequest Pending { get; private set; }
- public event Action<AdResult> Finished;
- public RewardedSlotCoordinator(IRewardedAdService ads, Func<Game> current, Action save)
- {
- this.ads = ads;
- this.current = current;
- this.save = save;
- ads.Result += Receive;
- }
- internal static bool CanRequest(Game game, AdPurpose purpose)
- {
- if (game == null) return false;
- return purpose == AdPurpose.ShopSlot
- ? game.State.stage == Stage.Shop && !game.State.adSlot
- : purpose == AdPurpose.ExtraCollect && game.State.stage == Stage.ReviveChoice && !game.State.reviveUsed;
- }
- public bool Request(AdPurpose purpose = AdPurpose.ShopSlot)
- {
- var game = current();
- if (Pending != null || !CanRequest(game, purpose) || !ads.Available) return false;
- if (opportunityRun != game.State.id || opportunityPurpose != purpose) closed.Clear();
- opportunityRun = game.State.id;
- opportunityPurpose = purpose;
- receivedReward = false;
- Pending = new AdRequest{runId=opportunityRun, requestId=Guid.NewGuid().ToString("N"), purpose=purpose};
- if (ads.Show(Pending)) return true;
- Pending = null;
- return false;
- }
- void Receive(AdRequest request, AdResult result)
- {
- if (request == null || request.runId != opportunityRun || request.purpose != opportunityPurpose) return;
- bool active = request.requestId == Pending?.requestId;
- if (!active && (result != AdResult.Rewarded || !closed.Remove(request.requestId))) return;
- var game = current();
- if (game == null || game.State.id != request.runId)
- {
- if (active) Pending = null;
- return;
- }
- if (result == AdResult.Rewarded)
- {
- bool granted = request.purpose == AdPurpose.ExtraCollect
- ? game.GrantExtraCollect(request.runId, request.requestId)
- : game.State.stage == Stage.Shop && game.GrantAdSlot(request.runId, request.requestId);
- if (!granted) return;
- // Commit immediately, then release the UI when the covering video closes.
- closed.Clear();
- receivedReward = true;
- save();
- if (Pending == null) Finished?.Invoke(AdResult.Rewarded);
- return;
- }
- if (result == AdResult.AwaitingLateReward && !receivedReward) closed.Add(request.requestId);
- Pending = null;
- Finished?.Invoke(receivedReward ? AdResult.Rewarded : result);
- }
- public void Dispose()
- {
- ads.Result -= Receive;
- Pending = null;
- }
- }
- }
|