Exemplo n.º 1
0
        public void LoadGame()
        {
            var(game, data) = saveService.LoadGame();

            GameData.Initialize(data);
            CurrentGame.Load(game);

            if (game == null)
            {
                return;
            }

            game.Player.Inventory.ItemAdded += (sender, args) =>
            {
                game.Journal.Write(new ItemReceivedMessage(args.Item));
            };
            game.Player.Inventory.ItemRemoved += (sender, args) =>
            {
                game.Journal.Write(new ItemLostMessage(args.Item));
            };

            game.TurnEnded += game_TurnEnded;

            turnsSinceLastSaving = 0;
        }
Exemplo n.º 2
0
        public async Task <bool> CheckIfPlaysChampion(Region region, string summonerName, string championName)
        {
            Summoner summoner = await GetSummonerByName(region, summonerName);

            if (summoner is null)
            {
                return(false);
            }

            CurrentGame match = await GetCurrentMatchId(region, summoner.Id);

            if (match is null)
            {
                return(false);
            }

            CurrentGameParticipant participant = match.Participants.SingleOrDefault(x => x.SummonerId == summoner.Id);

            Champions.TryGetValue(championName, out long championId);

            if (participant.ChampionId == championId)
            {
                return(true);
            }

            return(false);
        }
        public void Initialize()
        {
            _requester = new Mock <IRateLimitedRequester>();
            var staticEndpointProvider = new Mock <IStaticEndpointProvider>();

            _currentGameResponse = new CurrentGame
            {
                GameId        = 1,
                GameLength    = 60,
                GameMode      = "GameMode",
                GameQueueType = "Normal Draft",
                GameType      = GameType.MatchedGame,
                MapType       = MapType.SummonersRift,
                GameStartTime = DateTime.Today,
                Platform      = Platform.EUW1
            };

            _featuredGamesResponse = new FeaturedGames
            {
                GameList = new List <CurrentGame>
                {
                    _currentGameResponse
                },
                ClientRefreshInterval = 30
            };
            _riotApi = new RiotApi(_requester.Object, staticEndpointProvider.Object);
        }
Exemplo n.º 4
0
        static public void init()
        {
            if (initialized == false)
            {
                Maps        = null;          // Initialized in the dashboard
                MapTowns    = null;          // Initialized in the dashboard
                CurrentGame = new CurrentGame();
                Viewport    = new Viewport();
                State       = new State();
                Calendar    = new Calendar();
                Towns       = new Town[Config.MAX_TOWNS];
                Players     = new Player[Config.MAX_PLAYERS];
                Tiles       = new Tile[Config.TILES_X, Config.TILES_Y];

                for (int i = 0; i < Config.MAX_PLAYERS; i++)
                {
                    Players[i] = new Player(i);
                }

                for (int i = 0; i < Config.MAX_TOWNS; i++)
                {
                    Towns[i] = new Town(i);
                }

                for (int x = 0; x < Config.TILES_X; x++)
                {
                    for (int y = 0; y < Config.TILES_Y; y++)
                    {
                        Tiles[x, y] = new Tile(x + 1, y + 1);
                    }
                }

                initialized = true;
            }
        }
Exemplo n.º 5
0
 /// <summary>
 /// Realiza la próxima jugada en la partida, puede iniciar un juego nuevo
 /// </summary>
 /// <returns>jugada</returns>
 public IPlay <TGameKind> GetNextPlay()
 {
     if (CurrentGame != null)
     {
         if (CurrentGame.Result == null)
         {
             var play = CurrentGame.GetNextPlay();
             if (play != null)
             {
                 return(play);
             }
             else //se acabó el juego actual
             {
                 UpdateScore();
                 if (StartNewGame())//Se puede empezar un juego nuevo
                 {
                     return(CurrentGame.GetNextPlay());
                 }
                 return(null); //se acabó la partida
             }
         }
         else
         {
             if (StartNewGame())
             {
                 return(CurrentGame.GetNextPlay());
             }
             return(null); //se acabó la partida
         }
     }
     else
     {
         throw new Exception();
     }
 }
        public void handleGameInfoMsg(NetworkMessage initMsg)
        {
            GameInfo msg = Deserialize <GameInfo> (initMsg.reader.ReadBytesAndSize());

            if (msg.gameOver)
            {
                isGameOver        = true;
                canSendServerMsg  = false;
                isListeningForTCP = false;


                UnetRoomConnector.shutdownCurrentConnection();

                string gameOverString = TCP_API.APIStandardConstants.Fields.gameOver;
                string gameOverMsg;
                //Debug.LogError ("Winner: " + msg.winnerColor);
                if (msg.winnerColor == Game.PlayerColor.None)
                {
                    gameOverMsg = "It's a draw!";
                    TCPLocalConnection.sendMessage(gameOverString + ": 0");
                }
                else
                {
                    gameOverMsg = msg.winnerColor + " won";
                    TCPLocalConnection.sendMessage(gameOverString + ": " + (msg.winnerColor == PlayerColor.Blue ? "1" : "-1"));
                }
                CurrentGame.gameOver(gameOverMsg);
            }
        }
Exemplo n.º 7
0
    private void SubmitTurnCallBack(SubmitTurnResponse response)
    {
        var previous = CurrentGame.Copy();

        CurrentGame.Update(response.Match);
        OnMatchUpdated(CurrentGame, previous);
    }
Exemplo n.º 8
0
    private void GetMatchCallBack(GetMatchResponse response)
    {
        var previous = CurrentGame.Copy();

        CurrentGame.Update(response.Match);
        OnMatchUpdated(CurrentGame, previous);
    }
Exemplo n.º 9
0
    private void JoinAvailableMatchCallBack(JoinAvailableMatchResponse response)
    {
        if (response.Success)
        {
            var matchObject = response.Match;
            if (matchObject.State != GameState.MATCHSTATE_READY)
            {
                UnityEngine.Debug.Log("INVALID MATCH STATE:" + matchObject.State);
            }

            SaveMatchId(matchObject.MatchId);

            CurrentGame.MatchId = matchObject.MatchId;
            CurrentGame.Update(matchObject);
            CurrentGame.OccupyEmptyPlayerPosition(m_chilliConnectId);

            StartMatch(matchObject.MatchId);

            OnMatchMakingSuceeded(CurrentGame);
        }
        else
        {
            OnMatchMakingFailed();
        }
    }
Exemplo n.º 10
0
    public void SubmitTurn()
    {
        UnityEngine.Debug.Log("Submitting turn");

        var submitTurnRequest = new SubmitTurnRequestDesc(CurrentGame.MatchId);

        submitTurnRequest.StateData = CurrentGame.AsMultiTypeDictionary();
        if (CurrentGame.MatchState == GameState.MATCHSTATE_COMPLETE)
        {
            var outcomeDataBuilder = new SdkCore.MultiTypeDictionaryBuilder();
            outcomeDataBuilder.Add("Winner", m_chilliConnectId);
            submitTurnRequest.OutcomeData = outcomeDataBuilder.Build();
            submitTurnRequest.Completed   = true;

            SkillLevel++;
            var setPlayerDataRequest = new SetPlayerDataRequestDesc("SkillLevel", SkillLevel);
            m_chilliConnect.CloudData.SetPlayerData(setPlayerDataRequest,
                                                    (request, response) => Debug.Log("Player Data Updated"),
                                                    (request, error) => Debug.Log(error.ErrorDescription));
        }

        m_chilliConnect.AsyncMultiplayer.SubmitTurn(submitTurnRequest,
                                                    (request, response) => SubmitTurnCallBack(response),
                                                    (request, error) => Debug.Log(error.ErrorDescription));
    }
Exemplo n.º 11
0
        private void BuildMainMenu()
        {
            jQuery.FromElement(_overlay).Empty();

            BuildMenuButton("Play!", 370, delegate(ElementEvent e)
            {
                CurrentGame.Play();
            });

            BuildMenuButton("Practice", 420, delegate(ElementEvent e)
            {
                BuildPracticeMenu();
            });

            //BuildMenuButton("Options", 470, delegate(ElementEvent e)
            //    {
            //        BuildOptionsMenu();
            //    });

            //BuildMenuButton("High Scores", 520, delegate(ElementEvent e)
            //    {
            //        CurrentGame.ShowHiScores();
            //    });

            jQuery.FromElement(_overlay).Show();
        }
Exemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RiotClient"/> class.
        /// </summary>
        /// <param name="apiKey">The API key.</param>
        public RiotClient(string apiKey)
        {
            IChampion        champion        = new Champion(apiKey);
            ICurrentGame     currentGame     = new CurrentGame(apiKey);
            IFeaturedGames   featuredGames   = new FeaturedGames(apiKey);
            IGame            game            = new Game(apiKey);
            ILeague          league          = new League(apiKey);
            ILolStaticData   lolStaticData   = new LolStaticData(apiKey);
            ILolStatus       lolStatus       = new LolStatus();
            IMatch           match           = new Match(apiKey);
            IMatchList       matchList       = new MatchList(apiKey);
            IStats           stats           = new Stats(apiKey);
            ISummoner        summoner        = new Summoner(apiKey);
            ITeam            team            = new Team(apiKey);
            IChampionMastery championMastery = new ChampionMastery(apiKey);

            this.Champion        = champion;
            this.CurrentGame     = currentGame;
            this.FeaturedGames   = featuredGames;
            this.Game            = game;
            this.League          = league;
            this.LolStaticData   = lolStaticData;
            this.LolStatus       = lolStatus;
            this.Match           = match;
            this.MatchList       = matchList;
            this.Stats           = stats;
            this.Summoner        = summoner;
            this.Team            = team;
            this.ChampionMastery = championMastery;
        }
Exemplo n.º 13
0
 private void Next_Player_Talking(object sender, RoutedEventArgs e)
 {
     if (CurrentGame.RoundNumber != 0)
     {
         CurrentGame.Talking(IsSurvive);
     }
 }
Exemplo n.º 14
0
 public void VotePlayer(object sender, RoutedEventArgs e)
 {
     if (VoteQuantity < Player.PlayersList.Count)
     {
         Button btn = (Button)e.OriginalSource;
         int    i   = Int32.Parse(btn.Name.Substring(btn.Name.Length - 2));
         foreach (var player in Player.PlayersList)
         {
             if (player.Quanity == i)
             {
                 player.Vote++;
                 BlockVoteQuantityDict["BlockVoteQuantity" + i.ToString()].Text = player.Vote.ToString();
                 VoteQuantity++;
                 break;
             }
         }
     }
     if (VoteQuantity == Player.PlayersList.Count)
     {
         if (CurrentGame.ToSurvive(Player.PlayersList).Count > 1)
         {
             IsSurvive = true;
         }
         BVoting.Content = "Закончить голосование";
     }
 }
Exemplo n.º 15
0
 /// <summary>
 /// Collects input from user for passive turn, ensures legality, then executes move.
 /// Also updates Turn properties to reflect upcoming aggressive turn.
 /// </summary>
 private void ExecutePassiveTurn()
 {
     while (!PassiveTurnDone)
     {
         while (!GetUserInputForTurn())
         {
             CurrentGame.Refresh();
         }
         if (MoveLogic.MoveIsLegal(this.CurrentMove))
         {
             ExecuteCurrentMove(this.CurrentMove);
             CurrentPlayer.LastMoveMade = CurrentMove;
             TurnIsPassive        = false;
             PassiveTurnDone      = true;
             this.currentTurnType = TurnType.Aggressive;
         }
         else
         {
             Console.WriteLine(MoveLogic.PrintErrorMessage(this.CurrentMove) + "  Press enter to continue...");
             Console.ReadLine();
             PassiveTurnDone = false;
         }
         CurrentGame.Refresh();
     }
 }
Exemplo n.º 16
0
 public void SendMessage(string message)
 {
     if (CurrentGame != null && CurrentPlayer != null)
     {
         CurrentGame.SendMessage(CurrentPlayer, message);
     }
 }
Exemplo n.º 17
0
        public bool Act()
        {
            // if key available, make action, otherwise use the same direction as last time
            if (Console.KeyAvailable)
            {
                var pressed = Console.ReadKey(true).Key;

                if (pressed == _up)
                {
                    _direction = Direction.Up;
                }
                else if (pressed == _right)
                {
                    _direction = Direction.Right;
                }
                else if (pressed == _down)
                {
                    _direction = Direction.Down;
                }
                else if (pressed == _left)
                {
                    _direction = Direction.Left;
                }
            }

            return(CurrentGame.Move(_direction));
        }
Exemplo n.º 18
0
        public void NextGame()
        {
            try
            {
                if (CurrentGame != null)
                {
                    CurrentGame.DrawRequest     -= GameDrawRequest;
                    CurrentGame.UpdateUIElement -= GameUpdateUIElement;
                    CurrentGame.Finish();
                }

                history.GamesPlayed++;
                CurrentGame = game_manager.GetPuzzle();
                CurrentGame.SynchronizingObject = SynchronizingObject;
                CurrentGame.DrawRequest        += GameDrawRequest;
                CurrentGame.UpdateUIElement    += GameUpdateUIElement;

                CurrentGame.Begin();

                CurrentGame.GameTime = TimeSpan.Zero;
                Status = SessionStatus.Playing;
            }
            catch (Exception e)
            {
                Console.WriteLine("GameSession.NextGame {0}", e);
            }
        }
Exemplo n.º 19
0
        public async IAsyncEnumerable <ulong> DoPerft(int depth)
        {
            if (Positions.Count == 0)
            {
                yield break;
            }

            foreach (var fd in Positions.Select(p => new FenData(p.Fen)))
            {
                Game.Table.NewSearch();
                CurrentGame.Pos.SetFen(fd);

                if (_results.TryGetValue(CurrentGame.Pos.State.Key, out var result))
                {
                    yield return(result);

                    continue;
                }

                result = CurrentGame.Perft(depth, true);

                _results[CurrentGame.Pos.State.Key] = result;

                // BoardPrintCallback?.Invoke(fd.ToString());
                yield return(result);
            }
        }
Exemplo n.º 20
0
        protected override void OnInitialize()
        {
            TaleWorlds.Core.Game currentGame = this.CurrentGame;
            currentGame.FirstInitialize(false);
            InitializeGameTexts(currentGame.GameTextManager);
            IGameStarter gameStarter = new BasicGameStarter();

            InitializeGameModels(gameStarter);
            GameManager.OnGameStart(currentGame, gameStarter);
            MBObjectManager objectManager = currentGame.ObjectManager;

            currentGame.SecondInitialize(gameStarter.Models);
            currentGame.CreateGameManager();
            GameManager.BeginGameStart(currentGame);
            currentGame.ThirdInitialize();
            currentGame.CreateObjects();
            currentGame.InitializeDefaultGameObjects();
            currentGame.LoadBasicFiles(false);
            LoadXmls();
            currentGame.SetDefaultEquipments((IReadOnlyDictionary <string, Equipment>) new Dictionary <string, Equipment>());
            currentGame.CreateLists();
            ObjectManager.LoadXML("MPClassDivisions");
            objectManager.ClearEmptyObjects();
            MultiplayerClassDivisions.Initialize();
            GameManager.OnCampaignStart(this.CurrentGame, (object)null);
            GameManager.OnAfterCampaignStart(this.CurrentGame);
            GameManager.OnGameInitializationFinished(this.CurrentGame);
            CurrentGame.AddGameHandler <ChatBox>();
        }
 void _Game_OnBoardChanged(object sender, EventArgs e)
 {
     if (InMultiplayer)
     {
         this.SendBoard(CurrentGame.GetBoardData());
     }
 }
Exemplo n.º 22
0
 private void FixMapObjectsZ()
 {
     foreach (GameObject mapObject in MapObjects)
     {
         CurrentGame.FixZ(mapObject);
     }
 }
        public void handleGameInfo(NetworkMessage msg)
        {
            byte[]   bytes   = msg.reader.ReadBytesAndSize();
            GameInfo infoMsg = Game.ClientController.Deserialize <GameInfo> (bytes);;

            if (infoMsg.gameOver)
            {
                string gameOverString = TCP_API.APIStandardConstants.Fields.gameOver;
                TCPLocalConnection.sendMessage(gameOverString);
                isGameOver = true;
                UnetRoomConnector.shutdownCurrentConnection();

                string gameOverMsg;
                if (infoMsg.winnerColor == Game.PlayerColor.None)
                {
                    gameOverMsg = "It's a draw!";
                }
                else
                {
                    gameOverMsg = infoMsg.winnerColor + " won";
                }

                CurrentGame.gameOver(gameOverMsg);
            }
        }
Exemplo n.º 24
0
        public void GetBlockingMoveTestMethod()
        {
            var boards = new[] { new[] { -1, -1, 0, 0, 1, 1, 0, 0, 0 }, //
                                 new[] { 0, 0, 1, -1, 1, 0, 0, 0, 0 } };

            var positions = new[]
                {
                    new[] { 2, 0 }, //
                    new[] { 0, 2 }, //
                };

            for (var i = 0; i < boards.Length; i++)
            {
                var board = boards[i];

                var g = new CurrentGame(new Board(board));

                var brainResult = new BrainResult();
                var canMove = g.GetNewMove(brainResult);

                try
                {
                    Assert.AreEqual(positions[i][0], brainResult.Moves[0].X);
                    Assert.AreEqual(positions[i][1], brainResult.Moves[0].Y);
                    Assert.AreEqual(true, canMove);
                }
                catch
                {
                    UnitTestHelpers.PrintBoard(board, brainResult.Moves[0].X, brainResult.Moves[0].Y, canMove);

                    throw;
                }
            }
        }
Exemplo n.º 25
0
        protected override void KeyDown(ElementEvent e)
        {
            switch (Status)
            {
            case ShooterStatus.Win:
                foreach (int handle in pendingTimers)
                {
                    Window.ClearTimeout(handle);
                }
                if (_practice)
                {
                    CurrentGame.ShowTitleScreen();
                }
                else
                {
                    CurrentGame.NextLevel();
                }
                break;

            case ShooterStatus.Fail:
                foreach (int handle in pendingTimers)
                {
                    Window.ClearTimeout(handle);
                }
                if (_practice)
                {
                    CurrentGame.ShowTitleScreen();
                }
                else
                {
                    CurrentGame.GameOver();
                }
                break;
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Handles the LobbyLost AGCEvent
        /// </summary>
        /// <param name="sender">The object firing the event</param>
        /// <param name="e">The arguments of the event</param>
        public static void LobbyLostAGCEventHandler(object sender, LobbyLostAGCEventArgs e)
        {
            try
            {
                TagTrace.WriteLine(TraceLevel.Verbose, "LobbyLost event received.");

                // Send a chat to all games informing that lobby was lost
                GameServer.SendChat("This server has disconnected from the lobby.  New players will be unable to find this game until the server reconnects.");

                // Log lobby losts to all current games
                foreach (Game CurrentGame in GameServer.Games)
                {
                    TagTrace.WriteLine(TraceLevel.Verbose, "LobbyLost Event waiting to lock Game {0}'s GameData...", CurrentGame.GameID);
                    lock (CurrentGame.GetSyncRoot())
                    {
                        CurrentGame.GameData.LogLobbyLost(e.Time);
                        TagTrace.WriteLine(TraceLevel.Info, "LobbyLost event logged to game {0}.", CurrentGame.GameID);
                    }
                }
            }
            catch (Exception ex)
            {
                TagTrace.WriteLine(TraceLevel.Error, "Error handling LobbyLost event: {0}", ex.Message);
            }
        }
        public string getQueueData(CurrentGame game, long summonerid)
        {
            GameQueueType type = game.GameQueueType;

            FileWriter.WriteToFile(type.ToString());
            return(type.ToString());
        }
Exemplo n.º 28
0
        /// <summary>
        /// Делает ход "Первый ход"
        /// </summary>
        /// <param name="move"></param>
        public void MakeFirstMove(FirstMove move)
        {
            if (move == null)
            {
                throw new ArgumentNullException(nameof(move));
            }

            try
            {
                _moveMutex.WaitOne();

                if (IsInvalid)
                {
                    throw new TrueFalseGameException("Игровой стол находится в инвалидном состоянии");
                }

                if (CurrentGame == null)
                {
                    throw new TrueFalseGameException("Игра еще не началась");
                }

                CurrentGame.MakeFirstMove(move);
            }
            finally
            {
                _moveMutex.ReleaseMutex();
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Делает ход "Не верю"
        /// </summary>
        /// <param name="move"></param>
        public void MakeDontBeleiveMove(DontBelieveMove move, out IReadOnlyCollection <IPlayingCardInfo> takedLoserCards, out Guid loserId)
        {
            if (move == null)
            {
                throw new ArgumentNullException(nameof(move));
            }

            try
            {
                _moveMutex.WaitOne();

                if (IsInvalid)
                {
                    throw new TrueFalseGameException("Игровой стол находится в инвалидном состоянии");
                }

                if (CurrentGame == null)
                {
                    throw new TrueFalseGameException("Игра еще не началась");
                }

                CurrentGame.MakeDontBeleiveMove(move, out takedLoserCards, out loserId);
            }
            finally
            {
                _moveMutex.ReleaseMutex();
            }
        }
Exemplo n.º 30
0
        public void handleGameStatus(NetworkMessage gameStatusMsg)
        {
            byte[]   bytes = gameStatusMsg.reader.ReadBytesAndSize();
            GameInfo msg   = ClientController.Deserialize <GameInfo> (bytes);

            if (msg.gameOver)
            {
                string gameOverString = TCP_API.APIStandardConstants.Fields.gameOver;
                TCPLocalConnection.sendMessage(gameOverString);
                gameOver();
                waitingForInput = false;

                string gameOverMsg;
                if (msg.winnerColor == PlayerColor.None)
                {
                    gameOverMsg = "It's a draw!";
                }
                else
                {
                    gameOverMsg = msg.winnerColor + " won";
                }

                CurrentGame.gameOver(gameOverMsg);
            }
        }
Exemplo n.º 31
0
    private Vector2 GetNextPos()
    {
        float time = Time.deltaTime;

        if (collided && !recoveringFromCollision)
        {
            collisionRecoveryTime             = 0; // SI HAY ALGO RARO BORRAR
            GetComponent <Renderer>().enabled = false;
            speedAtCollision = originalSpeed;
            // speed /= 3;
            speed    = originalSpeed / 3;
            collided = false;
            recoveringFromCollision = true;
        }
        if (recoveringFromCollision)
        {
            twinkleDelta += time;
            if (twinkleDelta > twinkleTime)
            {
                twinkleDelta = 0;
                if (GetComponent <Renderer>().enabled == false)
                {
                    GetComponent <Renderer>().enabled = true;
                }
                else
                {
                    GetComponent <Renderer>().enabled = false;
                }
            }
            collisionRecoveryTime += time;
            if (speed < speedAtCollision)
            {
                speed += collisionRecoveryTime * collisionRecoveryTime;
            }
            else
            {
                GetComponent <Renderer>().enabled = true;
                collisionRecoveryTime             = 0;
                recoveringFromCollision           = false;
            }
        }
        float advance    = time * speed;
        float pathLength = path.GetLength();
        float advancedPercentageInFrame = advance / pathLength;
        float percentageOfLap           = previousS + advancedPercentageInFrame;

        if (percentageOfLap > 1)
        {
            CurrentGame.GetInstance().JustMadeLap();
            numberOfLaps++;
            percentageOfLap -= 1;
        }
        distanceMade = percentageOfLap + numberOfLaps;


        Vector2 pos = path.GetPos(percentageOfLap);

        previousS = percentageOfLap;
        return(pos);
    }
Exemplo n.º 32
0
        private static void Check(int[][] boards, int[][] sizes, Move[][] positions, bool vertical)
        {
            for (var i = 0; i < boards.Length; i++)
            {
                var board = boards[i];

                var g = new CurrentGame(new Board(board, sizes[i][0], sizes[i][1]));

                var brainResult = new BrainResult();
                var canMove = GameBrain.CheckForWin(vertical, false, brainResult, g.Board);

                try
                {
                    Assert.AreEqual(true, canMove);

                    for (int x = 0; x < positions[i].Length; x++)
                    {
                        Assert.AreEqual(positions[i][x].X, brainResult.Moves[x].X);
                        Assert.AreEqual(positions[i][x].Y, brainResult.Moves[x].Y);
                    }
                }
                catch
                {
                    UnitTestHelpers.PrintBoard(board, brainResult.Moves[0].X, brainResult.Moves[0].Y, canMove, sizes[i][0]);

                    throw;
                }
            }
        }
Exemplo n.º 33
0
        public void GetHorizontalWinningMoveTestMethod()
        {
            var boards = new[] { new[] { -1, -1, 0, -1,  0, 0, 0, 0,  0, 0, 0, 0 }, // xxx_
                                 //
                                 new[] { -1, -1, 0, 0, 0, 0, 0, 0, 0 }, // xx_
                                 new[] { 0, 0, 0, -1, -1, 0, 0, 0, 0 }, // xx_
                                 new[] { 0, 0, 0, 0, 0, 0, -1, -1, 0 }, // xx_
                                 //
                                 new[] { 0, -1, -1, 0, 0, 0, 0, 0, 0 }, // _xx
                                 new[] { 0, 0, 0, 0, -1, -1, 0, 0, 0 }, // _xx
                                 new[] { 0, 0, 0, 0, 0, 0, 0, -1, -1 }, // _xx
                                 //
                                 new[] { -1, 0, -1, 0, 0, 0, 0, 0, 0 }, // x_x
                                 new[] { 0, 0, 0, -1, 0, -1, 0, 0, 0 }, // x_x
                                 new[] { 0, 0, 0, 0, 0, 0, -1, 0, -1 } // x_x
                               };

            var positions = new[]
                {
                    new[] { 2, 0 }, // xx_
                    //
                    new[] { 2, 0 }, // xx_
                    new[] { 2, 1 }, // xx_
                    new[] { 2, 2 }, // xx_
                    //
                    new[] { 0, 0 }, // _xx
                    new[] { 0, 1 }, // _xx
                    new[] { 0, 2 }, // _xx
                    //
                    new[] { 1, 0 }, // x_x
                    new[] { 1, 1 }, // x_x
                    new[] { 1, 2 }  // x_x
                };

            var sizes = new[]
                {
                    new[] { 4, 3 },
                    //
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    //
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    //
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    new[] { 3, 3 }
                };

            for (var i = 0; i < boards.Length; i++)
            {
                var board = boards[i];

                var g = new CurrentGame(new Board(board, sizes[i][0], sizes[i][1]));

                var brainResult = new BrainResult();
                var canMove = GameBrain.GetStraightWinningMove(false, false, 1, brainResult, g.Board);

                try
                {
                    Assert.AreEqual(positions[i][0], brainResult.Moves[0].X);
                    Assert.AreEqual(positions[i][1], brainResult.Moves[0].Y);
                    Assert.AreEqual(true, canMove);
                }
                catch
                {
                    UnitTestHelpers.PrintBoard(board, brainResult.Moves[0].X, brainResult.Moves[0].Y, canMove, sizes[i][0]);

                    throw;
                }
            }
        }
Exemplo n.º 34
0
        public void GetVerticalWinningMoveTestMethod()
        {
            var boards = new[]
                {
                    // 4x4
                    new[] { 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
                    new[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
                    new[] { 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0 },
                    //
                    // 3x3
                    new[] { 1, 0, 0, 1, 0, 0, 0, 0, 0 },
                    new[] { 0, 1, 0, 0, 1, 0, 0, 0, 0 },
                    new[] { 0, 0, 1, 0, 0, 1, 0, 0, 0 },
                    //
                    new[] { 1, 0, 0, 0, 0, 0, 1, 0, 0 },
                    new[] { 0, 1, 0, 0, 0, 0, 0, 1, 0 },
                    new[] { 0, 0, 1, 0, 0, 0, 0, 0, 1 },
                    //
                    new[] { 0, 0, 0, 1, 0, 0, 1, 0, 0 },
                    new[] { 0, 0, 0, 0, 1, 0, 0, 1, 0 },
                    new[] { 0, 0, 0, 0, 0, 1, 0, 0, 1 }
                };

            var positions = new[]
                {
                    new[] { 0, 3 },
                    new[] { 1, 2 },
                    new[] { 0, 2 },
                    //
                    new[] { 0, 2 },
                    new[] { 1, 2 },
                    new[] { 2, 2 },
                    //
                    new[] { 0, 1 },
                    new[] { 1, 1 },
                    new[] { 2, 1 },
                    //
                    new[] { 0, 0 },
                    new[] { 1, 0 },
                    new[] { 2, 0 }
                };

            var sizes = new[]
                {
                    new[] { 4, 4 },
                    new[] { 4, 3 },
                    new[] { 3, 4 },
                    //
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    //
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    //
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    new[] { 3, 3 }
                };

            for (var i = 0; i < boards.Length; i++)
            {
                var g = new CurrentGame(new Board(boards[i], sizes[i][0], sizes[i][1]));

                var brainResult = new BrainResult();
                var canMove = GameBrain.GetStraightWinningMove(true, true, 1, brainResult, g.Board);

                try
                {
                    Assert.AreEqual(true, canMove);
                    Assert.AreEqual(positions[i][0], brainResult.Moves[0].X);
                    Assert.AreEqual(positions[i][1], brainResult.Moves[0].Y);
                }
                catch
                {
                    Console.WriteLine("Test: " + i);
                    var x = canMove ? brainResult.Moves[0].X : -1;
                    var y = canMove ? brainResult.Moves[0].Y : -1;
                    UnitTestHelpers.PrintBoard(boards[i], x, y, canMove, sizes[i][0]);

                    throw;
                }
            }
        }
Exemplo n.º 35
0
        public void GetDiagonalWinningMoveTestMethod()
        {
            var boards = new[]
                {
                    new[] { 1, 0, 0, 0,  0, 1, 0, 0,  0, 0, 1, 0,  0, 0, 0, 0 },
                    //
                    new[] { 1, 0, 0, 0, 1, 0, 0, 0, 0 },
                    new[] { 1, 0, 0, 0, 0, 0, 0, 0, 1 },
                    new[] { 0, 0, 0, 0, 1, 0, 0, 0, 1 },
                    //
                    new[] { 0, 0, 1, 0, 1, 0, 0, 0, 0 },
                    new[] { 0, 0, 1, 0, 0, 0, 1, 0, 0 },
                    new[] { 0, 0, 0, 0, 1, 0, 1, 0, 0 }
                };

            var positions = new[]
                {
                    new[] { 3, 3 },
                    //
                    new[] { 2, 2 },
                    new[] { 1, 1 },
                    new[] { 0, 0 },
                    //
                    new[] { 0, 2 },
                    new[] { 1, 1 },
                    new[] { 2, 0 },
                };

            var sizes = new[]
                {
                    new[] { 4, 4 },
                    //
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    //
                    new[] { 3, 3 },
                    new[] { 3, 3 },
                    new[] { 3, 3 }
                };

            for (var i = 0; i < boards.Length; i++)
            {
                var g = new CurrentGame(new Board(boards[i], sizes[i][0], sizes[i][1]));
                var brainResult = new BrainResult();
                var canMove = GameBrain.GetDiagonalWinningMove(true, brainResult, g.Board);

                try
                {
                    Assert.AreEqual(positions[i][0], brainResult.Moves[0].X);
                    Assert.AreEqual(positions[i][1], brainResult.Moves[0].Y);
                    Assert.AreEqual(true, canMove);

                    UnitTestHelpers.PrintBoard(boards[i], brainResult.Moves[0].X, brainResult.Moves[0].Y, canMove, sizes[i][0]);
                }
                catch
                {
                    UnitTestHelpers.PrintBoard(boards[i], brainResult.Moves[0].X, brainResult.Moves[0].Y, canMove, sizes[i][0]);

                    throw;
                }
            }
        }