用c语言编写一个贪吃蛇游戏
时间: 2023-09-12 18:06:40 浏览: 93
好的,编写贪吃蛇游戏可以使用C语言和图形库(如graphics.h)来实现。以下是基本的代码框架:
```c
#include <graphics.h>
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define WIDTH 640
#define HEIGHT 480
#define BLOCK_SIZE 10
#define MAX_LENGTH 100
int x[MAX_LENGTH], y[MAX_LENGTH], length = 3;
int food_x, food_y;
int direction = 1; //0-up, 1-right, 2-down, 3-left
void init_game();
void draw_snake();
void move_snake();
void generate_food();
int check_collision(int x, int y);
int main() {
init_game();
while (1) {
move_snake();
delay(100);
}
return 0;
}
void init_game() {
int gdriver = DETECT, gmode;
initgraph(&gdriver, &gmode, "");
setbkcolor(WHITE);
setcolor(BLACK);
setfillstyle(SOLID_FILL, BLACK);
rectangle(0, 0, WIDTH, HEIGHT);
floodfill(1, 1, BLACK);
x[0] = WIDTH / 2;
y[0] = HEIGHT / 2;
x[1] = x[0] - BLOCK_SIZE;
y[1] = y[0];
x[2] = x[0] - 2 * BLOCK_SIZE;
y[2] = y[0];
draw_snake();
generate_food();
}
void draw_snake() {
int i;
for (i = 0; i < length; i++) {
bar(x[i], y[i], x[i] + BLOCK_SIZE, y[i] + BLOCK_SIZE);
}
}
void move_snake() {
int i;
for (i = length - 1; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
switch (direction) {
case 0:
y[0] -= BLOCK_SIZE;
break;
case 1:
x[0] += BLOCK_SIZE;
break;
case 2:
y[0] += BLOCK_SIZE;
break;
case 3:
x[0] -= BLOCK_SIZE;
break;
}
if (check_collision(x[0], y[0])) {
closegraph();
exit(0);
}
if (x[0] == food_x && y[0] == food_y) {
length++;
generate_food();
}
cleardevice();
draw_snake();
setfillstyle(SOLID_FILL, RED);
bar(food_x, food_y, food_x + BLOCK_SIZE, food_y + BLOCK_SIZE);
}
void generate_food() {
srand(time(NULL));
food_x = (rand() % (WIDTH / BLOCK_SIZE)) * BLOCK_SIZE;
food_y = (rand() % (HEIGHT / BLOCK_SIZE)) * BLOCK_SIZE;
}
int check_collision(int x, int y) {
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT) {
return 1;
}
int i;
for (i = 1; i < length; i++) {
if (x == x[i] && y == y[i]) {
return 1;
}
}
return 0;
}
```
这个代码框架实现了基本的贪吃蛇游戏逻辑,包括蛇的移动、食物的生成、碰撞检测等。你可以根据自己的需要来修改代码来完善游戏的功能和界面。
阅读全文