Exemplo n.º 1
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var setupShips = (SetupShips)validationContext.ObjectInstance;
            var setupBoard = new SetupBoard();

            Ship thisShip = null;

            foreach (var ship in setupShips.GetValidStructuralShips())
            {
                if (ship.propertyName == validationContext.MemberName)
                {
                    thisShip = ship.ship;
                    continue;
                }

                // Add all other ships
                setupBoard.AddShip(ship.ship);
            }

            if (thisShip == null) // Isn't valid enough to test - TODO: Rework this to avoid the foreach, just exit
            {
                return(null);
            }

            // Now add target ship, to get error for this one specifically
            var result = setupBoard.AddShip(thisShip);

            if (!result.Success)
            {
                return(new ValidationResult(result.Error, new[] { validationContext.MemberName }));
            }

            return(null);
        }
Exemplo n.º 2
0
        public void SetupBoardDefaultsInvalid()
        {
            // When
            var setupBoard = new SetupBoard();

            // Then
            Assert.False(setupBoard.IsValid);
        }
Exemplo n.º 3
0
        public bool RunSetup(PlayerGrid playerGrid)
        {
            SetupBoard = new SetupBoard();
            var error = string.Empty;

            while (!SetupBoard.IsValid)
            {
                var errorDisplay = error.Length > 0 ? $" [{error}]" : "";
                var input        = m_CommandInput.WaitForInput($"Enter coords of Ship length {SetupBoard.NextShip}, e.g. A0 A4{errorDisplay}");
                // TODO: Note that you can enter in any order, so why ask?

                if (input.ToLowerInvariant() == "exit")
                {
                    return(false);
                }

                if (!s_Regex.IsMatch(input))
                {
                    error = $"Input not recognised as Ship Coordinates '{input}'";
                    continue;
                }

                var  coords = input.Split(' ');
                Ship ship;
                try
                {
                    ship = new Ship(coords[0], coords[1]);
                }
                catch (ArgumentException ex)
                {
                    error = ex.Message;
                    continue;
                }

                error = string.Empty;

                var result = SetupBoard.AddShip(ship);

                if (!result.Success)
                {
                    error = result.Error;
                }
                else
                {
                    playerGrid.DrawShip(ship);
                }
            }

            return(true);
        }
Exemplo n.º 4
0
        public void GenerateRandomCreatesValidRandomBoard()
        {
            // Given
            var setupBoardOne = new SetupBoard();
            var setupBoardTwo = new SetupBoard();

            // When
            setupBoardOne.GenerateRandom();
            setupBoardTwo.GenerateRandom();

            // Then
            Assert.True(setupBoardOne.IsValid);
            Assert.True(setupBoardTwo.IsValid);
            Assert.False(setupBoardOne.ShipsByOccupationPoints.Keys.All(p => setupBoardTwo.ShipsByOccupationPoints.ContainsKey(p)));
        }
Exemplo n.º 5
0
        public void GameCtorThrowsIfSetupBoardInvalid()
        {
            // Given
            var setupBoard = new SetupBoard();

            Assert.False(setupBoard.IsValid);

            // When
            var ex = Record.Exception(() => new Game(setupBoard));

            // Then
            Assert.NotNull(ex);
            var argEx = Assert.IsType <ArgumentException>(ex);

            Assert.Contains("is not valid.", argEx.Message);
        }
Exemplo n.º 6
0
        public void SetupBoardHasCorrectNextShipRequired()
        {
            var setupBoard = new SetupBoard();

            Assert.Equal(5, setupBoard.NextShip);

            setupBoard.AddShip(("E0", "E4"));
            Assert.Equal(4, setupBoard.NextShip);

            setupBoard.AddShip(("D0", "D3"));
            Assert.Equal(3, setupBoard.NextShip);

            setupBoard.AddShip(("C0", "C2"));
            Assert.Equal(3, setupBoard.NextShip);

            setupBoard.AddShip(("B0", "B2"));
            Assert.Equal(2, setupBoard.NextShip);

            setupBoard.AddShip(("A0", "A1"));
            Assert.Null(setupBoard.NextShip);
        }
        private NetworkGameState CalculateStartingConditions()
        {
            Debug.LogError("Calculating start");

            PlayerTurnOrder hostOrder = PlayerTurnOrder.Undecided;

            switch (lobby.OrderChoice)
            {
            case LobbyTurnOrderChoice.HostIsFirst:
                hostOrder = PlayerTurnOrder.First;
                break;

            case LobbyTurnOrderChoice.ClientIsFirst:
                hostOrder = PlayerTurnOrder.Second;
                break;

            default: {
                bool hostFirst = UnityEngine.Random.value < 0.5f;
                hostOrder = hostFirst ? PlayerTurnOrder.First : PlayerTurnOrder.Second;
            }
            break;
            }

            NetworkGameState gsc = new NetworkGameState()
            {
                hostPlayerOrder = hostOrder,
                turnNumber      = 0,
                activePlayer    = PlayerTurnOrder.First,
                turnState       = TurnState.None,
            };

            SetupBoard lBoard = new SetupBoard();

            lBoard.Width  = db.BoardDimensions.x;
            lBoard.Length = db.BoardDimensions.y;
            ScriptRuntimeException luaException;

            scripts.CallFunction(db.SetupFunction, lBoard, out luaException);
            if (luaException != null)
            {
                throw new BoardSetupException(string.Format("Board setup exception: exception in Lua code: {0}", luaException.DecoratedMessage));
            }

            if (lBoard.NumPieces == 0)
            {
                throw new BoardSetupException("Board setup exception: No piece created");
            }
            HashSet <IntVector2> takenPositions = new HashSet <IntVector2>();
            bool anyPlayer1 = false;
            bool anyPlayer2 = false;

            List <NetworkGameStatePiece> pieceList = new List <NetworkGameStatePiece>();

            for (int p = 1; p <= lBoard.NumPieces; p++)
            {
                SetupPiece      lPiece = lBoard.GetPiece(p);
                IntVector2      pos    = TranslatePosition(lPiece, p, takenPositions);
                PlayerTurnOrder player = TranslatePlayer(lPiece, p);
                switch (player)
                {
                case PlayerTurnOrder.First:
                    anyPlayer1 = true;
                    break;

                case PlayerTurnOrder.Second:
                    anyPlayer2 = true;
                    break;
                }
                int prototype = TranslatePrototype(lPiece, p);
                NetworkGameStatePiece piece = new NetworkGameStatePiece()
                {
                    prototypeID      = prototype,
                    owner            = player,
                    position         = pos,
                    isCaptured       = false,
                    numberMovesTaken = 0,
                };
                pieceList.Add(piece);
            }

            if (!anyPlayer1)
            {
                throw new BoardSetupException("Board setup exception: First player given no pieces");
            }
            else if (!anyPlayer2)
            {
                throw new BoardSetupException("Board setup exception: Second player given no pieces");
            }

            gsc.pieces = pieceList.ToArray();

            return(gsc);
        }
Exemplo n.º 8
0
        public void RunPlay(SetupBoard setupBoard, PlayerGrid playerGrid, PlayerGrid computerGrid)
        {
            var game  = new Game(setupBoard);
            var error = string.Empty;

            while (true)
            {
                if (game.Turn == Players.PlayerOne)
                {
                    var errorDisplay = error.Length > 0 ? $" [{error}]" : "";
                    var input        = m_CommandInput.WaitForInput($"Enter a Target coordinate, e.g. A0{errorDisplay}");

                    if (!s_Regex.IsMatch(input))
                    {
                        error = $"Input not recognised as a Target Coordinate '{input}'";
                        continue;
                    }

                    PlayFireSound();
                    m_CommandInput.ShowMessage($"Firing on {input.ToUpper()}...");

                    FireResult fireResult;
                    try
                    {
                        fireResult = game.Fire(input);
                    }
                    catch (ArgumentException ex)
                    {
                        error = ex.Message;
                        continue;
                    }

                    error = string.Empty;

                    computerGrid.DrawTarget(fireResult.Target.Point, fireResult.IsHit);

                    if (fireResult.IsHit)
                    {
                        PlayHitSound();
                    }

                    m_CommandInput.ShowMessage(fireResult.IsSunkShip ? $"HIT {fireResult.Target}. YOU'VE SUNK A SHIP OF LENGTH {fireResult.ShipSunk.Length}!" : fireResult.IsHit ? $"HIT {fireResult.Target}" : "Missed.");

                    if (fireResult.IsSunkShip)
                    {
                        computerGrid.DrawShip(fireResult.ShipSunk);
                        PlaySunkSound();
                    }

                    if (fireResult.HaveWon)
                    {
                        m_CommandInput.ShowMessage("YOU WIN!!!", ConsoleColor.Green);
                        PlayWinSound();
                        m_CommandInput.WaitForInput("YOU WIN!!!       (Press Enter to exit)", ConsoleColor.Green);
                        break;
                    }
                    else
                    {
                        Thread.Sleep(1000);
                        m_CommandInput.ShowMessage("Incoming...");
                    }
                }
                else
                {
                    PlayIncomingSound();

                    var fireResult = game.OpponentsTurn();
                    playerGrid.DrawTarget(fireResult.Target.Point, fireResult.IsHit);

                    if (fireResult.IsHit)
                    {
                        PlayHitSound();
                    }

                    m_CommandInput.ShowMessage(fireResult.IsSunkShip ? $"Opponent Hits {fireResult.Target}. Has Sunk your {fireResult.ShipSunk.Length}!" : fireResult.IsHit ? $"Opponent Hits {fireResult.Target}" : "Opponent Missed.");

                    if (fireResult.IsSunkShip)
                    {
                        playerGrid.DrawShip(fireResult.ShipSunk);
                        PlaySunkSound();
                    }

                    if (fireResult.HaveWon)
                    {
                        m_CommandInput.ShowMessage("YOU LOSE :(", ConsoleColor.Red);
                        PlayLoseSound();
                        m_CommandInput.WaitForInput("YOU LOSE :(       (Press Enter to exit)", ConsoleColor.Red);
                        break;
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
        }
Exemplo n.º 9
0
 void Start()
 {
     SelectorCase = GameObject.Find("Selector");
     setupBoard   = GetComponent <SetupBoard>();
 }