Beispiel #1
0
 public Round(int mainGroup, List <ActionUnit> battleUnit)
 {
     UserGroup   = mainGroup;
     BattleUnits = battleUnit;
     CurPhase    = RoundPhase.NotStart;
     StartData   = battleUnit.Select(a => a.CurrentStatus).ToList();
 }
 public void SetPhaseCompleted(RoundPhase phase)
 {
     if (!IsPhaseActionsComleted(phase))
     {
         CompletedPhase = phase;
     }
 }
        public Entity AddRoundPhase(RoundPhase newValue)
        {
            var component = CreateComponent <RoundPhaseComponent>(ComponentIds.RoundPhase);

            component.value = newValue;
            return(AddComponent(ComponentIds.RoundPhase, component));
        }
Beispiel #4
0
        public static RoundPhase GetNextRoundPhase(this RoundPhase phase)
        {
            int phaseInt = (int)phase;

            phaseInt++;
            return((RoundPhase)phaseInt);
        }
Beispiel #5
0
        public static RoundPhase GetNextPhase(this RoundPhase phase)
        {
            var currentPhaseInt = (int)phase;

            currentPhaseInt++;
            return((RoundPhase)currentPhaseInt);
        }
        public IActionResult GetCoinJoin([FromQuery, Required] string uniqueId, [FromQuery, Required] long roundId)
        {
            if (roundId < 0 || !ModelState.IsValid)
            {
                return(BadRequest());
            }

            (CoordinatorRound round, _) = GetRunningRoundAndAliceOrFailureResponse(roundId, uniqueId, RoundPhase.Signing, out IActionResult returnFailureResponse);
            if (returnFailureResponse != null)
            {
                return(returnFailureResponse);
            }

            RoundPhase phase = round.Phase;

            switch (phase)
            {
            case RoundPhase.Signing:
            {
                return(Ok(round.GetUnsignedCoinJoinHex()));
            }

            default:
            {
                TryLogLateRequest(roundId, RoundPhase.Signing);
                return(Conflict($"CoinJoin can only be requested from Signing phase. Current phase: {phase}."));
            }
            }
        }
Beispiel #7
0
 public CardPlayed(RoundPhase roundPhase, PlayerPosition playerPosition, Card card, CardSuit trump)
 {
     RoundPhase     = roundPhase;
     PlayerPosition = playerPosition;
     CardString     = card.ToString();
     Value          = card.GetPointsValue(trump);
 }
Beispiel #8
0
 internal RoundNode(string JSON)
     : base(JSON)
 {
     Phase   = GetEnum <RoundPhase>("phase");
     Bomb    = GetEnum <BombState>("bomb");
     WinTeam = GetEnum <RoundWinTeam>("win_team");
 }
Beispiel #9
0
 internal RoundNode(string JSON)
     : base(JSON)
 {
     Phase = GetEnum<RoundPhase>("phase");
     Bomb = GetEnum<BombState>("bomb");
     WinTeam = GetEnum<RoundWinTeam>("win_team");
 }
        public Entity ReplaceRoundPhase(RoundPhase newValue)
        {
            var component = CreateComponent <RoundPhaseComponent>(ComponentIds.RoundPhase);

            component.value = newValue;
            ReplaceComponent(ComponentIds.RoundPhase, component);
            return(this);
        }
        public async Task <IActionResult> PostConfirmationAsync([FromQuery, Required] string uniqueId, [FromQuery, Required] long roundId)
        {
            if (roundId < 0 || !ModelState.IsValid)
            {
                return(BadRequest());
            }

            (CoordinatorRound round, Alice alice) = GetRunningRoundAndAliceOrFailureResponse(roundId, uniqueId, RoundPhase.ConnectionConfirmation, out IActionResult returnFailureResponse);
            if (returnFailureResponse != null)
            {
                return(returnFailureResponse);
            }

            RoundPhase phase = round.Phase;

            // Start building the response.
            var resp = new ConnectionConfirmationResponse
            {
                CurrentPhase = phase
            };

            switch (phase)
            {
            case RoundPhase.InputRegistration:
            {
                round.StartAliceTimeout(alice.UniqueId);
                break;
            }

            case RoundPhase.ConnectionConfirmation:
            {
                alice.State = AliceState.ConnectionConfirmed;

                int takeBlindCount = round.EstimateBestMixingLevel(alice);

                alice.BlindedOutputScripts    = alice.BlindedOutputScripts.Take(takeBlindCount).ToArray();
                alice.BlindedOutputSignatures = alice.BlindedOutputSignatures.Take(takeBlindCount).ToArray();
                resp.BlindedOutputSignatures  = alice.BlindedOutputSignatures;                                // Do not give back more mixing levels than we'll use.

                // Progress round if needed.
                if (round.AllAlices(AliceState.ConnectionConfirmed))
                {
                    await round.ProgressToOutputRegistrationOrFailAsync();
                }

                break;
            }

            default:
            {
                TryLogLateRequest(roundId, RoundPhase.ConnectionConfirmation);
                return(Gone($"Participation can be only confirmed from InputRegistration or ConnectionConfirmation phase. Current phase: {phase}."));
            }
            }

            return(Ok(resp));
        }
Beispiel #12
0
    //抽牌阶段初始化
    public void DrawRoundStart()
    {
        roundPhase = RoundPhase.Draw;

        if (isMyturn)
        {
            Instantiate(getCardPrefabs, MainCanvas);
        }
    }
Beispiel #13
0
 private bool StartRound()
 {
     CurPhase  = RoundPhase.Battle;
     Result    = RoundResult.NoInfo;
     StartTime = System.DateTime.Now;
     TimeLeft  = RoundTime;
     BattleUnits.ForEach(a => a.BattleMode = true);
     return(true);
 }
Beispiel #14
0
    //游戏初始化赋值
    public void RoundGoingStart()
    {
        roundPhase  = RoundPhase.Preparatory;
        waitCounter = WaitPhase.NoWait;
        roundNum    = 0;

        myPlayer       = GameObject.Find("MainUI").GetComponent <PlayerManager>();
        EnemyPlayer    = GameObject.Find("EnemyUI").GetComponent <PlayerManager>();
        cardCurved     = GameObject.Find("HandCardPrefab").GetComponent <CardCurved>();
        enemyHCurved   = GameObject.Find("EnemyHCPrefab").GetComponent <EnemyHCurved>();
        RoundNumText   = GameObject.Find("RoundNumText").GetComponent <Text>();
        skillButtonGet = GameObject.Find("MainUI").GetComponent <SkillButtonGet>();
        skillManager   = GameObject.Find("SkillManager").GetComponent <SkillManager>();
    }
Beispiel #15
0
    //弃牌阶段初始化
    public void AbandonmentRoundStart()
    {
        roundPhase = RoundPhase.Abandonment;

        if (isMyturn)
        {
            Instantiate(discardTipPrefab, MainCanvas);
            cardCurved.AbandonmentCard();
        }
        else
        {
            enemyHCurved.AbandonmentCard();
        }
    }
        public IActionResult PostUnconfimation([FromQuery, Required] string uniqueId, [FromQuery, Required] long roundId)
        {
            if (roundId < 0 || !ModelState.IsValid)
            {
                return(BadRequest());
            }

            Guid uniqueIdGuid = GetGuidOrFailureResponse(uniqueId, out IActionResult returnFailureResponse);

            if (returnFailureResponse != null)
            {
                return(returnFailureResponse);
            }

            CoordinatorRound round = Coordinator.TryGetRound(roundId);

            if (round is null)
            {
                return(Ok("Round not found."));
            }

            Alice alice = round.TryGetAliceBy(uniqueIdGuid);

            if (alice is null)
            {
                return(Ok("Alice not found."));
            }

            if (round.Status != CoordinatorRoundStatus.Running)
            {
                return(Gone("Round is not running."));
            }

            RoundPhase phase = round.Phase;

            switch (phase)
            {
            case RoundPhase.InputRegistration:
            {
                round.RemoveAlicesBy(uniqueIdGuid);
                return(NoContent());
            }

            default:
            {
                return(Gone($"Participation can be only unconfirmed from InputRegistration phase. Current phase: {phase}."));
            }
            }
        }
 private static void TryLogLateRequest(long roundId, RoundPhase desiredPhase)
 {
     try
     {
         DateTimeOffset ended = CoordinatorRound.PhaseTimeoutLog.TryGet((roundId, desiredPhase));
         if (ended != default)
         {
             Logger.LogInfo($"{DateTime.UtcNow.ToLocalTime():yyyy-MM-dd HH:mm:ss} {desiredPhase} {(int)(DateTimeOffset.UtcNow - ended).TotalSeconds} seconds late.");
         }
     }
     catch (Exception ex)
     {
         Logger.LogDebug(ex);
     }
 }
Beispiel #18
0
        public async Task <IActionResult> PostConfirmationAsync([FromQuery, Required] string uniqueId, [FromQuery, Required] long roundId)
        {
            if (roundId < 0 || !ModelState.IsValid)
            {
                return(BadRequest());
            }

            using (await CoordinatorRound.ConnectionConfirmationLock.LockAsync())
            {
                (CoordinatorRound round, Alice alice) = GetRunningRoundAndAliceOrFailureResponse(roundId, uniqueId, RoundPhase.ConnectionConfirmation, out IActionResult returnFailureResponse);
                if (returnFailureResponse != null)
                {
                    return(returnFailureResponse);
                }

                RoundPhase phase = round.Phase;

                // Start building the response.
                var resp = new ConnectionConfirmationResponse
                {
                    CurrentPhase = phase
                };

                switch (phase)
                {
                case RoundPhase.InputRegistration:
                {
                    round.StartAliceTimeout(alice.UniqueId);
                    break;
                }

                case RoundPhase.ConnectionConfirmation:
                {
                    resp.BlindedOutputSignatures = await round.ConfirmAliceConnectionAsync(alice);

                    break;
                }

                default:
                {
                    TryLogLateRequest(roundId, RoundPhase.ConnectionConfirmation);
                    return(Gone($"Participation can be only confirmed from InputRegistration or ConnectionConfirmation phase. Current phase: {phase}."));
                }
                }

                return(Ok(resp));
            }
        }
Beispiel #19
0
    //准备阶段初始化
    public void PreparatoryRoundStart()
    {
        roundPhase = RoundPhase.Preparatory;

        //回合增加,显示更新
        roundNum++;
        if (roundNum < 10)
        {
            RoundNumText.text = "Round : 0" + roundNum;
        }
        else
        {
            RoundNumText.text = "Round : " + roundNum;
        }

        //回合开始动画,回复行动点
        if (isMyturn)
        {
            Instantiate(StartUI, MainCanvas);
            myPlayer.ApGetToStart();
            myPlayer.BurnDamageIn();
        }
        else
        {
            Instantiate(EnemyStartUI, MainCanvas);
            EnemyPlayer.ApGetToStart();
            EnemyPlayer.BurnDamageIn();
            WaitPrefabOn();
        }

        //挑战者技能
        if (myPlayer.hero.No == 1)
        {
            SkillManager.printSkill("我方挑战者恢复计数器");

            myPlayer.HeroTimer++;
        }
        else if (EnemyPlayer.hero.No == 1)
        {
            SkillManager.printSkill("对方挑战者恢复计数器");
            EnemyPlayer.HeroTimer++;
        }
    }
Beispiel #20
0
    public IEnumerator Restore(float delay)
    {
        yield return(new WaitForSeconds(delay));

        Debug.Log("Battle Unit " + BattleUnits.Count());
        MainMenuControl.Instance.RoundTime = 0;
        BattleUnits.Where(a => a.Group != UserGroup).ToList().ForEach(x => x.Destroy());
        MainUnits.ForEach(a =>
        {
            a.CurrentStatus           = a.SavedStatus;
            a.transform.localPosition = a.SavedStatus.position;
            a.BattleMode = false;
            a.gameObject.SetActive(true);
            a.Revive();
        });
        MainMenuControl.Instance.ShowUserMessage(UserMessageManager.MES_PHASE_PREPARE, 1f);
        BattleUnits = null;
        MainUnits   = null;
        CurPhase    = RoundPhase.End;
        Events.InvokeOnAction(EVENT_RESTORE_DONE);
        yield return(null);
    }
Beispiel #21
0
    public bool EndRound()
    {
        EndData = BattleUnits.Where(x => x.Alive).Select(a => a.CurrentStatus).ToList();
        if (OnlyGroup)
        {
            WinGroup = BattleUnits.Where(x => x.Alive).FirstOrDefault().Group;
            if (UserGroup == WinGroup)
            {
                Result = RoundResult.Win;
                MainMenuControl.Instance.ShowUserMessage(UserMessageManager.MES_WINNER, 1f);
            }
            else
            {
                Result = RoundResult.Lose;
                MainMenuControl.Instance.ShowUserMessage(UserMessageManager.MES_LOSE, 1f);
            }
        }
        else
        {
            MainMenuControl.Instance.ShowUserMessage(UserMessageManager.MES_DRAW, 1f);
            if (EndData.Count == 0)
            {
                Result = RoundResult.DrawBattle;
            }
            else
            {
                Result = RoundResult.DrawTimeout;
            }
        }
        CurPhase = RoundPhase.Result;
        Events.InvokeOnAction(EVENT_RESULT);
        Debug.Log("Battle Unit " + BattleUnits.Count());

        Game.Instance.StartCoroutine(Restore(3f));

        return(true);
    }
Beispiel #22
0
    //结束阶段初始化
    public void EndingRoundStart()
    {
        roundPhase = RoundPhase.Ending;

        //发动效果
        //光之猎手技能发动
        if (myPlayer.hero.No == 4)
        {
            if (myPlayer.HeroTimer > 0)
            {
                SkillManager.printSkill("我方光之猎手使用技能");
                myPlayer.HeroTimer = 0;
                skillManager.SkillEffect(4, true);
            }
        }
        else if (EnemyPlayer.hero.No == 4)
        {
            if (EnemyPlayer.HeroTimer > 0)
            {
                SkillManager.printSkill("对方光之猎手使用技能");
                EnemyPlayer.HeroTimer = 0;
                skillManager.SkillEffect(4, false);
            }
        }

        //回合结束动画
        if (isMyturn)
        {
            Instantiate(EndingUI, MainCanvas);
        }
        else
        {
            Instantiate(EnemyEndingUI, MainCanvas);
            WaitPrefabOff();
        }
    }
        public IActionResult GetCoinJoin([FromQuery, Required] string uniqueId, [FromQuery, Required] long roundId)
        {
            if (roundId < 0 || !ModelState.IsValid)
            {
                return(BadRequest());
            }

            (CoordinatorRound round, _) = GetRunningRoundAndAliceOrFailureResponse(roundId, uniqueId, RoundPhase.Signing, out IActionResult returnFailureResponse);
            if (returnFailureResponse != null)
            {
                return(returnFailureResponse);
            }

            RoundPhase phase = round.Phase;

            switch (phase)
            {
            case RoundPhase.Signing:
            {
                var hex = round.UnsignedCoinJoinHex;
                if (hex is { })
                {
                    return(Ok(hex));
                }
Beispiel #24
0
        public async Task <IActionResult> PostConfirmationAsync([FromQuery, Required] string uniqueId, [FromQuery, Required] long roundId)
        {
            if (roundId < 0 || !ModelState.IsValid)
            {
                return(BadRequest());
            }

            (CoordinatorRound round, Alice alice) = GetRunningRoundAndAliceOrFailureResponse(roundId, uniqueId, RoundPhase.ConnectionConfirmation, out IActionResult returnFailureResponse);
            if (returnFailureResponse != null)
            {
                return(returnFailureResponse);
            }

            RoundPhase phase = round.Phase;

            // Start building the response.
            var resp = new ConnectionConfirmationResponse
            {
                CurrentPhase = phase
            };

            switch (phase)
            {
            case RoundPhase.InputRegistration:
            {
                round.StartAliceTimeout(alice.UniqueId);
                break;
            }

            case RoundPhase.ConnectionConfirmation:
            {
                alice.State = AliceState.ConnectionConfirmed;

                int takeBlindCount = round.EstimateBestMixingLevel(alice);

                alice.BlindedOutputScripts    = alice.BlindedOutputScripts[..takeBlindCount];
Beispiel #25
0
    void movingPhase()
    {
        if(!newPositionPicked)
        {
            newPosition = new Vector3(_player.transform.position.x,_player.transform.position.y - enemySpacing);
            newPositionPicked = true;
        }

        _player.transform.position = Vector3.MoveTowards(_player.transform.position,newPosition,2*Time.deltaTime);

        if(_player.transform.position == newPosition)
        {
            newPositionPicked = false;
            actualRoundPhase = RoundPhase.shooting;
            succesHits--;
        }
    }
        private (CoordinatorRound round, Alice alice) GetRunningRoundAndAliceOrFailureResponse(long roundId, string uniqueId, RoundPhase desiredPhase, out IActionResult returnFailureResponse)
        {
            returnFailureResponse = null;

            Guid uniqueIdGuid = GetGuidOrFailureResponse(uniqueId, out IActionResult guidFail);

            if (guidFail != null)
            {
                returnFailureResponse = guidFail;
                return(null, null);
            }

            CoordinatorRound round = Coordinator.TryGetRound(roundId);

            if (round is null)
            {
                TryLogLateRequest(roundId, desiredPhase);
                returnFailureResponse = NotFound("Round not found.");
                return(null, null);
            }

            Alice alice = round.TryGetAliceBy(uniqueIdGuid);

            if (alice is null)
            {
                returnFailureResponse = NotFound("Alice not found.");
                return(round, null);
            }

            if (round.Status != CoordinatorRoundStatus.Running)
            {
                TryLogLateRequest(roundId, desiredPhase);
                returnFailureResponse = Gone("Round is not running.");
            }

            return(round, alice);
        }
Beispiel #27
0
 public void createBoard()
 {
     energyOnStartWasted = false;
     playerController.resetTempEnergy();
     succesHits = 0;
     actualRoundPhase = RoundPhase.steady;
     playerStartPosition = new Vector3(-2f, 3.5f, 0);
     enemyStartPosition = new Vector3(2, 3.5f, 0);
     createGame();
 }
Beispiel #28
0
 void invokedStartFighting()
 {
     
     if (actualRoundPhase == RoundPhase.steady)
     {
         actualRoundPhase = RoundPhase.evaluating;
     }
     else
         return;
 }
        public async Task <IActionResult> PostSignaturesAsync([FromQuery, Required] string uniqueId, [FromQuery, Required] long roundId, [FromBody, Required] IDictionary <int, string> signatures)
        {
            if (roundId < 0 ||
                !signatures.Any() ||
                signatures.Any(x => x.Key < 0 || string.IsNullOrWhiteSpace(x.Value)) ||
                !ModelState.IsValid)
            {
                return(BadRequest());
            }

            (CoordinatorRound round, Alice alice) = GetRunningRoundAndAliceOrFailureResponse(roundId, uniqueId, RoundPhase.Signing, out IActionResult returnFailureResponse);
            if (returnFailureResponse != null)
            {
                return(returnFailureResponse);
            }

            // Check if Alice provided signature to all her inputs.
            if (signatures.Count != alice.Inputs.Count())
            {
                return(BadRequest("Alice did not provide enough witnesses."));
            }

            RoundPhase phase = round.Phase;

            switch (phase)
            {
            case RoundPhase.Signing:
            {
                using (await SigningLock.LockAsync())
                {
                    foreach (var signaturePair in signatures)
                    {
                        int       index   = signaturePair.Key;
                        WitScript witness = null;
                        try
                        {
                            witness = new WitScript(signaturePair.Value);
                        }
                        catch (Exception ex)
                        {
                            return(BadRequest($"Malformed witness is provided. Details: {ex.Message}"));
                        }
                        int maxIndex = round.UnsignedCoinJoin.Inputs.Count - 1;
                        if (maxIndex < index)
                        {
                            return(BadRequest($"Index out of range. Maximum value: {maxIndex}. Provided value: {index}"));
                        }

                        // Check duplicates.
                        if (round.SignedCoinJoin.Inputs[index].HasWitScript())
                        {
                            return(BadRequest("Input is already signed."));
                        }

                        // Verify witness.
                        // 1. Copy UnsignedCoinJoin.
                        Transaction cjCopy = Transaction.Parse(round.UnsignedCoinJoin.ToHex(), Network);
                        // 2. Sign the copy.
                        cjCopy.Inputs[index].WitScript = witness;
                        // 3. Convert the current input to IndexedTxIn.
                        IndexedTxIn currentIndexedInput = cjCopy.Inputs.AsIndexedInputs().Skip(index).First();
                        // 4. Find the corresponding registered input.
                        Coin registeredCoin = alice.Inputs.Single(x => x.Outpoint == cjCopy.Inputs[index].PrevOut);
                        // 5. Verify if currentIndexedInput is correctly signed, if not, return the specific error.
                        if (!currentIndexedInput.VerifyScript(registeredCoin, out ScriptError error))
                        {
                            return(BadRequest($"Invalid witness is provided. {nameof(ScriptError)}: {error}."));
                        }

                        // Finally add it to our CJ.
                        round.SignedCoinJoin.Inputs[index].WitScript = witness;
                    }

                    alice.State = AliceState.SignedCoinJoin;

                    await round.BroadcastCoinJoinIfFullySignedAsync();
                }

                return(NoContent());
            }

            default:
            {
                TryLogLateRequest(roundId, RoundPhase.Signing);
                return(Conflict($"CoinJoin can only be requested from Signing phase. Current phase: {phase}."));
            }
            }
        }
Beispiel #30
0
 void Start() {
     actualRoundPhase = RoundPhase.steady;
     playerController = GetComponent<PlayerController>();
 }
        public async Task <IActionResult> PostOutputAsync([FromQuery, Required] long roundId, [FromBody, Required] OutputRequest request)
        {
            if (roundId < 0 ||
                request.Level < 0 ||
                !ModelState.IsValid)
            {
                return(BadRequest());
            }

            CoordinatorRound round = Coordinator.TryGetRound(roundId);

            if (round is null)
            {
                TryLogLateRequest(roundId, RoundPhase.OutputRegistration);
                return(NotFound("Round not found."));
            }

            if (round.Status != CoordinatorRoundStatus.Running)
            {
                TryLogLateRequest(roundId, RoundPhase.OutputRegistration);
                return(Gone("Round is not running."));
            }

            RoundPhase phase = round.Phase;

            if (phase != RoundPhase.OutputRegistration)
            {
                TryLogLateRequest(roundId, RoundPhase.OutputRegistration);
                return(Conflict($"Output registration can only be done from OutputRegistration phase. Current phase: {phase}."));
            }

            if (request.OutputAddress.Network != Network)
            {
                // RegTest and TestNet address formats are sometimes the same.
                if (Network == Network.Main)
                {
                    return(BadRequest($"Invalid OutputAddress Network."));
                }
            }

            if (request.OutputAddress == Constants.GetCoordinatorAddress(Network))
            {
                Logger.LogWarning($"Bob is registering the coordinator's address. Address: {request.OutputAddress}, Level: {request.Level}, Signature: {request.UnblindedSignature}.");
            }

            if (request.Level > round.MixingLevels.GetMaxLevel())
            {
                return(BadRequest($"Invalid mixing level is provided. Provided: {request.Level}. Maximum: {round.MixingLevels.GetMaxLevel()}."));
            }

            if (round.ContainsRegisteredUnblindedSignature(request.UnblindedSignature))
            {
                return(NoContent());
            }

            MixingLevel mixinglevel = round.MixingLevels.GetLevel(request.Level);
            Signer      signer      = mixinglevel.Signer;

            if (signer.VerifyUnblindedSignature(request.UnblindedSignature, request.OutputAddress.ScriptPubKey.ToBytes()))
            {
                using (await OutputLock.LockAsync())
                {
                    Bob bob = null;
                    try
                    {
                        bob = new Bob(request.OutputAddress, mixinglevel);
                        round.AddBob(bob);
                        round.AddRegisteredUnblindedSignature(request.UnblindedSignature);
                    }
                    catch (Exception ex)
                    {
                        return(BadRequest($"Invalid outputAddress is provided. Details: {ex.Message}"));
                    }

                    int bobCount      = round.CountBobs();
                    int blindSigCount = round.CountBlindSignatures();
                    if (bobCount == blindSigCount)                     // If there'll be more bobs, then round failed. Someone may broke the crypto.
                    {
                        await round.ExecuteNextPhaseAsync(RoundPhase.Signing);
                    }
                }

                return(NoContent());
            }
            return(BadRequest("Invalid signature provided."));
        }
Beispiel #32
0
    void Update() {

        switch (actualRoundPhase)
        {
            case RoundPhase.steady:
                {
                    if(_player != null)
                    {
                        if (_player.GetComponent<PlayerInFightHandler>().collision && (playerController.actualEnergy <= 0 /* or actual HP <= 0*/))
                        {
                            GetComponent<ScenesManager>().actualSceneState = SceneState.GameOverScene;
                            quitBattle();
                        }
                        else if ((_player.GetComponent<PlayerInFightHandler>().collision))
                        {
                            GetComponent<ScenesManager>().actualSceneState = SceneState.EvaluationScene;
                            quitBattle();
                        }else if(isEnemiesDestroyed())
                        {
                            playerController.convertTempEnergy();
                            GetComponent<ScenesManager>().actualSceneState = SceneState.EvaluationScene;
                            quitBattle();
                        }
                    }
                    return;
                }
            case RoundPhase.evaluating:
                {
                    evaluateFight();
                    break;
                }
            case RoundPhase.shooting:
                {
                    shootingPhase();
                    break;
                }
            case RoundPhase.moving:
                {
                    movingPhase();
                    break;
                }
            case RoundPhase.enemyMove:
                {
                    foreach (GameObject o in GameObject.FindGameObjectsWithTag("Enemy"))
                    {
                        o.GetComponent<EnemyMove>().enemyMoving = true;
                    }
                    setFightButtonActive();
                    actualRoundPhase = RoundPhase.steady;
                    break;
                }
        }
    }
 public bool IsPhaseActionsComleted(RoundPhase phase) => CompletedPhase >= phase;
 /// <summary>
 /// Initializes a new <see cref="RoundPhaseChangedEventArgs"/> instance from the given <see cref="GameState"/>.
 /// </summary>
 /// <param name="gameState">The <see cref="GameState"/> that should be used to initialize this instance.</param>
 public RoundPhaseChangedEventArgs(GameState gameState)
 {
     PreviousPhase = gameState.Previously.Round.Phase;
     CurrentPhase  = gameState.Round.Phase;
 }
Beispiel #35
0
    void evaluateFight()
    {
        evaluationCounterPosition = new Vector3(-1.5f,4.5f);
        pauseTimer -= Time.deltaTime;
        if(pauseTimer <= 0)
        {
            if(Random.Range(0,100) < odds)
            {
                Instantiate(succesFireIcon, new Vector3(evaluationCounterPosition.x + evaluationCounter, evaluationCounterPosition.y), Quaternion.identity);
                succesHits++;
            }else
            {
                Instantiate(failedFireIcon, new Vector3(evaluationCounterPosition.x + evaluationCounter, evaluationCounterPosition.y), Quaternion.identity);
            }
            
            pauseTimer = pauseInterval;
            evaluationCounter++;
        }

        if(evaluationCounter == 4)
        {
            pauseTimer = 0;
            evaluationCounter = 0;
            actualRoundPhase = RoundPhase.shooting; /// change to next phase!! 
        }
    }
Beispiel #36
0
        public async Task BanningTestsAsync()
        {
            (_, IRPCClient rpc, Network network, Coordinator coordinator, _, _, _) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1);

            Money   denomination                  = Money.Coins(0.1m);
            decimal coordinatorFeePercent         = 0.1m;
            int     anonymitySet                  = 3;
            int     connectionConfirmationTimeout = 120;
            var     roundConfig = RegTestFixture.CreateRoundConfig(denomination, 140, 0.7, coordinatorFeePercent, anonymitySet, 240, connectionConfirmationTimeout, 1, 1, 1, 24, true, 11);

            coordinator.RoundConfig.UpdateOrDefault(roundConfig, toFile: true);
            coordinator.AbortAllRoundsInInputRegistration("");

            await rpc.GenerateAsync(3);             // So to make sure we have enough money.

            Uri baseUri                = new Uri(RegTestFixture.BackendEndPoint);
            var fundingTxCount         = 0;
            var inputRegistrationUsers = new List <(Requester requester, BlindedOutputWithNonceIndex blinded, BitcoinAddress activeOutputAddress, BitcoinAddress changeOutputAddress, IEnumerable <InputProofModel> inputProofModels, List <(Key key, BitcoinWitPubKeyAddress address, uint256 txHash, Transaction tx, OutPoint input)> userInputData)>();
            CoordinatorRound round     = null;

            for (int i = 0; i < roundConfig.AnonymitySet; i++)
            {
                var userInputData       = new List <(Key key, BitcoinWitPubKeyAddress inputAddress, uint256 txHash, Transaction tx, OutPoint input)>();
                var activeOutputAddress = new Key().PubKey.GetAddress(ScriptPubKeyType.Segwit, network);
                var changeOutputAddress = new Key().PubKey.GetAddress(ScriptPubKeyType.Segwit, network);
                round = coordinator.GetCurrentInputRegisterableRoundOrDefault();
                Requester requester = new Requester();
                var       nonce     = round.NonceProvider.GetNextNonce();

                var     blinded = new BlindedOutputWithNonceIndex(nonce.N, requester.BlindScript(round.MixingLevels.GetBaseLevel().SignerKey.PubKey, nonce.R, activeOutputAddress.ScriptPubKey));
                uint256 blindedOutputScriptsHash = new uint256(Hashes.SHA256(blinded.BlindedOutput.ToBytes()));

                var inputProofModels  = new List <InputProofModel>();
                int numberOfInputs    = CryptoHelpers.RandomInt(1, 6);
                var receiveSatoshiSum = 0;
                for (int j = 0; j < numberOfInputs; j++)
                {
                    var key            = new Key();
                    var receiveSatoshi = CryptoHelpers.RandomInt(1000, 100000000);
                    receiveSatoshiSum += receiveSatoshi;
                    if (j == numberOfInputs - 1)
                    {
                        receiveSatoshi = 100000000;
                    }
                    BitcoinWitPubKeyAddress inputAddress = key.PubKey.GetSegwitAddress(network);
                    uint256 txHash = await rpc.SendToAddressAsync(inputAddress, Money.Satoshis(receiveSatoshi));

                    fundingTxCount++;
                    Assert.NotNull(txHash);
                    Transaction transaction = await rpc.GetRawTransactionAsync(txHash);

                    var coin = transaction.Outputs.GetCoins(inputAddress.ScriptPubKey).Single();

                    OutPoint input      = coin.Outpoint;
                    var      inputProof = new InputProofModel {
                        Input = input, Proof = key.SignCompact(blindedOutputScriptsHash)
                    };
                    inputProofModels.Add(inputProof);

                    GetTxOutResponse getTxOutResponse = await rpc.GetTxOutAsync(input.Hash, (int)input.N, includeMempool : true);

                    // Check if inputs are unspent.
                    Assert.NotNull(getTxOutResponse);

                    userInputData.Add((key, inputAddress, txHash, transaction, input));
                }

                inputRegistrationUsers.Add((requester, blinded, activeOutputAddress, changeOutputAddress, inputProofModels, userInputData));
            }

            var mempool = await rpc.GetRawMempoolAsync();

            Assert.Equal(inputRegistrationUsers.SelectMany(x => x.userInputData).Count(), mempool.Length);

            while ((await rpc.GetRawMempoolAsync()).Length != 0)
            {
                await rpc.GenerateAsync(1);
            }

            var aliceClients = new List <Task <AliceClient4> >();

            foreach (var user in inputRegistrationUsers)
            {
                aliceClients.Add(AliceClientBase.CreateNewAsync(round.RoundId, new[] { user.activeOutputAddress }, new[] { round.MixingLevels.GetBaseLevel().SignerKey.PubKey }, new[] { user.requester }, network, user.changeOutputAddress, new[] { user.blinded }, user.inputProofModels, BackendHttpClient));
            }

            long roundId = 0;
            var  users   = new List <(Requester requester, BlindedOutputWithNonceIndex blinded, BitcoinAddress activeOutputAddress, BitcoinAddress changeOutputAddress, IEnumerable <InputProofModel> inputProofModels, List <(Key key, BitcoinWitPubKeyAddress address, uint256 txHash, Transaction tx, OutPoint input)> userInputData, AliceClient4 aliceClient, UnblindedSignature unblindedSignature)>();

            for (int i = 0; i < inputRegistrationUsers.Count; i++)
            {
                var user    = inputRegistrationUsers[i];
                var request = aliceClients[i];

                var aliceClient = await request;

                if (roundId == 0)
                {
                    roundId = aliceClient.RoundId;
                }
                else
                {
                    Assert.Equal(roundId, aliceClient.RoundId);
                }

                // Because it's valuetuple.
                users.Add((user.requester, user.blinded, user.activeOutputAddress, user.changeOutputAddress, user.inputProofModels, user.userInputData, aliceClient, null));
            }

            Assert.Equal(users.Count, roundConfig.AnonymitySet);

            var confirmationRequests = new List <Task <(RoundPhase currentPhase, IEnumerable <ActiveOutput>)> >();

            foreach (var user in users)
            {
                confirmationRequests.Add(user.aliceClient.PostConfirmationAsync());
            }

            RoundPhase roundPhase = RoundPhase.InputRegistration;
            int        k          = 0;

            foreach (var request in confirmationRequests)
            {
                var resp = await request;
                if (roundPhase == RoundPhase.InputRegistration)
                {
                    roundPhase = resp.currentPhase;
                }
                else
                {
                    Assert.Equal(roundPhase, resp.currentPhase);
                }

                var user = users.ElementAt(k);
                user.unblindedSignature = resp.Item2.First().Signature;
            }

            {
                var times = 0;
                while (!(await SatoshiClient.GetAllRoundStatesAsync()).All(x => x.Phase == RoundPhase.InputRegistration))
                {
                    await Task.Delay(100);

                    if (times > 50)                     // 5 sec, 3 should be enough
                    {
                        throw new TimeoutException("Not all rounds were in InputRegistration.");
                    }
                    times++;
                }
            }

            int bannedCount = coordinator.UtxoReferee.CountBanned(false);

            Assert.Equal(0, bannedCount);

            aliceClients.Clear();
            round = coordinator.GetCurrentInputRegisterableRoundOrDefault();
            foreach (var user in inputRegistrationUsers)
            {
                aliceClients.Add(AliceClientBase.CreateNewAsync(round.RoundId, new[] { user.activeOutputAddress }, new[] { round.MixingLevels.GetBaseLevel().SignerKey.PubKey }, new[] { user.requester }, network, user.changeOutputAddress, new[] { user.blinded }, user.inputProofModels, BackendHttpClient));
            }

            roundId = 0;
            users   = new List <(Requester requester, BlindedOutputWithNonceIndex blinded, BitcoinAddress activeOutputAddress, BitcoinAddress changeOutputAddress, IEnumerable <InputProofModel> inputProofModels, List <(Key key, BitcoinWitPubKeyAddress address, uint256 txHash, Transaction tx, OutPoint input)> userInputData, AliceClient4 aliceClient, UnblindedSignature unblindedSignature)>();
            for (int i = 0; i < inputRegistrationUsers.Count; i++)
            {
                var user    = inputRegistrationUsers[i];
                var request = aliceClients[i];

                var aliceClient = await request;
                if (roundId == 0)
                {
                    roundId = aliceClient.RoundId;
                }
                else
                {
                    Assert.Equal(roundId, aliceClient.RoundId);
                }

                // Because it's valuetuple.
                users.Add((user.requester, user.blinded, user.activeOutputAddress, user.changeOutputAddress, user.inputProofModels, user.userInputData, aliceClient, null));
            }

            Assert.Equal(users.Count, roundConfig.AnonymitySet);

            confirmationRequests = new List <Task <(RoundPhase currentPhase, IEnumerable <ActiveOutput>)> >();

            foreach (var user in users)
            {
                confirmationRequests.Add(user.aliceClient.PostConfirmationAsync());
            }

            {
                var times = 0;
                while (!(await SatoshiClient.GetAllRoundStatesAsync()).All(x => x.Phase == RoundPhase.InputRegistration))
                {
                    await Task.Delay(100);

                    if (times > 50)                     // 5 sec, 3 should be enough
                    {
                        throw new TimeoutException("Not all rounds were in InputRegistration.");
                    }
                    times++;
                }
            }

            bannedCount = coordinator.UtxoReferee.CountBanned(false);
            Assert.True(bannedCount >= roundConfig.AnonymitySet);

            foreach (var aliceClient in aliceClients)
            {
                aliceClient?.Dispose();
            }
        }
Beispiel #37
0
 public Round()
 {
     CurPhase = RoundPhase.NotStart;
 }
Beispiel #38
0
    void shootingPhase()
    {
        if (succesHits > 0 && !missileShooted)
        {
            Instantiate(missile, _player.transform.position, Quaternion.identity);
            missileShooted = true;
        }else if(succesHits == 0)
        {
            Invoke("destroyIcons",0.3f);
            actualRoundPhase = RoundPhase.enemyMove;
            
            //destroyIcons();
        }

        shootingDelay -= Time.deltaTime;
        if(shootingDelay <= 0)
        {
            shootingDelay = 1f;
            missileShooted = false;
            if (isEnemiesDestroyed())
            {
                /// END 
                /// OF
                /// FIGHT
                /// HERE !!!!
                Invoke("destroyIcons",0.5f);
                actualRoundPhase = RoundPhase.steady;
            }else
                actualRoundPhase = RoundPhase.moving;
        }
    }