2011-01-10 107 views
0

我有一个随机生成的10x5阵列,我想检查3个数字是否水平和垂直匹配。我无法弄清楚检查数字是否匹配的好方法。我现在这样做的话,如果我的陈述会超过70,我知道还有更好的办法。我不认为我可以使用for循环来检查,因为我需要确切地知道哪3个数字(及其位置)是相同的。赢得第3场比赛的条件

这是我到目前为止的代码,对不起,如果它有点长。我只包括一行检查以节省空间。

 

#include &ltiostream> 
#include &lttime.h> 
#include &ltcstdlib> 
#include &ltcstdio> 

using namespace std; 
int col = 5; 
int row = 0; 

int board[9][4]; 
int i; 

int main(int argc, char * argv[]) 
{ 
srand(time(NULL)); 

// generate the random board 

cout << "==========\n"; 
while (row < 1) 
{ 
    for(i = 0; i < 5; i++) 
    { 
    board[row][i] = rand()%5 + 1; 
    cout << board[row][i] << " "; 
    } 
    cout << endl; 
    cout << "==========\n"; 
    row++; 
} 

//----check for matches----- 

// row 1 
if (board[0][0] == (board[0][1] && board[0][2])) 
{ 
    cout << "Balls 1,2,3 match\n"; 
} 
if (board[0][2] == (board[0][3] && board[0][4])) 
{ 
    cout << "Balls 3,4,5 match\n"; 
} 
if (board[0][1] == (board[0][2] && board[0][3])) 
{ 
    cout << "Balls 2,3,4 match\n"; 
} 
if (board[0][0] == (board[0][1] && board[0][2] && board[0][3])) 
{ 
    cout << "Balls 1,2,3,4 match\n"; 
} 
if (board[0][1] == (board[0][2] && board[0][3] && board[0][4])) 
{ 
    cout << "Balls 2,3,4,5 match\n"; 
} 
if (board[0][0] == (board[0][1] && board[0][2] && board[0][3] && board[0][4])) 
{ 
    cout << "Balls 1,2,3,4,5 match\n"; 
} 
else 
{ 
    cout << "No balls match\n"; 
} 

return 0; 
} 
 
+2

[Win-condition for a connect-4 like game]可能的重复(http://stackoverflow.com/questions/4636575/win-conditions-for-a-connect-4-like-game) – templatetypedef 2011-01-10 22:41:12

+0

这也是我的帖子,但它是不一样的 – FrozenWasteland 2011-01-10 22:46:01

回答

0

我在这个问题和你以前的问题之间唯一的区别就是你想知道匹配的位置和方向。在这种情况下,这是对@ templatetypedef的function的一个小修改。

enum Direction { NONE, VERTICAL, HORIZONTAL, DIAGONAL_UP, DIAGONAL_DOWN }; 

Direction IsLineStartingAt(int x, int y) { 
    if (IsLinearMatch(x, y, 1, 0) return HORIZONTAL; 
    if (IsLinearMatch(x, y, 0, 1) return VERTICAL; 
    if (IsLinearMatch(x, y, 1, 1) return DIAGONAL_DOWN; 
    if (IsLinearMatch(x, y, 1, -1) return DIAGONAL_UP; 
    return NONE; 
} 

如果您运行的是通过一个for循环,您已经有X和Y起始位置,如果没有匹配,这将返回方向,或者没有。