2016-01-13 77 views
-2

我有这个数组,我想连续检查4(游戏)。我可以用数以百计的方式来做到这一点,但我怎样才能做到这一点?这甚至有可能吗? 这是我的代码。提前致谢!检查数组4连续

int array[][] = {{0, 1, 1, 1, 1, 0, 0}, 
       {0, 0, 0, 1, 0, 1, 1}, 
       {0, 0, 0, 1, 0, 1, 1}, 
       {0, 1, 1, 0, 1, 0, 1}, 
       {1, 0, 0, 1, 0, 1, 1}, 
       {1, 0, 0, 1, 0, 1, 0}}; 

for (int rows = 0; rows < 6; rows++) { 
    for(int columns = 0; columns < 7; columns++) { 
     System.out.print(array[rows][columns] + " "); 
    } 
    System.out.println(); 
} 

if (array[0][0] == 0) { 
    if(array[0][1] == 0) { 
     if (array[0][2] == 0) { 
      if (array[0][3] == 0) { 
       System.out.println("Connect Four!"); 
      } 
     } 
    } 
} 
+0

你想检查一行,如果所有4列都有0值是正确的? – Dreamweaver

+0

Eehm很难解释,但我只是想检查四个零或一个谁是谁在旁边或上面彼此。像游戏连接四 –

+0

你不需要3个州? IMO国家的可能性是:0 =空白,1 =球员1,2 =球员2。如果它是空白的,则使用它,否则使用循环检查player1或player2的相邻数组项。 – Johannes

回答

0

我会介绍一个计数器,并在每次当前“行”中增加一个计数器,并在当前编号为1时将其复位。如果计数器达到4,则已连接4个计数器。

看看这个:

int array[][] = {{0, 1, 1, 1, 1, 0, 0}, 
       {0, 0, 0, 1, 0, 1, 1}, 
       {0, 0, 0, 1, 0, 1, 1}, 
       {0, 1, 1, 0, 1, 0, 1}, 
       {1, 0, 0, 1, 0, 1, 1}, 
       {1, 0, 0, 1, 0, 1, 0}}; 

//Search rows 
for (int i = 0; i < array.length; i++) { 
    int rowCount = 0;     
    for (int j = 0; j < array[i].length; j++) { 
     if (array[i][j] == 0) { 
      rowCount++; 
     } else { 
      rowCount = 0; 
     } 
     if (rowCount == 4) { 
      System.out.println("yay"); 
     } 
    } 
} 

这不是完整的代码,只为行。但它应该给你一个关于如何解决你的问题的行甚至对角线的想法。

+0

@ [Fabian van Rooyen](http://stackoverflow.com/users/4973740/fabian-van-rooyen)我很好奇你为什么认为这个答案更好? – martijnn2008

3

是这样的吗?

int[] dx = {0, 1, 0, -1}; // I think you only need the first two, because 
int[] dy = {1, 0, -1, 0}; // otherwise you check things twice 

for (int y = 0; y < array.length; y++) { 
    for (int x = 0; x < array[y].length; x++) { 
     int start_value = array[y][x]; 
     for (int i = 0; i < dx.length; i++) { 
      for (int j = 1; j < 4; j++) { 
       // check if there are enough cells in y direction 
       if (y + dy[i] * j >= array.length) break; 
       // check if there are enough cells in x direction 
       if (x + dx[i] * j >= array[y].length) break; 
       // check if the value is the same 
       if (array[y + dy[i] * j][x + dx[i] * j] != start_value) { 
        break; 
       } 
       // the next three elements in a direction are the same 
       if (j == 3) { 
        System.out.println("4 in a row"); 
        return; 
       } 
      } 
     } 
    } 
} 
System.out.println("not 4 in a row"); 

如果你想在多个方向进行检查,例如对角线添加多个值dxdy

+0

谢谢!有没有办法让连续4个地方变成大胆或红色的地方? –

+0

我想你需要知道连续四个元素的索引。我不知道你有什么样的图形用户界面,但自从我在15分钟前发布这个答案。我认为你应该首先尝试更多的自己或者聘请一些人为你做。 – martijnn2008

+0

我认为,第一个地方也许它甚至不可能。如果那是真的,那么我甚至不必去尝试它。但是,谢谢 –