1. 程式人生 > >以opengl製作2D貪吃蛇(一)

以opengl製作2D貪吃蛇(一)

1) 搭建好基本的視窗環境
    要確定視窗大小, 通過確定格子的大小(TILE_WIDTH, TILE_HEIGHT),

                            格子的數量(TILE_COLUMN, TILE_ROW)

2) 畫格子
     兩個迴圈

/*
 * 1) 搭建好基本的視窗環境
 *    要確定視窗大小, 通過確定格子的大小(TILE_WIDTH, TILE_HEIGHT),
 *                            格子的數量(TILE_COLUMN, TILE_ROW)
 */
 //2) 畫格子
 //*    兩個迴圈
//3) 畫方塊來表示蛇的身體
// *    glPointSize(..)
#include <stdio.h>
#include <GL/glew.h>
#include <GL/freeglut.h>

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

編譯得到

演示結果: