コード例 #1
0
 private MinesweeperBoard RevealEmpty(MinesweeperBoard board, int x, int y)
 {
     for (int row = -1; row < 2; row++)
     {
         for (int col = -1; col < 2; col++)
         {
             try
             {
                 board.Board[x + row, y + col].IsRevealed = true;
             }
             catch { }
         }
     }
     for (int row = -1; row < 2; row++)
     {
         for (int col = -1; col < 2; col++)
         {
             try
             {
                 if ((board.Board[x + row, y + col].TotalMines == 0) && !ScanAdjacent(board, x + row, y + col))
                 {
                     board = RevealEmpty(board, x + row, y + col);
                 }
             }
             catch { }
         }
     }
     return(board);
 }
コード例 #2
0
        private MinesweeperBoard PerformMove(MinesweeperBoard board, CommandContext ctx, string rawInput, string move, int xPosition)
        {
            var yPosition = 0;

            if (rawInput.Contains("unflag"))
            {
                try
                {
                    yPosition = Int32.Parse(move[1].ToString());
                    board.Board[xPosition, yPosition].Flagged = false;
                }
                catch
                {
                    var msg = ctx.Channel.SendMessageAsync("An input is invalid, make sure you input a letter and a number.");
                    Task.Delay(5000);
                    msg.Result.DeleteAsync();
                }
            }
            else if (rawInput.Contains("flag"))
            {
                try
                {
                    yPosition = Int32.Parse(move[1].ToString());
                    board.Board[xPosition, yPosition].Flagged = true;
                }
                catch
                {
                    var msg = ctx.Channel.SendMessageAsync("An input is invalid, make sure you input a letter and a number.");
                    Task.Delay(5000);
                    msg.Result.DeleteAsync();
                }
            }
            else
            {
                try
                {
                    yPosition = Int32.Parse(move[1].ToString());
                    if (board.Board[xPosition, yPosition].IsRevealed)
                    {
                        Chording(board, xPosition, yPosition);
                    }
                    else
                    {
                        board.Board[xPosition, yPosition].IsRevealed = true;
                    }
                    if (board.Board[xPosition, yPosition].TotalMines == 0)
                    {
                        board = RevealEmpty(board, xPosition, yPosition);
                    }
                }
                catch
                {
                    var msg = ctx.Channel.SendMessageAsync("An input is invalid, make sure you input a letter and a number.");
                    Task.Delay(5000);
                    msg.Result.DeleteAsync();
                }
            }
            return(board);
        }
コード例 #3
0
ファイル: Mode.cs プロジェクト: asd135hp/c-sharp-minesweeper
        public Mode(ModeType type, int width, int height, int bomb)
        {
            var board = new MinesweeperBoard(width, height, bomb);

            board.PopulateBomb();

            Type  = type;
            Board = board;
        }
コード例 #4
0
        private string MakeDisplay(MinesweeperBoard board)
        {
            var display = "  0 1 2 3 4 5 6 7 8 9\n";

            for (int row = 0; row < board.Board.GetLength(0); row++)
            {
                display += row switch
                {
                    0 => "A",
                    1 => "B",
                    2 => "C",
                    3 => "D",
                    4 => "E",
                    5 => "F",
                    6 => "G",
                    7 => "H",
                    8 => "I",
                    _ => "J",
                };
                for (int col = 0; col < board.Board.GetLength(1); col++)
                {
                    if (board.Board[row, col].IsRevealed == false && !board.Board[row, col].Flagged)
                    {
                        display += $" ‏‏‎#";
                    }
                    else if (board.Board[row, col].IsRevealed == false && board.Board[row, col].Flagged)
                    {
                        display += $" ‏‏‎X";
                    }
                    else if (!board.Board[row, col].IsMine)
                    {
                        if (board.Board[row, col].TotalMines == 0)
                        {
                            display += " ‏‏‎ ‏‏‎";
                        }
                        else
                        {
                            display += $" ‏‏‎{board.Board[row, col].TotalMines}";
                        }
                    }
                    else
                    {
                        display += $" ‏‏‎@";
                    }
                }
                display += " ‏‏‎|\n";
            }
            return(display);
        }
コード例 #5
0
        public override void Click(MouseButton clickedButton)
        {
            if (_connection.CurrentData.State == GameState.Playing)
            {
                var position    = SplashKit.MousePosition();
                var p           = _playerProps;
                int squareValue = 0,
                    size        = p.SquareSize,
                    x           = (int)Math.Floor((position.X - p.MarginLeft) / size),
                    y           = (int)Math.Floor((position.Y - p.MarginTop) / size);

                MinesweeperBoard board = (_role == MultiplayerRole.Host ?
                                          _connection.CurrentData.Host :
                                          _connection.CurrentData.Guest).Board as MinesweeperBoard;

                switch (clickedButton)
                {
                case MouseButton.LeftButton:
                    squareValue = board.RevealSquare(x, y);
                    break;

                case MouseButton.RightButton:
                    board.ToggleFlag(x, y);
                    break;
                }

                // if player is winning now (except for 1 edge case on my mind now),
                // change state of the game
                // then closes the connection
                bool isLose = squareValue == -1;
                if (board.IsWin || isLose)
                {
                    _connection.CurrentData.ChangeGameState(
                        _role == MultiplayerRole.Host ?
                        (isLose ? GameState.GuestWin : GameState.HostWin) :
                        (isLose ? GameState.HostWin : GameState.GuestWin)
                        );
                    CloseConnection();

                    // moves the player to result page
                    MultiplayerMinesweeper.UI.ChangeToResultPage(
                        board.Flag,
                        board.Bomb,
                        _connection.TimePlayed,
                        board.IsWin
                        );
                }
            }
        }
コード例 #6
0
 private void ToResultPage(MinesweeperBoard board, bool isWin)
 {
     CleanUp();
     Task.Run(() =>
     {
         // 1500 millisecs is the reasonable time for player to see the bombs on the screen
         Thread.Sleep(1500);
         // go to result page! because you lose/win, you know...
         MultiplayerMinesweeper.UI.ChangeToResultPage(
             board.Bomb - board.Flag,
             board.Bomb,
             _stopWatch.TimeElapsed,
             isWin
             );
     });
 }
コード例 #7
0
        public void MinesweeperBoard_WholeBoardUncovered_WithNoMines()
        {
            int width = 50, height = 50;
            var board = new MinesweeperBoard(width, height, 0);

            for (var i = 0; i < width; i++)
            {
                for (var j = 0; j < height; j++)
                {
                    if (board[i, j].Status == CellStatus.Uncovered)
                    {
                        Assert.Fail("Board with no mines has invalid cell status");
                    }
                }
            }
        }
コード例 #8
0
        private MinesweeperBoard Chording(MinesweeperBoard board, int x, int y)
        {
            var totalFlags          = 0;
            var totalCorrectFlagged = 0;

            for (int row = -1; row < 2; row++)
            {
                for (int col = -1; col < 2; col++)
                {
                    try
                    {
                        if (board.Board[x + row, y + col].Flagged && board.Board[x + row, y + col].IsMine)
                        {
                            totalCorrectFlagged++;
                        }
                        if (board.Board[x + row, y + col].Flagged)
                        {
                            totalFlags++;
                        }
                    }
                    catch { }
                }
            }
            if (totalCorrectFlagged == totalFlags)
            {
                for (int row = -1; row < 2; row++)
                {
                    for (int col = -1; col < 2; col++)
                    {
                        try
                        {
                            if (!board.Board[x + row, y + col].IsMine)
                            {
                                board.Board[x + row, y + col].IsRevealed = true;
                                if (board.Board[x + row, y + col].TotalMines == 0)
                                {
                                    RevealEmpty(board, x + row, y + col);
                                }
                            }
                        }
                        catch { }
                    }
                }
            }
            return(board);
        }
コード例 #9
0
 private bool ScanAdjacent(MinesweeperBoard board, int x, int y)
 {
     for (int row = -1; row < 2; row++)
     {
         for (int col = -1; col < 2; col++)
         {
             try
             {
                 if (board.Board[x + row, y + col].IsRevealed == false)
                 {
                     return(false);
                 }
             }
             catch { }
         }
     }
     return(true);
 }
コード例 #10
0
        public void MinesweeperBoard_Clone_PerformsDeepCopy()
        {
            int width = 50, height = 50, numMines = 10;
            var board = new MinesweeperBoard(width, height, numMines);
            var clone = (MinesweeperBoard)board.Clone();

            Assert.AreNotSame(board, clone, "Clone cannot produce same object reference");
            for (var i = 0; i < height; i++)
            {
                for (var j = 0; j < width; j++)
                {
                    var original = board[i, j];
                    var copied   = clone[i, j];
                    //Debug.WriteLine(original.Equals(copied) + " " + original.X + " " + original.Y + " " + original.Type + " " + original.Status + " " + copied.X + " " + copied.Y + " " + copied.Type + " " + copied.Status);
                    Assert.IsTrue(board[i, j].Equals(clone[i, j]));
                    Assert.AreNotSame(board[i, j], clone[i, j], "Clone copied a cell object reference");
                }
            }
        }
コード例 #11
0
        public void MinesweeperBoard_CascadesAllButOne_WithOneMine()
        {
            int width = 50, height = 50;
            var board = new MinesweeperBoard(width, height, 0);

            board[0, 0].Type = CellType.Mined;
            board.Uncover(25, 25, 0);
            var cascaded = 0;

            for (var i = 0; i < width; i++)
            {
                for (var j = 0; j < height; j++)
                {
                    if (board[i, j].Status == CellStatus.Uncovered)
                    {
                        cascaded++;
                    }
                }
            }
            Assert.AreEqual(width * height - 1, cascaded, "Wrong number of cascaded cells");
        }
コード例 #12
0
        public JsonResult Minesweeper([FromBody] MinesweeperBindingModel model)
        {
            var board = MinesweeperBoard.Decrypt(model.encodedBoard).Split(';').ToList();

            var gameEndedSuccessfully   = MinesweeperBoard.CheckIfGameEndedSuccessfully(board, model.flagged);
            var gameEndedUnsuccessfully = MinesweeperBoard.CheckIfMineIsHit(board, model.currentId);

            MineViewModel output = MinesweeperBoard.TilesToReveal(model.currentId, board, new MineViewModel());

            output.gameEnded = gameEndedSuccessfully || gameEndedUnsuccessfully;

            if (gameEndedUnsuccessfully)
            {
                output.mines = new List <Mine>();
                foreach (var mine in board)
                {
                    output.mines.Add(new Mine(mine, 0));
                }
            }

            return(new JsonResult(output));
        }
コード例 #13
0
    public override void EnterScene(object state)
    {
        // BGM再生
        gc.PlaySound(GcSound.Bgm_game, loop: true);

        // 時間初期化
        _startTime = gc.TimeSinceStartup;

        // 男の子の追加
        gc.CreateActor <BoyActor>();

        // タイマーの追加
        _timerActor = new TimerActor(0, new int2(gc.CanvasWidth, 0));
        gc.AddActor(_timerActor);

        // 爆弾個数表示の追加
        gc.AddActor(new BombCountActor(BombCount));

        // ゲームの状態の初期化
        _minesweeperBoard = new MinesweeperBoard(gc, BoardSize, BombCount);

        // セルボタンの初期化
        _cellArray = new ButtonActor[BoardSize.x][];
        for (var x = 0; x < BoardSize.x; x++)
        {
            _cellArray[x] = new ButtonActor[BoardSize.y];

            for (var y = 0; y < BoardSize.y; y++)
            {
                var pos  = _boardPadding + _cellImageSize + new float2(_cellImageSize.x * x, _cellImageSize.y * y);
                var cell = new ButtonActor(GcImage.Cell_dummy, GcAnchor.UpperLeft, pos);

                _cellArray[x][y] = cell;
                gc.AddActor(cell);
            }
        }
    }
コード例 #14
0
 public async Task Minesweeper([Summary("width")] int width, [Summary("height")] int height, [Summary("bomb count")] int bombs)
 {
     if (width < 1 || height < 1 || bombs < 0)
     {
         await Context.Channel.SendMessageAsync("Invalid grid size or bomb count");
     }
     else if (width > 10 || height > 10)
     {
         await Context.Channel.SendMessageAsync("Max Grid Size: 10 x 10");
     }
     else if (bombs >= height * width)
     {
         await Context.Channel.SendMessageAsync("Too many bombs!");
     }
     else
     {
         MinesweeperBoard game    = new MinesweeperBoard(height, width, bombs);
         EmbedBuilder     builder = new EmbedBuilder();
         builder.Title       = ":bomb: Minesweeper";
         builder.Color       = EMBED_COLOR;
         builder.Description = game.ToString();
         await SendEmbed(builder.Build());
     }
 }
コード例 #15
0
        public override void Click(MouseButton clickedButton)
        {
            var position           = SplashKit.MousePosition();
            int size               = _mode.SquareSize,
                x                  = (int)Math.Floor((position.X - _properties.MarginLeft) / size),
                y                  = (int)Math.Floor((position.Y - _properties.MarginTop) / size);
            MinesweeperBoard board = _mode.Board as MinesweeperBoard;

            switch (clickedButton)
            {
            case MouseButton.LeftButton:
                // the game should stop when player click on a bomb square or is considered win
                int result = board.RevealSquare(x, y);
                if (result != -2 && !_stopWatch.IsStarted && !_stopWatch.IsStopped)
                {
                    _stopWatch.Start();
                }
                if (result == -1)
                {
                    ToResultPage(board, false);
                }

                // triggering whole board check for winning condition
                bool isWin = board.IsWin;
                if (isWin)
                {
                    ToResultPage(board, true);
                }

                break;

            case MouseButton.RightButton:
                board.ToggleFlag(x, y);
                break;
            }
        }
コード例 #16
0
        //FOR REFACTORING
        public IActionResult Minesweeper()
        {
            MinesweeperBoard board = new MinesweeperBoard();

            return(View(board));
        }
コード例 #17
0
    public static string[] Annotate(string[] input)
    {
        MinesweeperBoard board = new MinesweeperBoard(input);

        return(board.AnnotatedBoard);
    }
コード例 #18
0
 public PlayerData(GameSettings settings)
 {
     Time  = 0;
     Flag  = settings.Bomb;
     Board = new MinesweeperBoard(settings.BoardWidth, settings.BoardHeight, settings.Bomb);
 }
コード例 #19
0
        public async Task Minesweeper(CommandContext ctx, Player user, bool isGauntlet = false, MineDifficulty difficulty = MineDifficulty.Easy, int stage = 0)
        {
            var interactivity = ctx.Client.GetInteractivity();

            embed = new DiscordEmbedBuilder();
            MinesweeperBoard board = null;
            var puzzleFinished     = false;
            var failed             = false;
            var timedOut           = false;

            embed.AddField("Controls:", "Choose a square by entering a letter followed by a number.\nInputs can be sent in a comma separated list.\nExample: A2 or A2,C4\nFlag A2 or Flag A2,B4");
            if (!isGauntlet)
            {
                embed.Title = "Minesweeper";
                int rNum = new Random().Next(1, 3);
                difficulty = rNum switch
                {
                    1 => MineDifficulty.Easy,
                    2 => MineDifficulty.Medium,
                    _ => MineDifficulty.Hard
                };
                board = new MinesweeperBoard(difficulty);
                var rewardDisplay = difficulty switch
                {
                    MineDifficulty.Easy => "Common Crate x3",
                    MineDifficulty.Medium => "Uncommon Crate x2",
                    _ => "Rare Crate x2",
                };
                embed.AddField("Reward:", $"{rewardDisplay}");
            }
            else
            {
                embed.Title = $"Minesweeper (Gauntlet stage: {stage})";
                board       = new MinesweeperBoard(difficulty);
            }
            var display = MakeDisplay(board);

            embed.Description = $"```\n{display}\n```";
            embed.Color       = DiscordColor.Blurple;
            embed.WithFooter($"Board will time out after 2 minutes of no actions.\nDifficulty: {board.Difficulty}");
            BuiltEmbed = embed.Build();
            var message = await ctx.RespondAsync(embed : BuiltEmbed);

            DiscordMessage wrongInputMessage = null;
            int            totalMoves        = 0;

            while (puzzleFinished != true)
            {
                var response = await interactivity.WaitForMessageAsync(x => x.Channel == ctx.Channel && x.Author == ctx.Member, TimeSpan.FromSeconds(120));

                if (response.TimedOut)
                {
                    timedOut = true;
                    break;
                }
                else
                {
                    var rawInput = response.Result.Content.ToLower();
                    if ((rawInput.Length > 8 && rawInput.Contains(",") == false && !rawInput.Contains("unflag") && rawInput.Contains("flag") == true) || (rawInput.Length > 10 && rawInput.Contains(",") == false && rawInput.Contains("unflag") == true))
                    {
                        wrongInputMessage = await ctx.Channel.SendMessageAsync("A list of inputs must be in a comma separated list.");
                    }
                    else if (rawInput.Length > 2 && rawInput.Contains(",") == false && rawInput.Contains("flag") == false)
                    {
                        wrongInputMessage = await ctx.Channel.SendMessageAsync("A list of inputs must be in a comma separated list.");
                    }
                    else
                    {
                        //Response processing
                        string[] moves = null;
                        if (response.Result.Content.ToLower().Contains("flag"))//change to rawinput
                        {
                            var commandRemovedArray = rawInput.Split("flag");
                            var spaceRemovedArray   = commandRemovedArray[1].Split(" ");
                            var spaceRemoved        = "";
                            foreach (string s in spaceRemovedArray)
                            {
                                spaceRemoved += s;
                            }
                            moves = spaceRemoved.Split(",");
                        }
                        else
                        {
                            var spaceRemovedArray = rawInput.Split(" ");
                            var spaceRemoved      = "";
                            foreach (string s in spaceRemovedArray)
                            {
                                spaceRemoved += s;
                            }
                            moves = spaceRemoved.Split(",");
                        }
                        //Finished response processing
                        foreach (string move in moves)
                        {
                            board = move[0] switch
                            {
                                'a' => PerformMove(board, ctx, rawInput, move, 0),
                                'b' => PerformMove(board, ctx, rawInput, move, 1),
                                'c' => PerformMove(board, ctx, rawInput, move, 2),
                                'd' => PerformMove(board, ctx, rawInput, move, 3),
                                'e' => PerformMove(board, ctx, rawInput, move, 4),
                                'f' => PerformMove(board, ctx, rawInput, move, 5),
                                'g' => PerformMove(board, ctx, rawInput, move, 6),
                                'h' => PerformMove(board, ctx, rawInput, move, 7),
                                'i' => PerformMove(board, ctx, rawInput, move, 8),
                                'j' => PerformMove(board, ctx, rawInput, move, 9),
                                _ => board
                            };
                        }
                        display = MakeDisplay(board);
                    }
                    //Decides if puzzle is finished or failed
                    puzzleFinished = true;
                    for (int row = 0; row < board.Board.GetLength(0); row++)
                    {
                        for (int col = 0; col < board.Board.GetLength(1); col++)
                        {
                            if (board.Board[row, col].IsMine && board.Board[row, col].IsRevealed)
                            {
                                puzzleFinished = true;
                                failed         = true;
                                break;
                            }
                            else if (!board.Board[row, col].IsRevealed && !board.Board[row, col].IsMine)
                            {
                                puzzleFinished = false;
                            }
                        }
                        if (failed)
                        {
                            break;
                        }
                    }
                    embed.Description = $"```\n{display}\n```";
                    BuiltEmbed        = embed.Build();
                    message           = await message.ModifyAsync(embed : BuiltEmbed);

                    try
                    {
                        await response.Result.DeleteAsync();
                    }
                    catch
                    {
                    }
                    if (wrongInputMessage != null)
                    {
                        await wrongInputMessage.DeleteAsync();

                        wrongInputMessage = null;
                    }
                }
            }
            if (timedOut)
            {
                embed.Color = DiscordColor.Red;
                embed.Title = "Minesweeper (Timed Out)";
                BuiltEmbed  = embed.Build();
            }
            else if (failed)
            {
                if (isGauntlet == true)
                {
                    GauntletCommands.PuzzleStatus = false;
                }
                else if (totalMoves == 1 && user.GameCooldownIgnore == false)
                {
                    user.MinesweeperStart    = DateTime.Now;
                    user.MinesweeperCooldown = TimeSpan.FromMinutes(0);
                    user.MinesweeperEnd      = DateTime.Now;
                    embed.ClearFields();
                    embed.AddField("Cooldown Ignored", "You were given another chance because you hit a mine on your first move.");
                    Bot.PlayerDatabase.UpdatePlayer(user);
                }
                embed.Title = "Minesweeper (Game Failed)";
                embed.Color = DiscordColor.Red;
                display     = "";
                for (int row = 0; row < board.Board.GetLength(0); row++)
                {
                    display += row switch
                    {
                        0 => "A",
                        1 => "B",
                        2 => "C",
                        3 => "D",
                        4 => "E",
                        5 => "F",
                        6 => "G",
                        7 => "H",
                        8 => "I",
                        _ => "J",
                    };
                    for (int col = 0; col < board.Board.GetLength(1); col++)
                    {
                        if (board.Board[row, col].IsRevealed == false && !board.Board[row, col].IsMine)
                        {
                            display += $" ‏‏‎#";
                        }
                        else if (!board.Board[row, col].IsMine)
                        {
                            if (board.Board[row, col].TotalMines == 0)
                            {
                                display += " ‏‏‎ ‏‏‎";
                            }
                            else
                            {
                                display += $" ‏‏‎{board.Board[row, col].TotalMines}";
                            }
                        }
                        else
                        {
                            display += $" ‏‏‎@";
                        }
                    }
                    display += " ‏‏‎|\n";
                }
                embed.Description = $"```\n{display}\n```";
                BuiltEmbed        = embed.Build();
            }
            else
            {
                if (isGauntlet == true)
                {
                    await message.DeleteAsync();

                    message = null;
                    GauntletCommands.PuzzleStatus = true;
                }
                else
                {
                    embed.Title = "Minesweeper (Game Win)";
                    embed.Color = DiscordColor.Green;
                    BuiltEmbed  = embed.Build();
                    if (user.GameCooldownIgnore == true || user.IsBanned == true)
                    {
                        var embed2 = new DiscordEmbedBuilder();
                        embed2.Title = "Reward Not Recieved";
                        if (user.IsBanned == true)
                        {
                            embed2.Description = "You are not eligible to revieve rewards from this mini-game because you are banned from using the main feature of this bot.";
                        }
                        else
                        {
                            embed2.Description     = "You are not eligible to revieve rewards from this mini-game because you are in cooldown ignore mode.";
                            user.DotPuzzleStart    = DateTime.Now;
                            user.DotPuzzleCooldown = TimeSpan.FromMinutes(0);
                            user.DotPuzzleEnd      = DateTime.Now;
                            Bot.PlayerDatabase.UpdatePlayer(user);
                        }
                        embed2.Color = DiscordColor.Red;
                        await ctx.Channel.SendMessageAsync(embed : embed2);
                    }
                    else
                    {
                        var crate = Crate.GetMinesweeperReward(board.Difficulty);
                        switch (board.Difficulty)
                        {
                        case MineDifficulty.Easy:
                            GeneralFunctions.AddToInventory(user, crate, 3);
                            break;

                        case MineDifficulty.Medium:
                            GeneralFunctions.AddToInventory(user, crate, 2);
                            break;

                        case MineDifficulty.Hard:
                            GeneralFunctions.AddToInventory(user, crate, 2);
                            break;
                        }
                    }
                }
            }
            try { message = await message.ModifyAsync(embed : BuiltEmbed); }
            catch { }
            Bot.PlayerDatabase.UpdatePlayer(user);
        }