Four in a row logic

前端 未结 2 674
逝去的感伤
逝去的感伤 2020-12-16 23:15

I\'m currently working on a basic four in a row game for myself, but I\'m rather stuck at the logic behind it.

Currently I have this multi-dimensional array that rep

2条回答
  •  余生分开走
    2020-12-16 23:29

    I had developed four in a row game some time back. Here is the code snippet to check for winning condition that is four in a row condition : (This is in C language)

    int checkWinOrLose(int grid[][7],int result,int rowNum) {
    //  For checking whether any win or lose condition is reached. Returns 1 if win or lose is reached. else returns 0
    //  grid[][] is the 6X7 matrix
    //  result is the column number where the last coin was placed
    //  rowNum is the row number where the last coin was placed
    
        int player=grid[rowNum][result];
        if(rowNum<=2 && grid[rowNum+1][result]==player && grid[rowNum+2][result]==player && grid[rowNum+3][result]==player) // 4 in a row vertically
            return 1;
        else {
            int count=1,i,j;
            for(i=result+1;i<7;i++) { // 4 in a row horizontally
                if(grid[rowNum][i]!=player)
                    break;
                count++;
            }
            for(i=result-1;i>=0;i--) { // 4 in a row horizontally
                if(grid[rowNum][i]!=player)
                    break;
                count++;
            }
            if(count>=4)
                return 1;
            count=1;
            for(i=result+1,j=rowNum+1;i<7 && j<6;i++,j++) { // 4 in a row diagonally
                if(grid[j][i]!=player)
                    break;
                count++;
            }
            for(i=result-1,j=rowNum-1;i>=0 && j>=0;i--,j--) { // 4 in a row diagonally
                if(grid[j][i]!=player)
                    break;
                count++;
            }
            if(count>=4)
                return 1;
            count=1;
            for(i=result+1,j=rowNum-1;i<7 && j>=0;i++,j--) { // 4 in a row diagonally
                if(grid[j][i]!=player)
                    break;
                count++;
            }
            for(i=result-1,j=rowNum+1;i>=0 && j<6;i--,j++) { // 4 in a row diagonally
                if(grid[j][i]!=player)
                    break;
                count++;
            }
            if(count>=4)
                return 1;
        }
        return 0;
    }
    

提交回复
热议问题