简体   繁体   English

如何查看2D数组内的行中是否使用了多个相同的值-C#

[英]How to see if more than one of the same values is used in a row inside a 2D array - c#

I am new to coding and are trying to make a Connect 4 game in c#. 我是编码新手,正在尝试用C#制作Connect 4游戏。 I have a 2D array that is 6 by 6 and initialized as all 0's to begin with. 我有一个6×6的2D数组,并将其初始化为全0。 When player 1 inputs their choice, the 0 in the lowest position for that column in the array is replaced with a 1. Likewise with Player 2 - with a 2 replacing the 0's (only) instead. 当玩家1输入他们的选择时,数组中该列最低位置的0被替换为1。与玩家2相同-用2代替了0(仅)。

What I can't seem to make work is for it to check each column for 4 of the same values in a row, each row for 4 of the same values in a row, and then diagonally for 4 of the same values in a row. 我似乎无法进行的工作是检查每一列中是否有4个相同的值,检查每一行中是否有4个相同的值,然后对角地检查一行中的4个相同的值。 Below is the code I was trying to make it search along each column for 4 of the same values in a row. 下面是我试图使它沿着每一列在一行中搜索4个相同值的代码。 Could you please help. 能否请你帮忙。 Thank you 谢谢

x = 0;
while (x <= 5)
{
    for (row = 5; row >= 0; row--)
    {
        if (Grid[row, x] == 1)
        {
            Player1Score = Player1Score + 1;
        }
        else
        {
            Player1Score = 0;
        }

        if (Grid[row, x] == 2)
        {
            Player2Score = Player2Score + 1;
        }
        else
        {
            Player2Score = 0;
        }
    }

    x = x + 1;

    if (Player1Score == 4)
    {
        Console.Clear();
        Console.WriteLine("Player1 wins");
    }
    else if (Player2Score == 4)
    {
        Console.Clear();
        Console.WriteLine("Player2 wins");
    }
}

How about: Have 2 vars, player1Score, player2Score. 怎么样:拥有2个变量,player1Score,player2Score。

For rows: go through each element in a row, 对于行:遍历行中的每个元素,

  • if it is 0 如果是0

    • set player1Score and player2Score to 0 将player1Score和player2Score设置为0
  • if it is 1 如果是1

    • increase player1Score by 1 -- set player2Score to 0 将player1Score增加1-将player2Score设置为0
  • if it is 2 如果是2
    • increase player2Score by 1 将player2Score增加1
    • set player1Score to 0 将player1Score设置为0

when you're done with with the row, check if any of the player scores is equal to 4, if it is, game won. 当您完成该行的操作后,请检查是否有任何玩家得分等于4,如果是,则赢得了游戏。 Otherways reset scores and go to the another row. 否则,重置分数并转到另一行。

You do the same thing with cols, and diagonals (in diagonals col id is equal to row id). 您对cols和对角线(在对角线中,col id等于行id)执行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM