C# 在一行中查找5个相同颜色的元素

C# 在一行中查找5个相同颜色的元素,c#,arrays,multidimensional-array,C#,Arrays,Multidimensional Array,我创建了一个二维标签数组[19,19]。单击后,用户根据迭代将标签颜色更改为黑色或白色。当有五个相同颜色的标签水平、垂直或对角排列时,我希望弹出一个消息框。只有对角线检查不起作用,我不知道为什么。任何帮助都将不胜感激 class gamePlay { const int WinLength = 5; const int BoardWidth = 19; const int BoardHeight = 19; const int kwinningCount = 5

我创建了一个二维标签数组[19,19]。单击后,用户根据迭代将标签颜色更改为黑色或白色。当有五个相同颜色的标签水平、垂直或对角排列时,我希望弹出一个消息框。只有对角线检查不起作用,我不知道为什么。任何帮助都将不胜感激

class gamePlay
{
    const int WinLength = 5;
    const int BoardWidth = 19;
    const int BoardHeight = 19;

    const int kwinningCount = 5;

    public Color? CheckWinner(Label[,] board)
    {
        int columnCount = board.GetLength(1), rowCount = board.GetLength(0);

        for (int row = 0; row < rowCount; row++)
        {
            Color? lineResult = CheckWinnerForLine(board, 0, row, columnCount, 1, 0);

            if (lineResult != null)
            {
                return lineResult;
            }

            if (rowCount - row >= kwinningCount)
            {
                lineResult = CheckWinnerForLine(board, 0, row, rowCount - row, 1, 1);

                if (lineResult != null)
                {
                    return lineResult;
                }
            }
        }

        for (int column = 0; column < columnCount; column++)
        {
            Color? lineResult = CheckWinnerForLine(board, column, 0, rowCount, 0, 1);

            if (lineResult != null)
            {
                return lineResult;
            }

            if (column > 0 && columnCount - column >= kwinningCount)
            {
                lineResult =
                    CheckWinnerForLine(board, column, 0, columnCount - column, 1, 1);

                if (lineResult != null)
                {
                    return lineResult;
                }
            }
        }

        return null;
    }

    Color? CheckWinnerForLine(Label[,] board,
        int column, int row, int count, int columnIncrement, int rowIncrement)
    {
        // Initialize from the first cell
        int colorCount = 1;
        Color currentColor = board[row, column].BackColor;

        while (--count > 0)
        {
            column += columnIncrement;
            row += rowIncrement;

            Color cellColor = board[row, column].BackColor;

            if (currentColor != cellColor)
            {
                // switched colors, so reset for this cell to be the first of the string
                colorCount = 1;
                currentColor = cellColor;
            }
            else if (++colorCount == kwinningCount && cellColor != Color.Transparent)
            {
                return cellColor;
            }
        }

        return null;
    }
public partial class Form1 : Form
{
    int iteration = 0;
    public Label[,] board = new Label[19,19];
    int count;
    int columnIncrement;
    int rowIncrement;
    const int WinLength = 5;
    const int BoardWidth = 19;
    const int BoardHeight = 19;
    gamePlay WinCheck = new gamePlay();

    public Form1()
    {
        InitializeComponent();

        int x = this.Location.X + 10;
        int y = this.Location.Y + 15;

        // create 361 labels, set their properties
        for (int i = 0; i < 19; i++)
        {
            for (int j = 0; j < 19; j++)
            {
                board[i,j] = new Label();
                board[i,j].Parent = this;
                board[i,j].Name = "label" + i;
                //board[i,j].BackColor = System.Drawing.ColorTranslator.FromHtml("#DBB262");
                board[i,j].BackColor = Color.Transparent;
                //board[i, j].StyleChanged = Opacity
                //set size of labels
                board[i,j].Size = new Size(30, 30);
                //initialize click event handler
                this.board[i,j].Click += new System.EventHandler(this.labelClick);
                this.Controls.Add(board[i,j]);
                board[i,j].BringToFront();
            }

        }



        // set the position of the label
        for (int i = 0; i < 19; i++)
        {
            for (int j = 0; j < 19; j++)
            {
                board[i,j].Location = new Point(x, y);
                //set distance between labels
                if (x >= 755)
                {
                    x = this.Location.X + 10;
                    y += 42;
                }

                else
                {
                    x += 43;
                }
            }

        }
    }

        private void labelClick (object sender, EventArgs e)
        {

            Label clickedLabel = (Label)sender;

            if (clickedLabel.BackColor == Color.Transparent)
            {
                if (iteration % 2 == 0)
                {
                    clickedLabel.BackColor = Color.Black;
                }
                else
                {
                    clickedLabel.BackColor = Color.White;
                }
                iteration++;
            }
            else
            {

            }

            for (int row = 0; row < BoardHeight; row++)
            {
                for (int column = 0; column < BoardWidth; column++)
                {
                    if (board[row, column] == clickedLabel)
                    {
                        Color? winner = WinCheck.CheckWinner(board);
                        if (winner == Color.Black)
                        {
                            MessageBox.Show("Black is the winner!");
                        }
                        else if (winner == Color.White)
                        {
                            MessageBox.Show("White is the winner!");
                        }
                    }
                }
            }
        }

        private int[] FindClickedLabelCoordinates(Label[,] board, Label label)
        {
            for (int row = 0; row < BoardHeight; row++)
            {
                for (int column = 0; column < BoardWidth; column++)
                {
                    if (board[row, column] == label)
                        return new int[] { row, column };
                }
            }
            return null;
        }
类游戏
{
const int WinLength=5;
const int BoardWidth=19;
const int BoardHeight=19;
常数int kwinningCount=5;
公共颜色?制表符(标签[,]板)
{
int columnCount=board.GetLength(1),rowCount=board.GetLength(0);
对于(int row=0;row=kwinningCount)
{
lineResult=CheckWinnerForLine(板,0,行,行计数-行,1,1);
if(lineResult!=null)
{
返回行结果;
}
}
}
for(int column=0;column0&&columnCount-列>=kwinningCount)
{
lineResult=
CheckWinnerForLine(board,column,0,columnCount-column,1,1);
if(lineResult!=null)
{
返回行结果;
}
}
}
返回null;
}
颜色?选中WinnerForline(标签[,]板,
int列、int行、int计数、int列增量、int行增量)
{
//从第一个单元格初始化
int colorCount=1;
Color currentColor=线路板[行,列]。背景色;
而(--计数>0)
{
列+=列增量;
行+=行增量;
Color cellColor=线路板[行,列].背景色;
如果(currentColor!=cellColor)
{
//切换了颜色,因此将此单元格重置为字符串的第一个
颜色计数=1;
currentColor=cellColor;
}
else如果(++colorCount==kwinningCount&&cellColor!=Color.Transparent)
{
返回细胞颜色;
}
}
返回null;
}
公共部分类Form1:Form
{
int迭代=0;
公共标签[,]板=新标签[19,19];
整数计数;
int列增量;
内行增量;
const int WinLength=5;
const int BoardWidth=19;
const int BoardHeight=19;
gamePlay WinCheck=新游戏性();
公共表格1()
{
初始化组件();
int x=此.Location.x+10;
int y=这个位置y+15;
//创建361个标签,设置其属性
对于(int i=0;i<19;i++)
{
对于(int j=0;j<19;j++)
{
板[i,j]=新标签();
板[i,j]。父级=此;
板[i,j].Name=“label”+i;
//board[i,j].BackColor=System.Drawing.ColorTranslator.FromHtml(“#DBB262”);
电路板[i,j]。背景色=颜色。透明;
//板[i,j]。样式更改=不透明度
//设置标签的大小
板[i,j]。尺寸=新尺寸(30,30);
//初始化单击事件处理程序
this.board[i,j].Click+=newsystem.EventHandler(this.labelClick);
这个.Controls.Add(board[i,j]);
板[i,j]。布林托夫隆();
}
}
//设置标签的位置
对于(int i=0;i<19;i++)
{
对于(int j=0;j<19;j++)
{
板[i,j]。位置=新点(x,y);
//设置标签之间的距离
如果(x>=755)
{
x=这个位置x+10;
y+=42;
}
其他的
{
x+=43;
}
}
}
}
私有无效标签单击(对象发送方,事件参数e)
{
标签点击标签=(标签)发件人;
如果(clickedLabel.BackColor==Color.Transparent)
{
如果(迭代%2==0)
{
单击label.BackColor=Color.Black;
}
其他的
{
单击label.BackColor=Color.White;
}
迭代++;
}
其他的
{
}
对于(int row=0;rowprivate static Boolean IsWon(Label[,] board) {
  if (null == board)
    return false;

  // Let code not be that rigid: "5" can be easily updated 
  const int atLeast = 5; 

  // Do not use magic numbers - i.e. "19"
  for (int i = 0; i < board.GetLength(0); ++i) {
    Color current = board[i, 0].BackColor;
    int count = 1;

    for (int j = 1; j < board.GetLength(1); ++j) { // note j = 1
      if (current == board[i, j].BackColor) {
        count += 1;

        if (count >= atLeast)   
          return true;
      }      
      else {
        current = board[i, j].BackColor;
        count = 1;
      } 
    }
  } 

  return false;
}

public void checkWinner(Label[,] board) {
  if (IsWon(board))
    MessageBox.Show("You Win!");
}
class GamePlay
{
    private readonly int _winLength = 5;

    public GamePlay(int winLength)
    {
        _winLength = winLength;
    }

    public Color? CheckWinner(Label[,] board)
    {
        return CheckWinnerIterator(board).FirstOrDefault(color => color != null);
    }

    private IEnumerable<Color?> CheckWinnerIterator(Label[,] board)
    {
        int columnCount = board.GetLength(1), rowCount = board.GetLength(0);

        for (int row = 0; row < rowCount; row++)
        {
            // Horizontal
            yield return CheckWinnerForLine(board, 0, row, columnCount, 1, 0);
            // Diagonals starting in first column, upper-left to lower-right
            yield return CheckWinnerForLine(board, 0, row, rowCount - row, 1, 1);
            // Diagonals starting in first column, lower-left to upper-right
            yield return CheckWinnerForLine(board, 0, row, row + 1, 1, -1);
        }

        for (int column = 0; column < columnCount; column++)
        {
            // Vertical
            yield return CheckWinnerForLine(board, column, 0, rowCount, 0, 1);
            // Diagonals starting in first row, upper-left to lower-right
            yield return CheckWinnerForLine(board, column, 0, columnCount - column, 1, 1);
            // Diagonals starting in last row, lower-left to upper-right
            yield return CheckWinnerForLine(board, column, rowCount - 1, columnCount - column, 1, -1);
        }
    }

    Color? CheckWinnerForLine(Label[,] board,
        int column, int row, int count, int columnIncrement, int rowIncrement)
    {
        if (count < _winLength)
        {
            return null;
        }

        // Initialize from the first cell
        int colorCount = 1;
        Color currentColor = board[row, column].BackColor;

        while (--count > 0)
        {
            column += columnIncrement;
            row += rowIncrement;

            Color cellColor = board[row, column].BackColor;

            if (currentColor != cellColor)
            {
                // switched colors, so reset for this cell to be the first of the string
                colorCount = 1;
                currentColor = cellColor;
            }
            else if (++colorCount == _winLength && cellColor != Color.Transparent)
            {
                return cellColor;
            }
        }

        return null;
    }
}
public partial class Form1 : Form
{
    const int WinLength = 5;
    const int BoardWidth = 19;
    const int BoardHeight = 19;

    private bool isBlackTurn = true;
    private Label[,] board = new Label[BoardHeight, BoardWidth];
    private GamePlay WinCheck = new GamePlay(WinLength);

    public Form1()
    {
        InitializeComponent();

        int x = this.Location.X + 10;
        int y = this.Location.Y + 15;

        // create 361 labels, set their properties
        for (int i = 0; i < BoardHeight; i++)
        {
            for (int j = 0; j < BoardWidth; j++)
            {
                Label label = new Label();

                label.Parent = this;
                label.Name = "label" + i;
                label.BackColor = Color.Transparent;
                label.BorderStyle = BorderStyle.FixedSingle;
                label.Size = new Size(30, 30);
                label.Click += new System.EventHandler(this.labelClick);
                this.Controls.Add(board[i, j]);
                label.BringToFront();

                board[i, j] = label;
            }

        }

        // set the position of the label
        for (int i = 0; i < BoardHeight; i++)
        {
            for (int j = 0; j < BoardWidth; j++)
            {
                board[i, j].Location = new Point(x, y);
                //set distance between labels
                if (x >= 755)
                {
                    x = this.Location.X + 10;
                    y += 42;
                }

                else
                {
                    x += 43;
                }
            }

        }
    }

    private void labelClick(object sender, EventArgs e)
    {
        Label clickedLabel = (Label)sender;

        if (clickedLabel.BackColor != Color.Transparent)
        {
            return;
        }

        clickedLabel.BackColor = isBlackTurn ? Color.Black : Color.White;
        isBlackTurn = !isBlackTurn;

        Color? winner = WinCheck.CheckWinner(board);
        if (winner == Color.Black)
        {
            MessageBox.Show("Black is the winner!");
        }
        else if (winner == Color.White)
        {
            MessageBox.Show("White is the winner!");
        }
        else
        {
            return;
        }

        foreach (Label label in board)
        {
            label.BackColor = Color.Transparent;
        }
    }
}
<Window x:Class="TestSO33773260FiveInARow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:l="clr-namespace:TestSO33773260FiveInARow"
        Title="MainWindow" Height="525" Width="525">

  <ItemsControl ItemsSource="{Binding Board}" Background="AliceBlue">
    <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
        <UniformGrid x:Name="uniformGrid1" Rows="{Binding Rows}" Columns="{Binding Columns}" IsItemsHost="True"/>
      </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
      <DataTemplate DataType="l:BoardCell">
        <Rectangle Fill="{Binding Color}" MouseUp="Rectangle_MouseUp"/>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</Window>
public partial class MainWindow : Window
{
    private const int _kwinningCount = 5;
    public int Rows { get; set; }
    public int Columns { get; set; }
    public List<BoardCell> Board { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        Rows = 19;
        Columns = 19;
        Board = new List<BoardCell>(Enumerable.Range(0, Rows * Columns)
            .Select(i => new BoardCell { Color = Brushes.Transparent }));
        DataContext = this;
    }

    private void Rectangle_MouseUp(object sender, MouseButtonEventArgs e)
    {
        BoardCell boardCell = (BoardCell)((FrameworkElement)sender).DataContext;

        boardCell.IncrementColor();

        Color? winningColor = CheckWinner();

        if (winningColor != null)
        {
            MessageBox.Show(winningColor.Value.GetFriendlyName() + " won!");
        }
    }

    private Color _GetColorForBoardCell(int column, int row)
    {
        return Board[column + row * Rows].Color.Color;
    }

    public Color? CheckWinner()
    {
        return CheckWinnerIterator().FirstOrDefault(color => color != null);
    }

    private IEnumerable<Color?> CheckWinnerIterator()
    {
        int columnCount = Columns, rowCount = Rows;

        for (int row = 0; row < rowCount; row++)
        {
            // Horizontal
            yield return CheckWinnerForLine(0, row, columnCount, 1, 0);
            // Diagonals starting in first column, upper-left to lower-right
            yield return CheckWinnerForLine(0, row, rowCount - row, 1, 1);
            // Diagonals starting in first column, lower-left to upper-right
            yield return CheckWinnerForLine(0, row, row + 1, 1, -1);
        }

        for (int column = 0; column < columnCount; column++)
        {
            // Vertical
            yield return CheckWinnerForLine(column, 0, rowCount, 0, 1);
            // Diagonals starting in first row, upper-left to lower-right
            yield return CheckWinnerForLine(column, 0, columnCount - column, 1, 1);
            // Diagonals starting in last row, lower-left to upper-right
            yield return CheckWinnerForLine(column, rowCount - 1, columnCount - column, 1, -1);
        }
    }

    Color? CheckWinnerForLine(int column, int row, int count, int columnIncrement, int rowIncrement)
    {
        // Initialize from the first cell
        int colorCount = 1;
        Color currentColor = _GetColorForBoardCell(column, row);

        while (--count > 0)
        {
            column += columnIncrement;
            row += rowIncrement;

            Color cellColor = _GetColorForBoardCell(column, row);

            if (currentColor != cellColor)
            {
                // switched colors, so reset for this cell to be the first of the string
                colorCount = 1;
                currentColor = cellColor;
            }
            else if (++colorCount == _kwinningCount && cellColor != Colors.Transparent)
            {
                return cellColor;
            }
        }

        return null;
    }
}

public class BoardCell : INotifyPropertyChanged
{
    private static readonly SolidColorBrush[] _colors =
        { Brushes.Transparent, Brushes.White, Brushes.Black };

    private int _colorIndex;

    public SolidColorBrush Color
    {
        get { return _colors[_colorIndex]; }
        set
        {
            if (value != _colors[_colorIndex])
            {
                _SetColorIndex(Array.IndexOf(_colors, value));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void _OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public void IncrementColor()
    {
        _SetColorIndex(_colorIndex < _colors.Length - 1 ? _colorIndex + 1 : 0);
    }

    private void _SetColorIndex(int colorIndex)
    {
        _colorIndex = colorIndex;
        _OnPropertyChanged("Color");
    }
}

static class Extensions
{
    private static readonly Lazy<Dictionary<Color, string>> _colorToName =
        new Lazy<Dictionary<Color, string>>(() => GetColorToNameDictionary());

    private static Dictionary<Color, string> GetColorToNameDictionary()
    {
        Dictionary<Color, string> colorToName = new Dictionary<Color, string>();

        foreach (PropertyInfo pi in
            typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public))
        {
            if (pi.PropertyType == typeof(Color))
            {
                colorToName[(Color)pi.GetValue(null)] = pi.Name;
            }
        }

        return colorToName;
    }

    public static string GetFriendlyName(this Color color)
    {
        string name;

        if (_colorToName.Value.TryGetValue(color, out name))
        {
            return name;
        }

        return color.ToString();
    }
}
private void Check(Label[,] board)
{
    int Checker = 0;

    for (int i = 0; i < 19; i++)
    {
        for (int j = 0; j < 19; j++)
        {
            if (board[i, j].BackColor == Color.Black)
                Checker++;
            else
                Checker = 0;

            if (Checker == 5)
            {
                MessageBox.Show("You WON....!");
                return;
            }
        }
    }
}
int countItemNeed = 5;
string[,] arr = new string[7, 6]
{
    {"0", "1", "1", "1", "0", "1"},
    {"1", "0", "1", "1", "1", "0"},
    {"1", "0", "1", "1", "1", "0"},
    {"1", "0", "1", "1", "1", "0"},
    {"1", "0", "1", "1", "1", "0"},
    {"1", "0", "1", "1", "1", "0"},
    {"1", "0", "1", "1", "1", "1"},
};

//convert the 2d array to list of object - List<new{string,index}>
var oneList = arr.Cast<string>()
    .Select((s,i)=> new {s,i}); 

// convert the List to into sub list. one for each row in 2D array   
var multipleList = new List<List<Tuple<string, int>>>();
//Size of the row - mean column in a row.
int size = arr.GetLength(1);
while (oneList.Any())
{
    multipleList.Add(oneList
                     .Take(size)
                     .Select(c=>Tuple.Create(c.s, c.i%size)).ToList());
    oneList = oneList.Skip(size).ToList();
}

// check each row. then check each item if we have all 5 items as same.
var foundContinueItems = multipleList.Any(list =>
{
    return list.Any(c =>
    {
        if (c.Item2 > size - countItemNeed)
        {
            return false;
        }
        return list.Skip(c.Item2)
                    .Take(countItemNeed)
                    .All(d => d.Item1 == "1");
    });
});