分类: C/C++
2008-08-05 13:57:06
//知道所有的胜利组合状态,我们可以定义一个数组记录这些组合. BOOL bArrPlayerWin[ 10 ][ 10 ][ 192 ] = { FALSE }; BOOL bArrComWin[ 10 ][ 10 ][ 192 ] = { FALSE };这是一个三维数组, 记录了在棋盘中所有的胜利组合.如玩家在棋盘 列1 行1的位置,则有三种胜利组合,如图:
void InitWinStatus() { int nCount = 0; // Set the vertical combinations winning status. for ( int i = 0; i < 10; i ) for ( int j = 0; j < 6; j ) { for ( int k = 0; k < 5; k ) { bArrPlayerWin[ j k ][ i ][ nCount ] = TRUE; bArrComWin[ j k ][ i ][ nCount ] = TRUE; } nCount ; } // Vertical has 60 winning status. assert( nCount == 60 ); // Set the horizontal combinations winning status. for ( i = 0; i < 10; i ) for ( int j = 0; j < 6; j ) { for ( int k = 0; k < 5; k ) { bArrPlayerWin[ i ][ j k ][ nCount ] = TRUE; bArrComWin[ i ][ j k ][ nCount ] = TRUE; } nCount ; } // Horizontal has 60 winning status assert( nCount == 120 ); // Set the positive diagonal winning status. for ( i = 0; i < 6; i ) for ( int j = 0; j < 6; j ) { for ( int k = 0; k < 5; k ) { bArrPlayerWin[ j k ][ i k ][ nCount ] = TRUE; bArrComWin[ j k ][ i k ][ nCount ] = TRUE; } nCount ; } // Positive diagonal has 36 winning status. assert( nCount == 156 ); // Set the negative diagonal winning status. for ( i = 0; i < 6; i ) for ( int j = 9; j > 3; j-- ) { for ( int k = 0; k < 5; k ) { bArrPlayerWin[ j - k ][ i k ][ nCount ] = TRUE; bArrComWin[ j - k ][ i k ][ nCount ] = TRUE; } nCount ; } // Negative diagonal has 36 winning status. assert( nCount == 192 ); // Who is the first ? if ( rand() % 2 == 0 ) bPlayerDo = TRUE; else bComputerDo = TRUE; }第二步,电脑计算玩家下棋状态采取进攻或防守的策略,这是五子棋的关键所在,这儿给出实现的伪代码.
// 计算玩家的状态. for ( int i = 0; i < 10; i ) for ( int j = 0; j < 10; j ) if ( nArrBoard[ i ][ j ] == NoBall ) { // 利用一个变量记录该位置的分值. nArrPlayerGrades[ i ][ j ] = 0; for ( int k = 0; k < 192; k ) // 该位置是在获胜的组合中. if ( bArrPlayerWin[ i ][ j ][ k ] ) switch( nArrWinner[ nPlayer ][ k ] ) // 根据放在组合的棋子数计算分值. // 棋数越多,分值越高. } // 计算电脑的状态, 代码同上. ......... // 判断情况 if ( nArrComGrades[ i ][ j ] < nArrPlayerGrades[ i ][ j ] ) // 该胜利组合中有可能输 进攻; else 防守;
for ( int i = 0; i <= 1; i ) for ( int j = 0; j < 192; j ) { if ( nArrWinner[ i ][ j ] == 5 ) if ( i == nPlayer ) { bPlayerWin = TRUE; bOver = TRUE; break; } else { bComputerWin = TRUE; bOver = TRUE; break; } if ( bOver ) break; }遍历所有的胜利组合, 如果所属的组合已经有五颗棋子,有则游戏结束!这只是简单地说明我实现的过程,附件中附有五子棋的所有源代码,你自已修改这些代码,增加功能。