/// <inheritdoc />
        protected override async Task <bool> ProcessEventUnderLockAsync(GameRound gameRound,
                                                                        StartGameRoundEventOutput eventData,
                                                                        TransactionHash transactionHash,
                                                                        INetworkBlockHeader networkBlockHeader,
                                                                        CancellationToken cancellationToken)
        {
            if (gameRound.Status != GameRoundStatus.PENDING)
            {
                // Don't care what status it is in - if its not pending then this event isn't relevant
                return(true);
            }

            // n.b. can't use the network time as blocks are not regular
            DateTime now = this._dateTimeSource.UtcNow();

            GameRound newRoundState =
                new(gameRoundId : gameRound.GameRoundId, network : gameRound.Network, gameManagerContract : gameRound.GameManagerContract, createdByAccount : gameRound.CreatedByAccount, gameContract :
                    gameRound.GameContract, seedCommit : gameRound.SeedCommit, seedReveal : gameRound.SeedReveal, status : GameRoundStatus.STARTED, roundDuration : gameRound.RoundDuration,
                    bettingCloseDuration : gameRound.BettingCloseDuration, roundTimeoutDuration : gameRound.RoundTimeoutDuration, dateCreated : gameRound.DateCreated, dateUpdated :
                    networkBlockHeader.Timestamp, dateStarted : now, dateClosed : null, blockNumberCreated : networkBlockHeader.Number);

            await this.GameRoundDataManager.ActivateAsync(activationTime : newRoundState.DateStarted !.Value,
                                                          gameRoundId : newRoundState.GameRoundId,
                                                          blockNumberCreated : newRoundState.BlockNumberCreated,
                                                          transactionHash : transactionHash);

            await this._gameStatisticsPublisher.GameRoundStartedAsync(network : newRoundState.Network,
                                                                      gameRoundId : newRoundState.GameRoundId,
                                                                      this._gameRoundTimeCalculator.CalculateTimeLeft(gameRound: newRoundState),
                                                                      blockNumber : newRoundState.BlockNumberCreated);

            return(true);
        }
Пример #2
0
        public Start(Base.ISelect selectGame, GameRound.Base.IStart startRound,
					 Hubs.Base.ISendMessage sendMessage)
        {
            this._selectGame = selectGame;
            this._startRound = startRound;
            this._sendMessage = sendMessage;
        }
        public Task <StartRoundResult> StartNewRound(MathEquation equation)
        {
            lock (_lock)
            {
                if (CurrentState == GameState.RoundInPlay)
                {
                    throw new InvalidOperationException("Cannot start new round when previous round is in play");
                }

                var gamePlayers = Players.ToArray();

                if (!gamePlayers.Any())
                {
                    var gameState = UpdateRoundStatus();

                    return(Task.FromResult(new StartRoundResult(gameState.State, CurrentRound)));
                }

                CurrentRound = new GameRound(Guid.NewGuid(), _dateTimeProvider.UtcNow, equation, gamePlayers);
                CurrentState = GameState.RoundInPlay;

                var state = UpdateRoundStatus();

                return(Task.FromResult(new StartRoundResult(state.State, CurrentRound)));
            }
        }
        private Task FixGameAsync(INetworkBlockHeader blockHeader, GameRound game, CancellationToken cancellationToken)
        {
            if (!this._contractInfo.Addresses.TryGetValue(key: blockHeader.Network, out ContractAddress? gameManagerContractAddress))
            {
                this._logger.LogWarning($"{blockHeader.Network.Name}: {game.GameRoundId} - No game contract.");

                return(Task.CompletedTask);
            }

            if (gameManagerContractAddress != game.GameManagerContract)
            {
                this._logger.LogWarning($"{blockHeader.Network.Name}: {game.GameRoundId} - Unknown contract address - using {game.GameManagerContract}, Current: {gameManagerContractAddress}");

                return(Task.CompletedTask);
            }

            switch (game.Status)
            {
            case GameRoundStatus.PENDING: return(this.FixPendingGameAsync(blockHeader: blockHeader, game: game, cancellationToken: cancellationToken));

            case GameRoundStatus.BETTING_STOPPING: return(this.FixBettingStoppingGameAsync(blockHeader: blockHeader, game: game, cancellationToken: cancellationToken));

            case GameRoundStatus.COMPLETING: return(this.FixCompletingGameAsync(blockHeader: blockHeader, game: game, cancellationToken: cancellationToken));

            default:
                this._logger.LogWarning($"{blockHeader.Network.Name}: {game.GameRoundId} - in unexpected state: {game.Status.GetName()}");

                return(Task.CompletedTask);
            }
        }
Пример #5
0
        public void PlayTheGame()
        {
            List <CodePeg> copiedCodePegsPlayer1      = new List <CodePeg>(codePegsPlayer1);
            string         letterCodedCodePegsPlayer2 = "";

            Console.WriteLine("Enter four-color guess; R for Red, G for Green, C for Cyan, Y for Yellow, B for Black, W for White)\n" +
                              "eg. RCRW ");

            while (true)
            {
                copiedCodePegsPlayer1.Clear();
                copiedCodePegsPlayer1 = codePegsPlayer1.ToList();

                Console.WriteLine("Your last guess was: " + letterCodedCodePegsPlayer2);
                codePegsPlayer2.Clear();

                letterCodedCodePegsPlayer2 = Console.ReadLine();
                List <string> stringlist = new List <string>(letterCodedCodePegsPlayer2.Select(c => c.ToString()));

                foreach (string str in stringlist)
                {
                    CodePeg singleCodePeg = new CodePeg();
                    Enum.TryParse(str, out singleCodePeg);
                    codePegsPlayer2.Add(singleCodePeg);
                }

                var gameRound = new GameRound(copiedCodePegsPlayer1, codePegsPlayer2);
                gameRound.PrintTheAssessmentResult();
            }
        }
Пример #6
0
        /// <inheritdoc />
        public async Task StartGameAsync(INetworkSigningAccount account, GameRound game, INetworkBlockHeader networkBlockHeader, CancellationToken cancellationToken)
        {
            PendingTransaction pendingTransaction;

            try
            {
                StartGameRoundInput input = new(roundId : game.GameRoundId, gameAddress : game.GameContract, entropyCommit : game.SeedCommit);

                pendingTransaction = await this._transactionService.SubmitAsync(account : account,
                                                                                transactionContext : new TransactionContext(contextType: @"GAMEROUND", game.GameRoundId.ToString()),
                                                                                input : input,
                                                                                cancellationToken : cancellationToken);
            }
            catch (TransactionWillAlwaysFailException exception)
            {
                this._logger.LogError(new EventId(exception.HResult), exception: exception, $"{networkBlockHeader.Network.Name}: Failed to start game {game.GameRoundId}: {exception.Message}");

                await this._gameRoundDataManager.MarkAsBrokenAsync(gameRoundId : game.GameRoundId, closingBlockNumber : networkBlockHeader.Number, exceptionMessage : exception.Message);

                await this._gameStatisticsPublisher.GameRoundBrokenAsync(network : account.Network, gameRoundId : game.GameRoundId);

                return;
            }

            this._logger.LogInformation($"{pendingTransaction.Network.Name}: Created game {game.GameRoundId}: tx {pendingTransaction.TransactionHash}");
        }
Пример #7
0
        protected override void DoBetting(GameRound round)
        {
            var rnd = new Random(Guid.NewGuid().GetHashCode());

            round.BetCountDesc = $"{rnd.Next(400,3000)}:{rnd.Next(700,3000)}:{rnd.Next(10,100)}";
            base.DoBetting(round);
        }
Пример #8
0
        /// <inheritdoc />
        protected override async Task <bool> ProcessEventUnderLockAsync(GameRound gameRound,
                                                                        EndGameRoundEventOutput eventData,
                                                                        TransactionHash transactionHash,
                                                                        INetworkBlockHeader networkBlockHeader,
                                                                        CancellationToken cancellationToken)
        {
            if (gameRound.Status != GameRoundStatus.COMPLETING)
            {
                // Don't care what status it is in - if its not completing then this event isn't relevant
                return(true);
            }

            WinAmount[] winAmounts = eventData
                                     .Players.Zip(second: eventData.WinAmounts, resultSelector: (accountAddress, winAmount) => new WinAmount {
                AccountAddress = accountAddress, Amount = winAmount
            })
                                     .ToArray();

            this.Logger.LogInformation($"{networkBlockHeader.Network.Name}: {eventData.GameRoundId}. Progressive Win/Loss: {eventData.ProgressivePotWinLoss}");

            await this.GameRoundDataManager.SaveEndRoundAsync(gameRoundId : gameRound.GameRoundId,
                                                              blockNumberCreated : networkBlockHeader.Number,
                                                              transactionHash : transactionHash,
                                                              winAmounts : winAmounts,
                                                              progressivePotWinLoss : eventData.ProgressivePotWinLoss,
                                                              gameResult : eventData.GameResult,
                                                              history : eventData.History);

            await this._gameStatisticsPublisher.GameRoundEndedAsync(network : networkBlockHeader.Network,
                                                                    gameRoundId : gameRound.GameRoundId,
                                                                    blockNumber : networkBlockHeader.Number,
                                                                    startBlockNumber : gameRound.BlockNumberCreated);

            return(true);
        }
Пример #9
0
        public void ReturnMixedOutcomeGivenSomeCorrectAndSomeIncorrect(int[] guess, int[] answer, string expected)
        {
            var gameRound = new GameRound(answer);
            var outcome   = gameRound.CheckAnswer(guess);

            outcome.ShouldBe(expected);
        }
Пример #10
0
    internal void RunBattleScreen(Player rcvdMePlayer, GameRound gameRound)
    {
        if (gameRound.player1.sessionId == rcvdMePlayer.sessionId)
        {
            _enemy = gameRound.player2;
            _me    = gameRound.player1;
        }
        else if (gameRound.player2.sessionId == rcvdMePlayer.sessionId)
        {
            _enemy = gameRound.player1;
            _me    = gameRound.player2;
        }


        for (int i = 0; i < 5; i++)
        {
            turns[i] = new GameTurn
            {
                damageDealt    = CalcDamage(_me.actions[i], _enemy.actions[i]),
                damageReceived = CalcDamage(_enemy.actions[i], _me.actions[i]),
                action         = _me.actions[i],
                actionRecieved = _enemy.actions[i]
            };
        }
        enemyImage.sprite = avatars[(int)_enemy.avatar];
        meImage.sprite    = avatars[(int)_me.avatar];
        _turn             = 0;
        DisplayTurn();
    }
Пример #11
0
 public void ProcessRoundPlayed(GameRound gameRound)
 {
     Debug.Log("process round");
     _gameRoundContainer.gameRound = gameRound;
     _gameRoundContainer.me        = me;
     SceneManager.LoadScene("BattleScene", LoadSceneMode.Additive);
 }
        private async Task EndGameRoundAsync(INetworkBlockHeader blockHeader, GameRound gameRound, CancellationToken cancellationToken)
        {
            await using (IObjectLock <GameRoundId>?gameRoundLock = await this._gameRoundLockManager.TakeLockAsync(gameRound.GameRoundId))
            {
                if (gameRoundLock == null)
                {
                    // something else has the game round locked
                    this._logger.LogInformation($"{gameRound.Network.Name}: could not get lock for {gameRound.GameRoundId}");

                    return;
                }

                try
                {
                    INetworkSigningAccount signingAccount = this._ethereumAccountManager.GetAccount(new NetworkAccount(network: gameRound.Network, address: gameRound.CreatedByAccount));

                    this._logger.LogInformation($"{gameRound.Network.Name}: End using game round: {gameRound.GameRoundId}");

                    await this._gameManager.EndGameAsync(account : signingAccount, gameRoundId : gameRound.GameRoundId, networkBlockHeader : blockHeader, cancellationToken : cancellationToken);
                }
                catch (Exception exception)
                {
                    this._logger.LogError(new EventId(exception.HResult), exception: exception, $"{gameRound.Network.Name}: Failed to end game {gameRound.GameRoundId}: {exception.Message}");
                }
            }
        }
Пример #13
0
        public void NextRownd()
        {
            var gameRound = new GameRound();

            this.GameRounds.Add(gameRound);
            ConsoleHelper.PrintLine();
            ConsoleHelper.PrintBlue(String.Format(UIConstants.Round, this.GameRounds.Count()));
            ConsoleHelper.ShowGameMenuForPlayer();

            ReadPlayerMove(this.player1);
            ReadPlayerMove(this.player2);

            gameRound.player1 = player1;
            gameRound.player2 = player2;

            ruleService.ProcessRowndWinner(gameRound);

            if (gameRound.IsTieMatch)
            {
                ConsoleHelper.PrintTieInTheGame(
                    player1.CurrentMove.Description(),
                    player2.CurrentMove.Description()
                    );
            }
            else
            {
                ConsoleHelper.PrintWinner(
                    gameRound.Winner.Description,
                    gameRound.Looser.CurrentMove.Description(),
                    gameRound.Winner.CurrentMove.Description()
                    );
            }

            ConsoleHelper.PrinEndTurn();
        }
Пример #14
0
        private GameRound DetermineRound(Player p1, Player p2)
        {
            int p1D = 0;
            int p2D = 0;

            for (int i = 0; i <= 4; i++)
            {
                p1D += CalcDamage((ActionType)p1.actions[i], (ActionType)p2.actions[i]);
                p2D += CalcDamage((ActionType)p2.actions[i], (ActionType)p1.actions[i]);
            }

            int w = -1;

            if (p1D > p2D)
            {
                w = 1;
            }
            else if (p1D < p2D)
            {
                w = 2;
            }
            else
            {
                w = 3;
            }
            p1.lockedIn = false;
            p2.lockedIn = false;
            GameRound gameRound = new GameRound {
                player1 = p1, player2 = p2, player1Damnage = p1D, player2Damage = p2D, winner = w
            };

            return(gameRound);
        }
 public void SetupClientReceipt(Client targetClient, GameRound currentRound)
 {
     Debug.Log("Setup Client Receipt");
     this.currentRound = currentRound;
     this.currentClient = targetClient;
     this.enabled = true;
 }
        private BaseResult ResetRound()
        {
            CurrentRound = null;
            CurrentState = GameState.Waiting;

            return(UpdateRoundStatus());
        }
 private void LoadRoundAssets( )
 {
     round = new GameRound( );
     round.LoadNewGrid( );
     transitionAsset = round.LoadedTransitionIntroAsset;
     LoadPlayersIntoRound( );
 }
Пример #18
0
 /// <summary>
 /// Assign cards to the players
 /// </summary>
 private void DrawCards(GameRound currentRound)
 {
     foreach (var player in this._players)
     {
         player.Hand.Cards = this.AssignSet(currentRound, player.Hand).ToList();
     }
 }
Пример #19
0
 public void StartNewRound(GameRound round)
 {
     this.ResetPlayersHand();
     this.ReturnAllCards();
     this.ShuffleDeck();
     this.DrawCards(round);
 }
Пример #20
0
        public void PlayCard(int playerId, Card card, IGameMessenger gameMessenger)
        {
            if (card is null)
            {
                throw new ArgumentNullException(nameof(card));
            }

            if (gameMessenger is null)
            {
                throw new ArgumentNullException(nameof(gameMessenger));
            }

            this.ThrowIfPlayerIsNotInGame(playerId);
            if (GameIsInLobby)
            {
                throw new InvalidOperationException("Round is not started.");
            }

            if (!this.currentRound.CanPlayCard(playerId, card))
            {
                throw new InvalidOperationException("You can't play this card at current time.");
            }

            this.currentRound.PlayCard(playerId, card);

            var cardPlayedMsg = this.CreateGameMsg <CardWasPlayed>();

            cardPlayedMsg.Card     = card;
            cardPlayedMsg.PlayerId = playerId;
            gameMessenger.SendMessage(cardPlayedMsg, this.playerLobby.PlayersInLobby);

            if (this.currentRound.TrickIsComplete())
            {
                var trickWinnerId = this.currentRound.GetTrickWinner();
                var failedGoals   = this.currentRound.GetFailedTasks(trickWinnerId);

                if (failedGoals.Count > 0)
                {
                    var roudFailedMsg = this.CreateGameMsg <RoundFailed>();
                    gameMessenger.SendMessage(roudFailedMsg, this.playerLobby.PlayersInLobby);
                    this.currentRound = null;
                    return;
                }

                var finishedTasks = this.currentRound.GetFinishedTasks(trickWinnerId);
                this.currentRound.GoToNextTrick(trickWinnerId);

                var trickMsg = CreateGameMsg <TrickFinished>();
                trickMsg.WinnerPlayerId = trickWinnerId;
                trickMsg.FinishedTasks  = finishedTasks;
                trickMsg.TakenCards     = this.currentRound.GetCurrentTrickCards();

                gameMessenger.SendMessage(trickMsg, this.playerLobby.PlayersInLobby);
            }
            else
            {
                this.currentRound.MoveToNextPlayer();
            }
        }
Пример #21
0
        public void InitializeNewGame(int commandsCount)
        {
            CurrentRound = GameRound.FirstRound;

            ViewModelLocator.Initialize();
            ViewModelLocator.QuestionTable.LoadDataCommand.Execute(service => service.GetQuestionGroupList());
            ViewModelLocator.CommandResults.InitializeCommands(commandsCount);
        }
Пример #22
0
    private void sendMoveOutOfPlay()
    {
        IGameInputReceiver inputReceiver = GameRound.GetInputReceiver();

        inputReceiver.InputPutLudoOutOfPlay(Data.player, selectedLudo);

        finishDeployable();
    }
Пример #23
0
    private void sendMove(BoardTile tile)
    {
        IGameInputReceiver inputReceiver = GameRound.GetInputReceiver();

        inputReceiver.InputMove(Data.player, selectedLudo, tile);

        finishDeployable();
    }
Пример #24
0
        public void SetUp()
        {
            gameRound = new GameRound();
            game      = new RockPaperScissors(gameRound);

            player1 = Substitute.For <IPlayer>();
            player2 = Substitute.For <IPlayer>();
        }
Пример #25
0
        public void ReturnAllMinusGivenAllCorrectNumbersInWrongPlaces(int[] guess, int[] answer)
        {
            var gameRound = new GameRound(answer);
            var outcome   = gameRound.CheckAnswer(guess);
            var expected  = string.Concat(Enumerable.Repeat(GameAnswers.CorrectNumberWrongPlace, 4));

            outcome.ShouldBe(expected);
        }
Пример #26
0
    private void initalizeAndStartGameRound()
    {
        GameObject gameRoundObject = new GameObject("GameRoundManager", typeof(GameRound));
        GameRound  round           = gameRoundObject.GetComponent <GameRound>();

        round.SetupPlayers(currentPlayers);
        round.StartRound();
    }
Пример #27
0
        static void Main(string[] args)
        {
            List <QuestionClass> questions = LoadJSON();
            int       startingIndex        = 0;
            GameRound round = new GameRound();

            round.StartGameRound(questions, startingIndex);
        }
Пример #28
0
 private IEnumerator StartGameAfterLoad(GameRound round)
 {
     while (round.State != GameRound.GameState.Ready)
     {
         yield return(null);
     }
     round.StartGame();
     StartCoroutine(Countdown());
 }
Пример #29
0
        public async Task <GameRound> InsertGameRound(GameRound gameRound)
        {
            using (var db = new DbConnection(m_connectionString))
            {
                gameRound.Id = await db.Connection.InsertAsync(gameRound);

                return(gameRound);
            }
        }
Пример #30
0
    private void HandleOnRoundComplete(string sender, string roundInfo)
    {
        GameRound round = JsonUtility.FromJson <GameRound> (roundInfo);

        if (round.Round == (int)TABLE_GAME_ROUND.PLAY)
        {
            OpenWhoopAssCard();
        }
    }
Пример #31
0
 private void StartCourtCutscene()
 {
     currentRound = GameRound.CourtCutscene;
     nextRound    = GameRound.StealthRound;
     if (SceneManager.GetActiveScene() != SceneManager.GetSceneByName("CourtScene"))
     {
         SceneManager.LoadScene("CourtScene");
     }
 }
Пример #32
0
        public void FinishGame(int gameId, int myScore, int opponentsScore, Result myResult, Result opponentsResult)
        {
            var game  = CurrentGames[gameId];
            var other = game.GetOther(ClientCallback);
            var me    = game.GetMe(ClientCallback);

            other.Client.FinishGame();
            game.Stop();
            CurrentGames.Remove(gameId);
            me.Playing    = false;
            other.Playing = false;

            using (var db = new GameDataContext())
            {
                GamePlayer dbMe    = db.GamePlayers.Find(me.NickName);
                GamePlayer dbOther = db.GamePlayers.Find(other.NickName);

                var dbGame = new Game()
                {
                    CardCount    = game.CardTypes.Count,
                    GameDuration = game.GameDuration
                };
                db.Games.Add(dbGame);
                db.SaveChanges();

                var dbMyGameRound = new GameRound()
                {
                    GamePlayer     = dbMe,
                    Game           = dbGame,
                    GameId         = dbGame.Id,
                    MovesCount     = me.MovesCount,
                    PlayerNickName = me.NickName,
                    Result         = myResult
                };

                var dbOpponentRound = new GameRound()
                {
                    GamePlayer     = dbOther,
                    Game           = dbGame,
                    GameId         = dbGame.Id,
                    MovesCount     = other.MovesCount,
                    PlayerNickName = other.NickName,
                    Result         = opponentsResult
                };
                db.GameRounds.Add(dbMyGameRound); //add rounds
                db.GameRounds.Add(dbOpponentRound);

                dbGame.PlayedRounds.Add(dbMyGameRound); //add games reference
                dbGame.PlayedRounds.Add(dbOpponentRound);

                dbMe?.PlayerRounds.Add(dbMyGameRound); //add players reference
                dbOther?.PlayerRounds.Add(dbOpponentRound);

                db.SaveChanges(); //save
            }
        }
Пример #33
0
 public NinthPlanetServer(
     GameInfo gameInfo,
     GameLobby gameLobby,
     GameRound gameRound,
     IGameRoundFactory gameRoundFactory,
     ILogger <NinthPlanetServer> logger)
     : this(gameInfo, gameLobby, gameRoundFactory, logger)
 {
     this.currentRound = gameRound;
 }
Пример #34
0
        /// <summary>
        /// Assigns cards to the specified card set (i.e. hand)
        /// and returns the list of the assigned cards
        /// </summary>
        /// <param name="currentRound"></param>
        /// <param name="cardSet"></param>
        public IEnumerable<ICard> AssignSet(GameRound currentRound, ICardSet cardSet)
        {
            if (cardSet == null)
            {
                throw new InvalidOperationException("Cannot assign cards to a null cardSet");
            }

            var numOfCardsToAssign = this._cardsForEachRound[currentRound];
            return this._deck.AssignSet(numOfCardsToAssign, cardSet);
        }
Пример #35
0
        public void ThrowDices()
        {
            var dices = GameRound.Run();

            FirstDice  = dices.Item1;
            SecondDice = dices.Item2;

            OnPropertyChanged(nameof(FirstDice));
            OnPropertyChanged(nameof(SecondDice));
        }
    /// <summary>
    /// Should be called at the start of a round.
    /// </summary>
    public void HandleRoundStarted(GameRound currentRound)
    {
        this.enabled = true;
        this.clientArrivalDelay = 0;
        lastClientArrived = Time.time;
        this.currentRound = currentRound;

        // Invite Returning Customers:
        arrivingClients.AddRange(returningClients);
        returningClients.Clear();
    }
Пример #37
0
        public Leave(DS.Game.Base.ILeave leaveGame, 
					 Game.Base.ISelect selectGame,
                     Hubs.Base.ISendMessage sendMessage,
					 GameRound.Base.IStart startRound,
					 GameRound.Base.IDelete deleteRound,
					 Base.IUpdate updateGame,
                     GamePlayerCard.Base.IDeal dealCards)
        {
            this._leaveGame = leaveGame;
            this._selectGame = selectGame;
            this._sendMessage = sendMessage;
            this._startRound = startRound;
            this._deleteRound = deleteRound;
            this._updateGame = updateGame;
            this._dealCards = dealCards;
        }
Пример #38
0
 /// <summary>
 /// Starts the game for this table
 /// </summary>
 public void StartNewGame()
 {
     this._dealer.StartNewGame(this.Players);
     this._currentRound = GameRound.BlockOneRoundOne;
 }
Пример #39
0
 /// <summary>
 /// Changes the current round to the next one
 /// </summary>
 private void MoveToTheNextRound()
 {
     this._currentRound += 1;
 }