如何在OpenGl中制作2d棋盘

How to make 2d Chess Board in OpenGl

本文关键字:2d 棋盘 OpenGl      更新时间:2023-10-16

我必须用 VisualC++ 在 OpenGL 中制作一个 8 * 8 个方块的 2d 棋盘。我有以下代码我尝试过.

但是我在这个代码中有一个问题.

  1. 我无法减小电路板尺寸,例如 5*5。
  2. 当我单击窗口时,它会重新绘制板。
  3. 我想让这段代码只使用循环。除非 ,否则。


#include<GLglut.h>
int black=0,white=1,color=0;
GLint a1=10,b1=10,a2=30,b2=30;
void init (void)
{
  glClearColor (0.0, 0.0,1.0,0.0);
  glMatrixMode (GL_PROJECTION);
  glClear (GL_COLOR_BUFFER_BIT);
  gluOrtho2D (0.0,120.0,0.0,140.0);
}
void lineSegment ()
{       
  for(int i=0;i<3;i++)
  {
    if(b2<120)
    {
      a1=10;b1=b2;
      a2=30;b2=b2+20;
    }
    for(int j=0;j<5;j++)
    {
      if(a2<120)
      {
        if(color==black)
        {
          glColor3f(0,0,0);
          glRecti(a1,b1,a2,b2);
          color=1;
          a1=a2;
          a2=a2+20;
        }
        else
        {                   
          glColor3f(1,1,1);
          glRecti(a1,b1,a2,b2);
          color=0;
          a1=a2;
          a2=a2+20;
        }
      }
    }
    //GLint a1=10,b1=10,a2=30,b2=30;    
  }         
  glFlush();
}       
void main (int argc, char** argv)
{       
  glutInit(&argc,argv); //Initialize GLUT.
  glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // Set display mode.
  glutInitWindowPosition (50,100); //Set top-left display-window position.
  glutInitWindowSize (400,300); //Set display-window width and height.
  glutCreateWindow ("An Example OpenGL Program"); //Create display window.
  init(); // Execute initialization procedure.
  glutDisplayFunc(lineSegment); //send graphics to display window.
  glutMainLoop(); //display everything and wait.
}

我建议你大大减少你正在使用的代码。定义电路板的宽度和高度以及电路板每侧的分区数。

让我们分别将宽度和高度定义为wh,并分别nm的分区数。 W.L.O.G. 假设nm平均划分wh

void DrawBoard(int w, int h, int n, int m) {
  bool color = true;
  int sw = w/n, sh = h/m; //square width and height respectively
  //for each width and height draw a rectangle with a specific color
  for(int i = 0; i < n; ++i) {
    for(int j = 0; j < m; ++j) {
      //oscillate the color per square of the board
      if(color)
        glColor3f(1, 1, 1);
      else
        glColor3f(0, 0, 0);
      color = !color;
      //draw a rectangle in the ith row and jth column
      glRecti(i*sw, j*sh, (i+1)*sw, (j+1)*sh);
    }
    if(m % 2 == 0) color = !color; //switch color order at end of row if necessary
  }
}

这应该给出基本的想法,尽管我可能会犹豫一两个索引。但本质上,迭代网格单元格并为每个板正方形绘制一个矩形。

此代码还将绘制从坐标 (0, 0) 开始并在 (w, h) 结束的电路板。但是,如果您希望它位于任意位置,则可以在glRecti调用中添加(x,y)到eaxh相应的坐标,或者了解openGL中的转换并使用glTranslatef