【解決方法】10 x 10 のグリッドでランダムに発射する方法は?


コンピュータのグリッドをクリックした後、ランダムな x 座標と y 座標を選択し、正方形を青または赤でペイントすることにより、その一部が自分のグリッドでコンピュータを起動するアプリケーションを構築しようとしています。 コンピュータグリッドをクリックすると、コンピュータがグリッドの最初の行全体を強調表示し、その後のクリックでは何もしません。 ランダムな行と列を選択し、クリックした後にその四角だけをペイントする必要があります。

private void shotToGridMe()
    {

        Random random;
        random = new Random();

        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                var x = random.Next(0, 10);
                var y = random.Next(0, 10);

                if (MyArrayPlace[x, y] == 1)
                {

                    ((Button)gridMe.Children[i]).Background = Brushes.Red;
                }
                else
                {
                    ((Button)gridMe.Children[i]).Background = Brushes.Blue;
                }
            }

        }

    }

これは、敵のグリッドをクリックした関数で、shotToGridMe() 関数が含まれています。

private void ButtonEnemy_Click(object sender, RoutedEventArgs e)
       {
           for (int i = 0; i < row; i++)
           {
               for (int j = 0; j < col; j++)
               {
                   if (EnemyArrayPlace[i, j] == 1)
                   {
                       ((Button)sender).Background = Brushes.Red;
                   }
                   else
                   {
                       ((Button)sender).Background = Brushes.Blue;
                   }
               }
           }
           shotToGridMe();
       }

私が試したこと:

X と Y を別の場所に配置し、ループを別の方法で配置しようとしましたが、それでも最初の行全体にしかヒットしません。 ありがとう

解決策 1

まず、必要になるたびに Random インスタンスを作成しないでください。クラス レベルで 1 つのインスタンスを作成し、ランダムな値が必要になるたびにそれを再利用します。 Ransom クラスは作成時にシステム クロックから初期化されるため、最近のプロセッサでは同じシーケンスを簡単に繰り返すことができます。

次に、デバッガーを使用して何が起こっているかを正確に確認します。関数の最初の行にブレークポイントを置き、デバッガーでコードを実行します。 次に、コードとデータを見て、何が起こるべきかを手動で解決します。 次に、各行を 1 ステップ実行して、予想どおりの動作を確認します。 そうでない場合は、問題が発生したときであり、後戻りして (またはもう一度実行して詳しく調べて) 原因を突き止めることができます。

申し訳ありませんが、私たちはあなたにそれを行うことはできません – 新しい (そして非常に便利な) スキルを学ぶ時が来ました: デバッグ!

解決策 2

以下は、2048 ゲームの WPF 実装から変更されています。 私は UniformGrid そしてそれを満たした Buttons. ボタンは、空白の色のタイルとして表示されるようにスタイル設定されました。 変換にはコンバーターを使用しました。 Button.Tag プロパティ値を Fill 色を変更するだけでタイルの色を変更できるように Tag 価値。

C#
public partial class MainWindow : Window
    {
        private readonly List<Button> tiles = new();
        private Random random = new();
        private int lastSelectedIndex;
        public MainWindow()
        {
            InitializeComponent();
          //  var viewModel = new GameViewModel();
          //  viewModel.TilesUpdatedEvent += TilesUpdatedEventhandler;
            AddEmptyTilesToCollection();
            lastSelectedIndex = 0;
          //  DataContext = viewModel;
          //  viewModel.StartGame();
        }

        private void AddEmptyTilesToCollection()
        {
            var style = (Style)FindResource("TileButton");

            for (int id = 0; id < 16; id++)
            {
                var tile = new Button
                {
                    Style = style,
                    Tag = 0                 
                  
                };
                tile.Click += OnTileClick;
                tiles.Add(tile);
                Board.Children.Add(tile);
            }

        }
        private void OnTileClick(object sender, RoutedEventArgs e)
        {
            int index = random.Next(tiles.Count);
            var selectedTile = tiles[index];
            tiles[lastSelectedIndex].Tag = 0;
            selectedTile.Tag = 1;
            lastSelectedIndex = index;
        }
    }

MainWindow.xaml は単に

C#
<Window x:Class="ColouredTiles.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ColouredTiles"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <UniformGrid Margin="2" Grid.Row="0" Rows="4" Columns="4"  Name="Board" Background="White"  Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}" >

        </UniformGrid>
    </Grid>
</Window>

ボタンは app.xaml でスタイル設定されます

C#
<Application x:Class="ColouredTiles.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:ColouredTiles"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <local:IntToBrushConverter x:Key="intToBrushConverter"/>
        <Style x:Key="TileButton" TargetType="Button">
            <Setter Property="OverridesDefaultStyle" Value="True"/>
            <Setter Property="Margin" Value="5"/>
            <Setter Property="Background" Value="LightGray"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Grid >
                            <Rectangle Fill="{TemplateBinding Tag,Converter={StaticResource intToBrushConverter}}"
                                         Stroke="{TemplateBinding BorderBrush}"
                                         StrokeThickness="6" 
                                Height="100"
                                       Width="100"     
                                         />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Application.Resources>
</Application>

intBrush コンバーターは次のように定義されます

public class IntToBrushConverter : IValueConverter
   {//always check for null as this may be called at startup with a null value
       public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
       {
           if (value == null)
           {
               return new SolidColorBrush();//colourless
           }

           int index = (int)value;
           return index > tileColours.Length - 1 ? new SolidColorBrush() : new SolidColorBrush(tileColours[index]);
       }

       public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
       {
           throw new NotImplementedException();
       }
       private readonly Color[] tileColours =
  {
           Colors.LightGray,     // 0
           Colors.Yellow,        // 1
           Colors.Red,           // 2
           Colors.Green,         // 3
           Colors.Orange,        // 4
           Colors.LightBlue,     // 5
           Colors.Magenta,       // 6
           Colors.LightPink,     // 7
           Colors.Goldenrod,     // 8
           Colors.Aquamarine,    // 9
           Colors.Blue,          // 10
            Colors.LightGreen,   // 11
           Colors.DarkRed,       // 12
           Colors.DarkBlue,      // 13
           Colors.DarkOrange,    // 14
           Colors.Black          // 15
       };


   }

2048 タイルは多色であるため、色の選択肢が豊富ですが、ニーズに合わせて調整できると確信しています。 グリッドをクリックするとランダムな黄色のタイルが配置されます。 これが役に立つことを願っています

コメント

タイトルとURLをコピーしました