public void RecursiveOpen(int x, int y, Minefield mine)
 {
     if (mine.isOpened())
     {
         return;
     }
     else
     {
         if (mine.bombInProximity != 0 || mine.CheckBomb())
         {
             mine.OpenCover();
             return;
         }
         else
         {
             mine.OpenCover();
             if (y + 1 < fieldHeight)
             {
                 RecursiveOpen(x, y + 1, field[x, y + 1].GetComponent <Minefield>());
             }
             if (x + 1 < fieldWidth)
             {
                 RecursiveOpen(x + 1, y, field[x + 1, y].GetComponent <Minefield>());
             }
             if (y - 1 >= 0)
             {
                 RecursiveOpen(x, y - 1, field[x, y - 1].GetComponent <Minefield>());
             }
             if (x - 1 >= 0)
             {
                 RecursiveOpen(x - 1, y, field[x - 1, y].GetComponent <Minefield>());
             }
         }
     }
 }
Exemple #2
0
    /// <summary>
    /// Sets the position of this Bar regarding to the size of the minefield
    /// </summary>
    /// <param name="minefield">The Minefield that calls this position. And has the information about the size of the minefield</param>
    public void SetPosition(Minefield minefield)
    {
        transform.position = topBar ? new Vector2(0, +((minefield.yTotal - 1f) / 2f + 2f)) : new Vector2(0, -((minefield.yTotal - 1f) / 2f + 2f));
        RectTransform rectTrans = (RectTransform)transform;

        rectTrans.sizeDelta = new Vector2(minefield.xTotal + height, height);
    }
Exemple #3
0
        public void AllNonBombsUncovered_NoneUncovered_ReturnsFalse()
        {
            Minefield minefield = new Minefield(DEFAULT_FIELD_SIZE);

            minefield.AddBombs(DEFAULT_BOMBS);
            Assert.IsFalse(minefield.AllNonBombsUncovered());
        }
Exemple #4
0
    /// <summary>
    /// Creates a new Tile
    /// </summary>
    /// <param name="x">The X-Position to create the new Tile</param>
    /// <param name="y">The y-Position to create the new Tile</param>
    /// <returns>The created tile</returns>
    public static Tile CreateNewTile(int x, int y)
    {
        //  Instantiate the new Tile
        GameObject tile = (GameObject)Instantiate(Resources.Load("Prefabs/Tile"));

        //  Find the parent (for hirachy)
        GameObject tiles = GameObject.FindGameObjectWithTag("Tiles");

        //  Find the minefield
        Minefield mineField = GameObject.FindGameObjectWithTag("Minefield").GetComponent <Minefield>();

        //  Inherit the Positions to the Tile-Script-Child
        tile.GetComponent <Tile>().x = x;
        tile.GetComponent <Tile>().y = y;

        //  Move it into the parent (hirachy)
        tile.transform.parent = tiles.transform;

        //  Set Position within the minefield
        tile.transform.position = new Vector2(
            (float)x - ((float)mineField.xTotal - 1f) / 2f,
            (float)y - ((float)mineField.yTotal - 1f) / 2f
            );

        //  Return the created tile
        return(tile.GetComponent <Tile>());
    }
Exemple #5
0
        /// <summary>
        /// Check if the fleet hits the minefiled.
        /// </summary>
        /// <remarks>
        /// The probability of hitting a mine is 0.3% per light year traveled for each
        /// warp over the safe speed.
        /// TODO (priority 3) - reference required.
        ///
        /// Example: A fleet traveling at Warp 9 has a 1.5% chance per light year
        /// traveled in a turn.  Traveling 10 light years through the Minefield that
        /// turn, the fleet has a 10.5% chance of triggering a mine.
        /// </remarks>
        /// <param name="fleet">The moving fleet.</param>
        /// <param name="minefield">The minefield being traversed.</param>
        /// <returns>true if the minefield is hit.</returns>
        private bool CheckForHit(Fleet fleet, Minefield minefield)
        {
            // Calculate how long we are going to be in the Minefield. This is the
            // lesser of the distance to the next waypoint and the radius of the
            // field.

            NovaPoint currentPosition = fleet.Position;
            Waypoint  targetWaypoint  = fleet.Waypoints[0];
            NovaPoint targetPosition  = targetWaypoint.Position;

            double travelDistance = PointUtilities.Distance(currentPosition, targetPosition);

            if (minefield.Radius > (int)travelDistance)
            {
                travelDistance = minefield.Radius;
            }

            double speeding    = fleet.Speed - minefield.SafeSpeed;
            double probability = (0.03 * travelDistance * speeding) * 100;
            double dice        = random.Next(0, 100);

            if (dice < probability)
            {
                return(true);
            }

            return(false);
        }
Exemple #6
0
        static void Main(string[] args)
        {
            string settingsFilePath = args.Length > 0 ? args[0] : string.Empty;

            while (string.IsNullOrEmpty(settingsFilePath))
            {
                Console.WriteLine("Provide path to game settings");
                settingsFilePath = Console.ReadLine();
            }

            var settingsTxt = File.ReadAllLines(settingsFilePath);

            var settings = GameSettingsReader.LoadSettings(settingsTxt);

            if (settings != null && settings.Valid())
            {
                foreach (var actionList in settings.ActionsLists)
                {
                    var board     = new Board(settings.BoardWidth, settings.BoardHeight, settings.Mines, settings.ExitPoint);
                    var turtle    = new Turtle(settings.StartingPoint, settings.StartingDirection);
                    var minefield = new Minefield(board, turtle);
                    Console.WriteLine($"Result: {minefield.TryEscape(actionList)}");
                }
            }
            else
            {
                Console.WriteLine("Invalid settings provided!");
            }
        }
Exemple #7
0
        public void AllNonBombsUncovered_OnlyBombsInField_ReturnsTrue()
        {
            Minefield minefield = new Minefield(DEFAULT_FIELD_SIZE);

            minefield.AddBombs(DEFAULT_FIELD_SIZE * DEFAULT_FIELD_SIZE); // Filling the field with bombs.

            Assert.IsTrue(minefield.AllNonBombsUncovered());
        }
Exemple #8
0
        public void WhenACoordinateHasBeenExploredThenIsExploredIsTrue()
        {
            var minefield         = Minefield.Empty(2, 3);
            var coordinate        = new Coordinates(0, 1);
            var exploredMinefield = minefield.Explore(coordinate);

            Assert.AreEqual(true, exploredMinefield.IsExplored(coordinate.RowIndex, coordinate.ColumnIndex));
        }
Exemple #9
0
        public void AllNonBombsUncovered_AllUncoveredNoBombs_ReturnsTrue()
        {
            Minefield minefield = new Minefield(DEFAULT_FIELD_SIZE);

            minefield.UncoverNode(0, 0);

            Assert.IsTrue(minefield.AllNonBombsUncovered());
        }
Exemple #10
0
        public void UncoverNode_BombUncovered_ReturnsTrue()
        {
            Minefield minefield = new Minefield(DEFAULT_FIELD_SIZE);

            minefield.AddBombs(DEFAULT_FIELD_SIZE * DEFAULT_FIELD_SIZE); // Filling the field with bombs.

            Assert.IsTrue(minefield.UncoverNode(0, 0));
        }
 public void init(Minefield kworld, int kid)
 {
     Start();
     setWorld(kworld);
     setId(kid);
     spriteRenderer.sprite = kworld.sprites[10];
     // Debug.Log(spriteRenderer); // unrevealed yet
 }
Exemple #12
0
        public void InitiallyAllMineLocationsUnexplored()
        {
            var minefield = Minefield.Empty(2, 3);

            Assert.AreEqual(false, minefield.IsExplored(0, 0));
            Assert.AreEqual(false, minefield.IsExplored(2, 1));
            Assert.AreEqual(false, minefield.IsExplored(1, 1));
        }
Exemple #13
0
        /// <summary>
        /// Generates the output
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public string GenerateOutput(string input)
        {
            List <Minefield> minefields = new List <Minefield>();
            Minefield        minefield  = null;
            StringBuilder    output     = new StringBuilder();

            string[] delimiter = { Environment.NewLine };
            string[] words     = input.Split(delimiter, StringSplitOptions.None);

            foreach (string s in words)
            {
                if (MinefieldValidator.IsHeader(s))
                {
                    minefield = MinefieldFactory.Create(minefields.Count + 1, s);
                    minefields.Add(minefield);
                }
                else if (MinefieldValidator.isFooter(s))
                {
                    break;
                }
                else
                {
                    foreach (char c in s.ToCharArray())
                    {
                        if (CellValidator.isMineOrSafe(c.ToString()))
                        {
                            minefield.Cells.Add(CellFactory.Create(c));
                        }
                        else
                        {
                            ErroMessage = "Your input data is not valid.";
                            return(output.ToString());
                        }
                    }
                }
            }
            try
            {
                foreach (Minefield field in minefields)
                {
                    MinesweeperConverter converter = new MinesweeperConverter();
                    converter.ConvertMinefield(field);
                    //header
                    output.Append(String.Format(MinefieldValidator.headerOutput, field.Id));
                    output.Append(Environment.NewLine);
                    //result
                    output.Append(converter.output);
                    output.Append(Environment.NewLine);
                }
            }
            catch
            {
                ErroMessage = "Your input data is not valid.";
                return(output.ToString());
            }

            return(output.ToString());
        }
Exemple #14
0
        public void ExploringARowTwiceWorks()
        {
            var       minefield                = Minefield.Empty(2, 3);
            Minefield exploredMinefield        = minefield.Explore(new Coordinates(0, 1));
            Minefield furtherExploredMinefield = exploredMinefield.Explore(new Coordinates(0, 0));

            Assert.AreEqual(true, furtherExploredMinefield.IsExplored(0, 0));
            Assert.AreEqual(true, furtherExploredMinefield.IsExplored(0, 1));
        }
Exemple #15
0
        public void ExploreDifferentRowsOnce()
        {
            var       minefield                = Minefield.Empty(2, 3);
            Minefield exploredMinefield        = minefield.Explore(new Coordinates(0, 1));
            Minefield furtherExploredMinefield = exploredMinefield.Explore(new Coordinates(1, 0));

            Assert.AreEqual(true, furtherExploredMinefield.IsExplored(1, 0));
            Assert.AreEqual(true, furtherExploredMinefield.IsExplored(0, 1));
        }
    // Use this for initialization
    void Start()
    {
        // Find gameobject outside its scope
        minefield = GameObject.FindGameObjectWithTag("Minefield").GetComponent <Minefield>();

        // Get component from self's gameobject
        spriteController = GetComponent <SpriteController>();
        tile             = GetComponent <Tile>();
    }
Exemple #17
0
        public void FieldMarkedAsMine_UndoExecuteMarkAsMineCommand_FieldIsNotMarkedAsMine()
        {
            this.Minefield = TestMinefieldFactory.CreateMinefield(MarkedMine);
            var command = new MarkAsMineCommand(this.Minefield, this.Middle);

            command.UndoExecution();

            Assert.Equal(0, Minefield.Count(x => x.BombMarked)); // Too many fields marked as mine.
        }
 public void UnexploredSquaresAreShownAsHashes()
 {
     // Given
     var minefield = new Minefield(3, 2);
     // When
     var result = MinefieldRenderer.RenderMinefield(minefield);
     // Then
     var expected = " 123\nA###\nB###\n";
     Assert.AreEqual(expected, result);
 }
Exemple #19
0
        /// <summary>
        /// Returns the minefield
        /// </summary>
        /// <param name="id"></param>
        /// <param name="result"></param>
        /// <param name="neighborMines"></param>
        public void DrawMinefield(Minefield field)
        {
            MinesweeperConverter converter = new MinesweeperConverter();

            converter.ConvertMinefield(field);

            this.renderer.WriteLine(String.Format(MinefieldValidator.headerOutput, field.Id));
            this.renderer.Write(converter.output.ToString());
            this.renderer.WriteLine();
        }
Exemple #20
0
        public void FieldNotMarkedAsMine_ExecuteMarkAsMineCommand_FieldIsMarkedAsMine()
        {
            this.Minefield = TestMinefieldFactory.CreateMinefield(HiddenMine);
            var command = new MarkAsMineCommand(this.Minefield, this.Middle);

            command.Execute();

            Assert.True(Minefield.GetValue(Middle).BombMarked);  // Field not marked as mine.
            Assert.Equal(1, Minefield.Count(x => x.BombMarked)); // Too many fields marked as mine.
        }
 public void ExploredSquaresAreShownAsSpaces()
 {
     // Given
     var minefield = new Minefield(3, 2).Explore(new Coordinates(0, 1));
     // When
     var result = MinefieldRenderer.RenderMinefield(minefield);
     // Then
     var expected = " 123\nA# #\nB###\n";
     Assert.AreEqual(expected, result);
 }
        public void CreateCell()
        {
            ICellFactory            factory   = new CellFactory();
            IMinePositionsGenerator generator = Substitute.For <IMinePositionsGenerator>();
            IMinefield field = new Minefield(factory, generator);

            ICell cell = factory.CreateCell(field, 0, 0);

            Assert.AreEqual(new Cell(field, 0, 0), cell);
        }
Exemple #23
0
    public static void Main()
    {
        int fieldDimension = 9;
        int mineCount      = 10;

        StartView();
        Console.CursorVisible = false;
        bool playerIsAddicted = true;

        while (playerIsAddicted)
        {
            Minefield board = new Minefield(fieldDimension, mineCount);
            while (board.PlayerWon == board.PlayerLost)
            {
                Console.Clear();
                board.Preview(); // should be false
                PrintControls();

                Console.SetCursorPosition(11, 8);//left bottom corner of board coords at 9x9
                Console.Write($"Flags left: {mineCount - board.FlagCounter}");

                var userInput = Console.ReadKey();

                board.ProcessCommand(userInput);

                board.UpdateGameState();
            }
            Delay(1000);
            Console.Clear();
            board.Preview();
            Console.WriteLine();
            if (board.PlayerWon)
            {
                Console.WriteLine("Congratulations! You won.");
            }
            else
            {
                Console.WriteLine("Unlucky! You lost.");
            }

            Console.WriteLine("\nTry again?");

            char input = (char)Console.Read();
            playerIsAddicted = input == 'y' || input == 'Y' /* || true */;
        }

        Console.WriteLine("Thanks for playing!");
        Delay(1000);
        for (int i = 3; i > 0; i--)
        {
            Console.Write($"\rLeaving in {i}");
            Delay(1000);
        }
    }
Exemple #24
0
        public void UnexploredSquaresAreShownAsHashes()
        {
            // Given
            var minefield = Minefield.Empty(3, 2);
            // When
            var result = MinefieldRenderer.RenderMinefield(minefield);
            // Then
            var expected = " 123\nA###\nB###\n";

            Assert.AreEqual(expected, result);
        }
Exemple #25
0
        public void ExploredSquaresAreShownAsSpaces()
        {
            // Given
            var minefield = Minefield.Empty(3, 2).Explore(new Coordinates(0, 1));
            // When
            var result = MinefieldRenderer.RenderMinefield(minefield);
            // Then
            var expected = " 123\nA# #\nB###\n";

            Assert.AreEqual(expected, result);
        }
 private void SetMineImage(int height, int width)
 {
     for (int i = 0; i < height; i++)
     {
         for (int j = 0; j < width; j++)
         {
             //Debug.Log(i + ", " + j);
             Minefield mine = field[i, j].GetComponent <Minefield>();
             mine.SetContent();
         }
     }
 }
Exemple #27
0
        public void Initialize(Minefield minefield)
        {
            if (minefield == null)
            {
                throw new ArgumentNullException(nameof(minefield));
            }

            this.TerminalPrinter.Minefield = minefield;
            var commandFactory = new CommandFactory(minefield);

            this.TerminalReader.Initialize(minefield, commandFactory);
        }
        public void ExecuteMoves_TurtleFindsExit_ReturnsTurtleExit()
        {
            // Arrange
            var setupLines = new string[] { "4 4", "1,1 2,2", "2 3", "0 0 E", "M M M", "R M M M", "R M" };

            // Act
            var minefield = new Minefield(setupLines);
            var result    = minefield.ExecuteMoves();

            // Assert
            Assert.Equal(Result.TurtleExit, result);
        }
        public void ExecuteMoves_TurtleStepsOutsideGrid_ReturnsTurtleOutside()
        {
            // Arrange
            var setupLines = new string[] { "4 4", "1,1 2,2", "2 3", "0 0 E", "M M M M M M" };

            // Act
            var minefield = new Minefield(setupLines);
            var result    = minefield.ExecuteMoves();

            // Assert
            Assert.Equal(Result.TurtleOutside, result);
        }
        /// <summary>
        /// Создаёт минное со стандартной фабрикой клеток и генератором мин со случайным порядком.
        /// </summary>
        /// <returns></returns>
        public static IMinefield CreateDefaultMinefield()
        {
            IMinefield   field    = new Minefield(DefaultCellFactory, DefaultMinePositionsGenerator);
            SettingsItem settings = new SettingsItem();

            settings.Height    = 10;
            settings.Width     = 10;
            settings.MineCount = 10;
            field.SetGameSettings(settings);
            field.Fill();
            return(field);
        }
Exemple #31
0
        /// <summary>
        /// We've hit a mine. Inflict appropriate damage to the fleet and bring it to a
        /// stop. If all ships are gone destroy the fleet.
        ///
        /// Let's start with the simplest algoritm:
        ///
        /// 5 destroyers take 500dp damage = 100dp each = 50dp to armor, 50dp to shields
        /// (absorbed).
        /// </summary>
        /// <param name="fleet">The fleet that hit the minefield.</param>
        /// <param name="minefield">The minefield being impacted.</param>
        private void InflictDamage(Fleet fleet, Minefield minefield)
        {
            int shipDamage = 100 / 2;
            int shipsLost  = 0;

            fleet.Speed = 0;

            List <ShipToken> tokensToRemove = new List <ShipToken>();

            foreach (ShipToken token in fleet.Composition.Values)
            {
                token.Armor -= shipDamage;

                if (token.Damage >= 100)
                {
                    tokensToRemove.Add(token);
                    shipsLost++;
                }
            }

            foreach (ShipToken removeToken in tokensToRemove)
            {
                fleet.Composition.Remove(removeToken.Key);
            }

            Message message = new Message();

            message.Audience = fleet.Owner;
            message.Event    = "Minefield";
            message.Text     = "Fleet " + fleet.Name
                               + " has hit a Minefield." + "\n\n";

            if (shipsLost == 0)
            {
                message.Text += "None of your ships were destroyed.";
                fleet.Speed   = 0;
            }
            else if (fleet.Composition.Count != 0)
            {
                message.Text += shipsLost.ToString(System.Globalization.CultureInfo.InvariantCulture)
                                + " of your ships were destroyed.\n";
            }
            else
            {
                message.Text += "All of your ships were destroyed.\n";
                message.Text += "You lost this fleet.";
                serverState.AllEmpires[fleet.Owner].OwnedFleets.Remove(fleet.Key);
                serverState.AllEmpires[fleet.Owner].FleetReports.Remove(fleet.Key);
            }

            serverState.AllMessages.Add(message);
        }
Exemple #32
0
        public void FillFromSettingsObject()
        {
            SettingsItem            settings  = CreateCustomSettings(10, 11, 9);
            IMinePositionsGenerator generator = new RandomMinePositionGenerator();
            IMinefield field = new Minefield(new CellFactory(), generator);

            field.SetGameSettings(settings);
            field.Fill();

            Assert.AreEqual(10, field.Height);
            Assert.AreEqual(11, field.Width);
            Assert.AreEqual(9, field.MinesCount);
        }
Exemple #33
0
        public void OpenCellHandlerShouldOpenOneCell()
        {
            // Arrange;
            testMinefield = new MinefieldEasy(5, 5, 2, randomGenerator.Object);
            cellPosition.Setup(x => x.Col).Returns(0);
            cellPosition.Setup(x => x.Row).Returns(0);

            // Act
            var result = testMinefield.OpenCellHandler(cellPosition.Object);
            var opened = testMinefield.OpenedCellsCount;

            // Assert
            Assert.AreEqual(1, opened);
            Assert.AreEqual(CellActionResult.Normal, result);
        }
Exemple #34
0
        public void OpenCellHandlerShouldReturnCorrectStateEnumerationValueNormalWthChainedOpening()
        {
            // Arrange;
            testMinefield = new MinefieldEasy(5, 5, 2, randomGenerator.Object);

            cellPosition.Setup(x => x.Col).Returns(2);
            cellPosition.Setup(x => x.Row).Returns(2);

            // Act
            var result = testMinefield.OpenCellHandler(cellPosition.Object);
            var opened = testMinefield.OpenedCellsCount;

            // Assert
            Assert.AreEqual(23, opened);
            Assert.AreEqual(CellActionResult.Normal, result);
        }
 protected void OnLoad(object sender, EventArgs e)
 {
     // load textures into array
     for (var i = 0; i < _stateTextures.Length; i++)
     {
         using (var bitmap = new Bitmap(Path.Combine("Data/Textures/", _stateTextures[i])))
         {
             bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
             if (_textureArray == null) BitmapTexture.CreateCompatible(bitmap, out _textureArray, _stateTextures.Length, 1);
             _textureArray.LoadBitmap(bitmap, i);
         }
     }
     // initialize buffer
     var field = new Minefield[FieldWidth*FieldHeight];
     for (var i = 0; i < field.Length; i++)
     {
         field[i] = new Minefield(i%FieldWidth, i/FieldHeight, i%_stateTextures.Length);
     }
     _buffer = new Buffer<Minefield>();
     _buffer.Init(BufferTarget.ArrayBuffer, field);
     // load program
     _gridProgram = ProgramFactory.Create<TextureGridProgram>();
     _gridProgram.Use();
     // bind the texture and set uniform
     _gridProgram.TextureData.BindTexture(TextureUnit.Texture0, _textureArray);
     // set up vertex array and attributes
     _vao = new VertexArray();
     _vao.Bind();
     _vao.BindAttribute(_gridProgram.InPosition, _buffer);
     _vao.BindAttribute(_gridProgram.InTexture, _buffer, 8);
     // set nice clear color
     GL.ClearColor(Color.MidnightBlue);
     // initialize camera position
     Camera.DefaultState.Position = new Vector3(0, 5, 15);
     Camera.ResetToDefault();
 }
Exemple #36
0
 public void Initialize()
 {
     testMinefield = new Minefield(5, 5, 2, randomGenerator.Object);
 }
Exemple #37
0
 public void MinefieldConstructorRecievingIncorrectMinesNumberShouldThrowAnException()
 {
     // Arrange
     var testMineField = new Minefield(5, 5, 0, randomGenerator.Object);
 }
Exemple #38
0
        /// <summary>
        /// Generates randomly mined minefield.
        /// </summary>
        public void GenerateMinefield()
        {
            // Create new minefield by Factory Method
            this.minefield = this.CreateMinefield(this.minefieldRows, this.minefieldCols);

            // Show minefield
            this.RedrawMinefield(false);
            this.uiManager.ClearCommandLine(this.prompt);
        }
Exemple #39
0
 public void MinefieldConstructorRecievingNullRandomGeneratorProviderShouldThrowAnException()
 {
     // Arrange
     var testMineField = new Minefield(5, 5, 2, null);
 }