时间:2021-07-01 10:21:17 帮助过:21人阅读
1) 搭建好基本的窗口环境 要确定窗口大小, 通过确定子的大小(TILE_WIDTH, TILE_HEIGHT), 子的数量(TILE_COLUMN, TILE_ROW) 2) 画子 两个循环 /* * 1) 搭建好基本的窗口环境 * 要确定窗口大小, 通过确定格子的大小(TILE_WIDTH, TILE_HEIGHT), * 格子的数量(TIL
1) 搭建好基本的窗口环境格子的数量(TILE_COLUMN, TILE_ROW)
2) 画格子
两个循环
/* * 1) 搭建好基本的窗口环境 * 要确定窗口大小, 通过确定格子的大小(TILE_WIDTH, TILE_HEIGHT), * 格子的数量(TILE_COLUMN, TILE_ROW) */ //2) 画格子 //* 两个循环 //3) 画方块来表示蛇的身体 // * glPointSize(..) #include#include #include int TILE_WIDTH = 32; int TILE_HEIGHT = 32; const int TILE_COLUMN = 20; const int TILE_ROW = 11; const int dt = 33; /* 毫秒数 */ #define DIR_UP 0 #define DIR_DOWN 1 #define DIR_LEFT 2 #define DIR_RIGHT 3 #define GL_PI 3.1415f int dir = DIR_RIGHT; float snake_x = 0; float snake_y = 0; float snake_v = 3; float food_x = 10; float food_y = 5; void ChangeSize(int w,int h) { GLfloat nRange = 100.0f; // Prevent a divide by zero if(h == 0) h = 1; // Set Viewport to window dimensions glViewport(0, 0, w, h); // Reset coordinate system glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Establish clipping volume (left, right, bottom, top, near, far) glOrtho (0.0f,TILE_COLUMN*TILE_WIDTH,TILE_ROW*TILE_HEIGHT,0,-1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void SetupRC()//在循环之前,为程序做一些一次性的设置 { // background color glClearColor(0.0f, 0.0f, 0.0f, 1.0f ); glColor3f(0.0f,1.0f,0.0f); } void RenderScene(void) {GLfloat x,y,z,angle; // Clear the window with current clearing color glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glPointSize(TILE_HEIGHT); glBegin(GL_POINTS); glVertex3f(snake_x+TILE_WIDTH/2,snake_y+TILE_HEIGHT/2,0.0f); glEnd(); for(float line_y=0;line_y<=TILE_ROW*TILE_HEIGHT;line_y += TILE_HEIGHT) { glBegin(GL_LINES); glVertex2f(0.0f,line_y); glVertex2f(TILE_COLUMN*TILE_WIDTH,line_y); glEnd(); } for(float line_x=0;line_x<=TILE_COLUMN*TILE_WIDTH;line_x+=TILE_WIDTH) { glBegin(GL_LINES); glVertex2f(line_x,0.0f); glVertex2f(line_x,TILE_COLUMN*TILE_WIDTH); glEnd(); } glPopMatrix(); glutSwapBuffers(); } int main(int argc,char* argv[]) { //基于GLUT的标准设置 glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize(TILE_WIDTH*TILE_COLUMN,TILE_HEIGHT*TILE_ROW); glutCreateWindow("Snake"); glutReshapeFunc(ChangeSize); glutDisplayFunc(RenderScene); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); return 1; } SetupRC(); glutMainLoop(); } g++ -g nima.cpp -o nima -lGL -lglut -lGLEW
编译得到
演示结果: