#include <gl\glut.h>
#include <cstdlib>
#include <ctime>
#include <cstdlib>
#include <windows.h>
int x,y;
int key = GLUT_KEY_RIGHT;
int snake[100][2];
int len = 5;
void myDisplay( void )
{
glClear( GL_COLOR_BUFFER_BIT );
glColor3f( 1.0f, 1.0f, 1.0f );
for ( int i = 0; i < len; ++i )
{
glRecti( snake[i][0], snake[i][1], snake[i][0]+1, snake[i][1]+1 );
}
glColor3f( 1.0f, 0.0f, 0.0f );
glRecti( x, y, x+1, y+1 );
glutSwapBuffers();
}
int Hit( int x, int y )
{
int i;
for ( i = 0; i < len; ++i )
{
if ( snake[i][0] == x && snake[i][1] == y )
{
return 1;
}
}
return 0;
}
int Eat( int a, int b )
{
if ( a == x && y == b )
{
do
{
x = rand()%64;
y = rand()%48;
} while ( Hit(x,y) );
return 1;
}
return 0;
}
void Add( int a, int b )
{
snake[len][0] = a;
snake[len][1] = b;
++len;
}
void Move( int x, int y )
{
int i;
for ( i = 0; i < len-1; ++i )
{
snake[i][0] = snake[i+1][0];
snake[i][1] = snake[i+1][1];
}
snake[len-1][0] = x;
snake[len-1][1] = y;
}
void Step( void )
{
switch ( key )
{
case GLUT_KEY_RIGHT:
if ( Hit( snake[len-1][0]+1, snake[len-1][1] ) == 1 )
{
exit(0);
}
else if ( Eat( snake[len-1][0]+1, snake[len-1][1] ) )
{
Add( snake[len-1][0]+1, snake[len-1][1] );
}
else
{
Move( snake[len-1][0]+1, snake[len-1][1] );
}
break;
case GLUT_KEY_LEFT:
if ( Hit( snake[len-1][0]-1, snake[len-1][1] ) == 1 )
{
exit(0);
}
else if ( Eat( snake[len-1][0]-1, snake[len-1][1] ) )
{
Add( snake[len-1][0]-1, snake[len-1][1] );
}
else
{
Move( snake[len-1][0]-1, snake[len-1][1] );
}
break;
case GLUT_KEY_UP:
if ( Hit( snake[len-1][0], snake[len-1][1]+1 ) == 1 )
{
exit(0);
}
else if ( Eat( snake[len-1][0], snake[len-1][1]+1 ) )
{
Add( snake[len-1][0], snake[len-1][1]+1 );
}
else
{
Move( snake[len-1][0], snake[len-1][1]+1 );
}
break;
case GLUT_KEY_DOWN:
if ( Hit( snake[len-1][0], snake[len-1][1]-1 ) == 1 )
{
exit(0);
}
else if ( Eat( snake[len-1][0], snake[len-1][1]-1 ) )
{
Add( snake[len-1][0], snake[len-1][1]-1 );
}
else
{
Move( snake[len-1][0], snake[len-1][1]-1 );
}
break;
default:
break;
}
}
void myKey( int k, int not_use, int not_use1 )
{
switch ( k )
{
case GLUT_KEY_DOWN:
if ( key != GLUT_KEY_UP )
{
key = k;
Step();
}
break;
case GLUT_KEY_UP:
if ( key != GLUT_KEY_DOWN )
{
key = k;
Step();
}
break;
case GLUT_KEY_LEFT:
if ( key != GLUT_KEY_RIGHT )
{
key = k;
Step();
}
break;
case GLUT_KEY_RIGHT:
if ( key != GLUT_KEY_LEFT )
{
key = k;
Step();
}
break;
default:
break;
}
glutPostRedisplay();
}
void Init( void )
{
int i;
for ( i = 0; i < len; ++i )
{
snake[i][0] = i;
snake[i][1] = 0;
}
srand( GetTickCount() );
do
{
x = rand()%64;
y = rand()%48;
} while ( Hit(x,y) );
}
int main( int argc, char* argv[] )
{
Init();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(640, 480);
glutCreateWindow("第一个OpenGL程序");
glutSpecialFunc( &myKey );
glutDisplayFunc(&myDisplay);
gluOrtho2D( 0, 64, 0, 48 );
glutMainLoop();
return 0;
}
大家很默契地一起停了随笔。我最近累的头昏脑胀。人是需要压力的,要自己给自己压力,不要总拖拖拉拉拖到deadline,自己也会不爽的。
我会严格要求自己的。