可以提供一个C语言OpenGL编写的贪吃神代码吗
时间: 2024-02-06 17:10:04 浏览: 77
当然可以,以下是一个简单的 C 语言 OpenGL 编写的贪吃蛇游戏示例代码:
```c
#include <GL/glut.h>
#include <stdlib.h>
#include <time.h>
#define GRID_SIZE 20
#define GRID_WIDTH 30
#define GRID_HEIGHT 30
int direction = GLUT_KEY_RIGHT;
int food_x, food_y;
int snake_length = 3;
int snake_x[100], snake_y[100];
void init() {
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, GRID_WIDTH * GRID_SIZE, 0, GRID_HEIGHT * GRID_SIZE);
srand(time(NULL));
food_x = rand() % GRID_WIDTH;
food_y = rand() % GRID_HEIGHT;
}
void draw_square(int x, int y) {
glBegin(GL_QUADS);
glVertex2i(x, y);
glVertex2i(x + GRID_SIZE, y);
glVertex2i(x + GRID_SIZE, y + GRID_SIZE);
glVertex2i(x, y + GRID_SIZE);
glEnd();
}
void draw_snake() {
glColor3f(1.0, 1.0, 1.0);
for (int i = 0; i < snake_length; i++) {
draw_square(snake_x[i] * GRID_SIZE, snake_y[i] * GRID_SIZE);
}
}
void draw_food() {
glColor3f(1.0, 0.0, 0.0);
draw_square(food_x * GRID_SIZE, food_y * GRID_SIZE);
}
void check_food() {
if (snake_x[0] == food_x && snake_y[0] == food_y) {
food_x = rand() % GRID_WIDTH;
food_y = rand() % GRID_HEIGHT;
snake_length++;
}
}
void check_collision() {
for (int i = 1; i < snake_length; i++) {
if (snake_x[0] == snake_x[i] && snake_y[0] == snake_y[i]) {
exit(0);
}
}
if (snake_x[0] < 0 || snake_x[0] >= GRID_WIDTH || snake_y[0] < 0 || snake_y[0] >= GRID_HEIGHT) {
exit(0);
}
}
void move_snake() {
for (int i = snake_length - 1; i > 0; i--) {
snake_x[i] = snake_x[i-1];
snake_y[i] = snake_y[i-1];
}
switch (direction) {
case GLUT_KEY_UP:
snake_y[0]++;
break;
case GLUT_KEY_DOWN:
snake_y[0]--;
break;
case GLUT_KEY_LEFT:
snake_x[0]--;
break;
case GLUT_KEY_RIGHT:
snake_x[0]++;
break;
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
draw_snake();
draw_food();
glutSwapBuffers();
}
void timer(int value) {
move_snake();
check_food();
check_collision();
glutPostRedisplay();
glutTimerFunc(100, timer, 0);
}
void keyboard(int key, int x, int y) {
switch (key) {
case GLUT_KEY_UP:
case GLUT_KEY_DOWN:
case GLUT_KEY_LEFT:
case GLUT_KEY_RIGHT:
direction = key;
break;
}
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(GRID_WIDTH * GRID_SIZE, GRID_HEIGHT * GRID_SIZE);
glutCreateWindow("OpenGL Snake Game");
init();
glutDisplayFunc(display);
glutSpecialFunc(keyboard);
glutTimerFunc(0, timer, 0);
glutMainLoop();
return 0;
}
```
这个代码使用了 OpenGL 库来绘制游戏界面,可以在 Windows、Linux 和 macOS 等操作系统上编译运行。在运行时,你可以通过方向键来控制贪吃蛇的移动方向,尝试吃掉食物并避免碰到边界和自身。
阅读全文