2011-01-10 68 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起始位置,如果沒有匹配,這將返回方向,或者沒有。