使用C语言设计一个贪吃蛇代码
时间: 2024-03-10 07:49:00 浏览: 68
好的,以下是一个简单的贪吃蛇游戏的C语言代码,希望能帮到你:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#define WIDTH 80 // 游戏区域宽度
#define HEIGHT 24 // 游戏区域高度
#define INIT_LENGTH 5 // 贪吃蛇初始长度
int score; // 得分
int speed; // 速度
int gameOver; // 游戏是否结束
int foodX, foodY; // 食物的位置
// 贪吃蛇的结构体
struct snake {
int x, y; // 贪吃蛇的位置
struct snake *next; // 指向下一个节点的指针
};
struct snake *head, *tail; // 贪吃蛇的头和尾指针
// 初始化游戏
void init() {
int i;
struct snake *p;
// 初始化贪吃蛇
head = tail = (struct snake*)malloc(sizeof(struct snake));
head->x = WIDTH / 2;
head->y = HEIGHT / 2;
head->next = NULL;
for (i = 1; i < INIT_LENGTH; i++) {
p = (struct snake*)malloc(sizeof(struct snake));
p->x = head->x - i;
p->y = head->y;
p->next = head;
head = p;
}
// 初始化得分、速度和游戏结束标志
score = 0;
speed = 100;
gameOver = 0;
// 随机生成食物的位置
srand(time(NULL));
foodX = rand() % (WIDTH - 2) + 1;
foodY = rand() % (HEIGHT - 2) + 1;
}
// 显示游戏画面
void display() {
int i, j;
struct snake *p;
// 清屏
system("cls");
// 绘制游戏区域
for (i = 0; i <= HEIGHT; i++) {
for (j = 0; j <= WIDTH; j++) {
if (i == 0 || i == HEIGHT || j == 0 || j == WIDTH) {
printf("#");
} else if (i == foodY && j == foodX) {
printf("*");
} else {
p = head;
while (p) {
if (p->x == j && p->y == i) {
printf("O");
break;
}
p = p->next;
}
if (!p) {
printf(" ");
}
}
}
printf("\n");
}
// 显示得分和速度
printf("Score: %d Speed: %d\n", score, speed);
}
// 更新贪吃蛇的位置
void update() {
int dx = 0, dy = 0;
struct snake *p;
// 获取键盘输入
if (_kbhit()) {
switch (_getch()) {
case 'w': // 上
dx = 0;
dy = -1;
break;
case 's': // 下
dx = 0;
dy = 1;
break;
case 'a': // 左
dx = -1;
dy = 0;
break;
case 'd': // 右
dx = 1;
dy = 0;
break;
}
}
// 计算贪吃蛇的新位置
p = (struct snake*)malloc(sizeof(struct snake));
p->x = head->x + dx;
p->y = head->y + dy;
p->next = head;
// 判断是否吃到了食物
if (p->x == foodX && p->y == foodY) {
score++;
speed -= 5;
if (speed < 20) {
speed = 20;
}
foodX = rand() % (WIDTH - 2) + 1;
foodY = rand() % (HEIGHT - 2) + 1;
} else {
tail = tail->next;
free(tail->next);
}
// 判断是否碰到了边界或自己
if (p->x <= 0 || p->x >= WIDTH || p->y <= 0 || p->y >= HEIGHT) {
gameOver = 1;
} else {
struct snake *q = head->next;
while (q) {
if (p->x == q->x && p->y == q->y) {
gameOver = 1;
break;
}
q = q->next;
}
}
// 更新贪吃蛇的位置
if (!gameOver) {
head = p;
}
}
// 游戏主循环
void gameLoop() {
while (!gameOver) {
display();
update();
Sleep(speed);
}
}
// 结束游戏
void gameOverFunc() {
printf("Game Over!\n");
printf("Your score is: %d\n", score);
system("pause");
}
int main() {
init();
gameLoop();
gameOverFunc();
return 0;
}
```
这是一个比较简单的贪吃蛇游戏代码,你可以根据自己的需求进行修改和补充。希望对你有所帮助!