#include <time.h>
#include <stdlib.h>
#include <glut.h>
int n = 30, m = 20;
int scale = 25;
int w = scale * n;
int h = scale * m;
int dir, num = 4;
bool controls_arrows = true;
struct
{
int x, y;
}
s[100];
class Apple
{
public:
int x, y;
void New()
{
x = rand() % n;
y = rand() % m;
}
void Draw_apple()
{
glColor3f(0.0, 0.0, 1.0);
glRectf(x * scale, y * scale, (x + 1) * scale, (y + 1) * scale);
}
}
m[10];
void Draw_snake()
{
glColor3f(0.0, 0.0, 1.0);
for (int i = 0; i < num; i++)
glRectf(s[i].x * scale, s[i].y * scale, (s[i].x + 0.9) * scale, (s[i].y + 0.9) * scale);
}
void Tick()
{
for (int i = num; i > 0; --i)
{
s[i].x = s[i - 1].x;
s[i].y = s[i - 1].y;
}
if (dir == 0) s[0].y += 1;
if (dir == 1) s[0].x -= 1;
if (dir == 2) s[0].x += 1;
if (dir == 3) s[0].y -= 1;
for (int i = 0; i<10; i++)
if ((s[0].x == m[i].x) && (s[0].y == m[i].y))
{
num++; m[i].New();
}
if (s[0].x > n) dir = 1;
if (s[0].x < 0) dir = 2;
if (s[0].y > m) dir = 3;
if (s[0].y < 0) dir = 0;
for (int i = 0; i < num; i++)
if (s[0].x == s[i].x && s[0].y == s[i].y) num = i;
}
void Draw_field()
{
glColor3f(0.0, 7.0, 0.0);
glBegin(GL_LINES);
for (int i = 0; i < w; i += scale)
{
glVertex2f(i, 0);
glVertex2f(i, h);
}
for (int j = 0; j < w; j += scale)
{
glVertex2f(0, j);
glVertex2f(w, j);
}
glEnd();
}
void Display()
{
glClear(GL_COLOR_BUFFER_BIT);
Draw_field();
Draw_snake();
for (int i = 0; i < 10; i++)
m[i].Draw_apple();
glFlush();
glutSwapBuffers();
}
void Keyboard(int key, int a, int b)
{
switch (key)
{
if (controls_arrows == true) case 101: dir = 0; break;
if (controls_arrows == true) case 102: dir = 2; break;
if (controls_arrows == true) case 100: dir = 1; break;
if (controls_arrows == true) case 103: dir = 3; break;
}
}
void Timer(int i = 0)
{
Display();
Tick();
glutTimerFunc(50, Timer, 0);
}
int main(int argc, char **argv)
{
srand(time(0));
for (int i = 0; i < 10; i++)
m[i].New();
s[i].x = 10;
s[i].y = 10;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(w, h);
glutCreateWindow("Snake");
glClearColor(1.0, 1.0, 0.6, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, w, 0, h);
glutDisplayFunc(Display);
glutSpecialFunc(Keyboard);
glutTimerFunc(50, Timer, 0);
glutMainLoop();
}
|