Writing a Connect 4 Game using OpenGL

Materials available at: http://forejune.co/cuda/

Connect 4 Game



			
  • The game board has 6 rows x 7 columns holes.
  • Two players pick a color (typically, red or yellow).
  • Take turns to drop a colored disc from the top of a column which occupies the lowest hole.
  • The first player who forms a line of four adjacent discs, horizontally, vertically, or diagonally wins.
  • Stencil Buffer

    Reference: http://www.opengl.org/archives/resources/features/StencilTalk/

  • An extra, per-pixel data buffer used to mask out specific areas of the screen

  • Not the same as depth-buffer

  • Can be turned on or off

  • In general, the pixel value is rendered only if the stencil test passes.

  • Example:

      GL_EQUAL: Passes if ( ref & mask ) = ( stencil & mask ).

  • Stencil Test:
    • Takes place only if there is a stencil buffer.
    • Compares a reference value with the value stored at a pixel position of the stencil buffer
    • The value of the stencil buffer may be modified, depending on the result of the test.
    • OpenGL functions:

        void glStencilFunc(GLenum func, int ref, unsigned mask);

        void glStencilOp(GLenum stencil_test_fail, GLenum depth_test_fail,
                                 GLenum depth_test_pass);

  • //Draw the moving disc only through empty holes in its column.
    //The stencil buffer contains 1's inside empty holes 
    // and 0's elsewhere.
    void drawMovingDiscThroughHoles()
    {
        // Clear the stencil buffer and prepare to write 
        // the aperture mask.
        glClear(GL_STENCIL_BUFFER_BIT);
        glEnable(GL_STENCIL_TEST);
    
        // Draw the stencil mask without changing the 
        // visible color buffer
        // no change in color buffer (red, green, blue, alpha)
        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); 
    		
        // always passes stencil test with reference value 1
        glStencilFunc(GL_ALWAYS, 1, 0xFF);  
    
        // The stencil buffer value is always replaced by 
        //reference value 1
        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); 
    
        // This does not render the disc but only writes 
        // '1' to the stencil
        // buffer at corresponding pixel positions of the 'hole'.
        for (int row = 0; row < 6; row++) {
            if (board[row][currentCol] == EMPTY)
                drawDisc(cellX(currentCol), cellY(row), r);
        }
    
        // Draw the moving disc only where the stencil value is 1.
        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
        glStencilFunc(GL_EQUAL, 1, 0xFF);
        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
    
        // only the part of the disc that overlaps with the 
        // 'holes' is rendered
        // stencil buffer has value 1 at the 'holes'
        drawDisc(animateX, animateY, r);
    
        glDisable(GL_STENCIL_TEST);
    }
    				

    Full Implementation

    /* 
     * https://forejune.co/cuda/
     *
     * connectFourGraphics.cpp
     * Connect Four graphics test program.
     *
     * Controls:
     *   - Click above a column to drop the user's RED disc.
     *   * Press 't' to toggle between random move and mouse-click move
     *   * Press 'p' to toggle animation and static rendering
     *   - Press 'r' to reset the game.
     *   - Press ESC to quit.
     *
     * The moving disc is stencil-clipped to the empty circular openings in
     * its column, so it appears behind the blue board.
     */
    
    #include <GL/gl.h>
    #include <GL/glu.h>
    #include <GL/glut.h>
    
    #include <cmath>
    #include <cstdlib>
    #include <ctime>
    #include <iostream>
    #include <string>
    #include <vector>
    
    using namespace std;
    
    enum Player { EMPTY = 0, RED, YELLOW };
    
    Player board[6][7];
    Player playerRandom = YELLOW;      // Temporary random test player.
    Player opp = RED;        // User.
    Player turn = opp;       // User moves first.
    bool gameOver = false;
    
    bool moving = false;
    bool pause = false;
    bool useRandom = true;
    const float d = 1.0;          // Distance between adjacent cell centers.
    const float bw = 7.0 * d;     // Board width.
    const float bh = 6.0 * d;     // Board height.
    const float bx0 = d;           // Board lower-left x coordinate.
    const float by0 = 2.0;        // Board lower-left y coordinate.
    const float r = d / 2.5;      // Radius of each circular opening/disc.
    
    int currentCol = -1;           // Column currently being animated.
    int destRow = -1;              // Row where the moving disc will settle.
    float animateX = 0.0;	       // Animation coordinates
    float animateY = 0.0;
    
    // Colors.
    const float red[]    = {1, 0, 0};
    const float yellow[] = {1, 1, 0};
    const float blue[]   = {0, 0, 1};
    const float white[]  = {1, 1, 1};
    
    int window = 0;
    int screenWidth = 700;
    int screenHeight = 600;
    const float worldWidth = 9.0;
    const float worldHeight = 9.0;
    
    void resetBoard()
    {
        for (int row = 0; row < 6; row++) 
            for (int col = 0; col < 7; col++)
                board[row][col] = EMPTY;
        
        turn = opp;
        moving = false;
        currentCol = -1;
        destRow = -1;
        animateX = 0.0;
        animateY = 0.0;
        pause = false;
        gameOver = false;
        useRandom = true;
    }
    
    bool hasWon(Player player)
    {
      if (player != RED && player != YELLOW)
         return false;
    
      for (int row = 0; row < 6; row++) {
         for (int col = 0; col < 7; col++) {
    
          // The first cell must belong to the player being checked.
             if (board[row][col] != player)
                continue;
    
             // Horizontal (right).
             if (col + 3 < 7 &&
                  player == board[row][col + 1] &&
                  player == board[row][col + 2] &&
                  player == board[row][col + 3])
                  return true;
    
             // Vertical (down).
             if (row + 3 < 6 &&
                  player == board[row + 1][col] &&
                  player == board[row + 2][col] &&
                  player == board[row + 3][col])
                  return true;
    
             // Diagonal (down-right).
             if (row + 3 < 6 && col + 3 < 7 &&
                  player == board[row + 1][col + 1] &&
                  player == board[row + 2][col + 2] &&
                  player == board[row + 3][col + 3])
                  return true;
    
             // Diagonal (up-right).
             if (row - 3 >= 0 && col + 3 < 7 &&
                  player == board[row - 1][col + 1] &&
                  player == board[row - 2][col + 2] &&
                  player == board[row - 3][col + 3])
                  return true;
         }
      }
    
      return false;
    }
    
    bool boardFull()
    {
      for (int col = 0; col < 7; col++) {
         if (board[0][col] == EMPTY)
            return false;
      }
    
      return true;
    }
    
    float cellX(int col)
    {
        return bx0 + (col + 0.5f) * d;
    }
    
    float cellY(int row)
    {
        return by0 + bh - (row + 0.5f) * d;
    }
    
    // Return the lowest empty row in a column, or -1 if it is full.
    int getDestinationRow(int col)
    {
        if (col < 0 || col >= 7)
            return -1;
    
        for (int row = 5; row >= 0; row--) {
            if (board[row][col] == EMPTY)
                return row;
        }
    
        return -1;
    }
    
    // Start an animated move for the current player.
    bool startMove(int col)
    {
        if (gameOver || moving || col < 0 || col >= 7)
            return false;
    
        int row = getDestinationRow(col);
        if (row < 0)
            return false;
    
        currentCol = col;
        destRow = row;
        animateX = cellX(col);
        animateY = by0 + bh + 0.5f * d;
        moving = true;
    
        glutPostRedisplay();
        return true;
    }
    
    void displayMessage(float x, float y, void* font, const string& str)
    {
        glColor3f(0.0f, 0.0f, 0.0f);
        glRasterPos2f(x, y);
    
        for (char c : str)
            glutBitmapCharacter(font, c);
    }
    
    void printResult()
    {
        if (!gameOver)
            return;
    
        if (hasWon(opp))
            displayMessage(d, d, GLUT_BITMAP_TIMES_ROMAN_24, "You have won!");
        else if (hasWon(playerRandom))
            displayMessage(d, d, GLUT_BITMAP_TIMES_ROMAN_24, "Computer has won!");
        else
            displayMessage(d, d, GLUT_BITMAP_TIMES_ROMAN_24, "It was a draw!");
    }
    
    // Draw a flat 2D disc. Using 2D discs makes the stencil clipping predictable.
    void drawDisc(float cx, float cy, float radius)
    {
        const int n = 48;	// number of polygon sides
        const float pi = 3.14159;
    
        glBegin(GL_TRIANGLE_FAN);
        glVertex2f(cx, cy);
    
        for (int i = 0; i <= n; i++) {
            float angle = 2 * pi * i / n;
            glVertex2f(cx + radius * cos(angle),
                       cy + radius * sin(angle));
        }
    
        glEnd();
    }
    
    void drawBoardAndDiscs()
    {
        // The blue board face.
        glColor3fv(blue);
        glRectf(bx0, by0, bx0 + bw, by0 + bh);
    
        // Draw the circular openings. Empty positions are white; occupied
        // positions show the corresponding player's disc.
        for (int row = 0; row < 6; row++) {
            for (int col = 0; col < 7; col++) {
                if (board[row][col] == RED)
                    glColor3fv(red);
                else if (board[row][col] == YELLOW)
                    glColor3fv(yellow);
                else
                    glColor3fv(white);
    
                drawDisc(cellX(col), cellY(row), r);
            }
        }
    }
    
    // Draw the moving disc only through empty openings in its column.
    // The stencil buffer contains 1 inside those openings and 0 elsewhere.
    void drawMovingDiscThroughHoles()
    {
        if (!moving || currentCol < 0 || currentCol >= 7 || destRow < 0)
            return;
    
        // Clear the stencil buffer and prepare to write the aperture mask.
        glClear(GL_STENCIL_BUFFER_BIT);
        glEnable(GL_STENCIL_TEST);
    
        // Draw the stencil mask without changing the visible color buffer
        // no change in color buffer (red, green, blue, alpha)
        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); 
    
        // always passes stencil test with reference value 1
        glStencilFunc(GL_ALWAYS, 1, 0xFF);  
    
        // The stencil buffer value is always replaced by reference value 1
        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); 
    
        // This does not render the disc but only writes '1' to the stencil
        // buffer at corresponding pixel positions of the 'hole'.
        for (int row = 0; row < 6; row++) {	
            if (board[row][currentCol] == EMPTY)
                drawDisc(cellX(currentCol), cellY(row), r);
        }
    
        // Draw the moving disc only where the stencil value is 1.
        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
        glStencilFunc(GL_EQUAL, 1, 0xFF);
        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
    
        if (turn == RED)
            glColor3fv(red);
        else
            glColor3fv(yellow);
    
        // only the part of the disc that overlaps with the 'hole' is rendered
        drawDisc(animateX, animateY, r);
    
        glDisable(GL_STENCIL_TEST);
    }
    
    void display(void)
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
    
        drawBoardAndDiscs();
        drawMovingDiscThroughHoles();
        printResult();
    
        glutSwapBuffers();
    }
    
    // Temporary random computer move 
    int randomMove()
    {  
        vector<int> validCols;
    
        for (int col = 0; col < 7; col++) {
            if (board[0][col] == EMPTY)
                validCols.push_back(col);
        }
    
        if (validCols.empty())
            return -1;
    
        // Return an actual column number
        return validCols[rand() % validCols.size()];
    }
    
    // ------------------------------------------------------------
    // Mouse/keyboard input
    // ------------------------------------------------------------
    
    int getColumn(float x, float y)
    {
        // The player clicks in the strip immediately above the board.
        if (x < bx0 || x > bx0 + bw)
            return -1;
    
        if (y < by0 + bh + r || y > by0 + bh + d)
            return -1;
    
        float rightX = bx0 + d;
        int col = 0;
    
        while (col < 6) {
            if (x < rightX)
                break;
            rightX += d;
            col++;
        }
    
        return col;
    }
    
    void keyboard(unsigned char key, int, int)
    {
        switch (key) {
            case 27: // ESC
                glutDestroyWindow(window);
                exit(0);
    
    	case 'p':	// toggle pausing animation
    	    pause = pause ? false : true;
    	    break;
    
            case 'r':
                resetBoard();
                glutPostRedisplay();
                break;
    
    	case 't':	// toggle useRandom
    	    useRandom = useRandom ? false : true;
    	    break;
    
        }
    }
    
    void mouse(int button, int state, int mx, int my)
    {
        if (button != GLUT_LEFT_BUTTON || state != GLUT_DOWN)
            return;
    
        if (moving || gameOver )
            return;
    
        if ( useRandom && turn != opp )
           return;
    
        int sx = mx;
        int sy = screenHeight - my;
    
        float x = sx * worldWidth / screenWidth;
        float y = sy * worldHeight / screenHeight;
    
        int col = getColumn(x, y);
        if (col >= 0)
            startMove(col);
    }
    
    // ------------------------------------------------------------
    // Animation and timer
    // ------------------------------------------------------------
    
    void animate()
    {
        if (pause || !moving || gameOver)
            return;
    
        if (currentCol < 0 || currentCol >= 7 || destRow < 0) {
            moving = false;
            currentCol = -1;
            destRow = -1;
            glutPostRedisplay();
            return;
        }
    
        animateY -= d / 10.0f;
    
        float targetY = cellY(destRow);
        if (animateY <= targetY) {
            animateY = targetY;
    
            // Commit the move to the board.
            board[destRow][currentCol] = turn;
            moving = false;
    
            if (hasWon(turn) || boardFull()) 
                gameOver = true;
            else 
                turn = (turn == opp) ? playerRandom : opp;
    
            currentCol = -1;
            destRow = -1;
    	if ( turn == playerRandom && useRandom )  
               startMove(randomMove());
    
        }
    
        glutPostRedisplay();
    }
    
    void timerHandle(int)
    {
        animate();
        glutTimerFunc(30, timerHandle, 0);
    }
    
    // ------------------------------------------------------------
    // OpenGL/GLUT initialization
    // ------------------------------------------------------------
    
    void init(void)
    {
        glClearColor(1, 1, 1, 1);
    
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluOrtho2D(0.0, worldWidth, 0.0, worldHeight);
    
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
    
        // This is a 2D scene; depth testing is not needed.
        glDisable(GL_DEPTH_TEST);
        glDisable(GL_STENCIL_TEST);
    
        resetBoard();
    }
    
    int graphics(int argc, char** argv)
    {
        glutInit(&argc, argv);
    
        // A stencil buffer is required to mask the moving disc to the holes.
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_STENCIL);
        glutInitWindowSize(screenWidth, screenHeight);
        glutInitWindowPosition(100, 100);
    
        window = glutCreateWindow("Connect 4 Game");
    
        GLint stencilBits = 0;
        glGetIntegerv(GL_STENCIL_BITS, &stencilBits);
        if (stencilBits == 0) {
            cerr << "Warning: no stencil buffer was created; "
                 << "the falling-disc hole mask will not work.\n";
        }
    
        glutDisplayFunc(display);
        glutKeyboardFunc(keyboard);
        glutMouseFunc(mouse);
    
        init();
        glutTimerFunc(20, timerHandle, 0);
        glutMainLoop();
    
        return 0;
    }
    
    int main(int argc, char** argv)
    {
        // Seed once, for randomMove() 
        srand(static_cast<unsigned int>(time(nullptr)));
    
        graphics(argc, argv);
        return 0;
    }