贪吃蛇游戏c语言程序代码
时间: 2023-12-14 13:35:05 浏览: 97
好的,下面是一个简单的C语言贪吃蛇游戏程序代码,希望能够帮到你:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 30
#define HEIGHT 20
int score = 0; // 记录得分
int speed = 200; // 控制速度
// 定义蛇的结构体
struct Snake {
int x;
int y;
struct Snake *next;
};
// 定义食物的结构体
struct Food {
int x;
int y;
};
// 初始化蛇
struct Snake *initSnake() {
struct Snake *head = (struct Snake*)malloc(sizeof(struct Snake));
head->x = WIDTH / 2;
head->y = HEIGHT / 2; head->next = NULL;
return head;
}
// 初始化食物
struct Food initFood() {
struct Food food;
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
return food;
}
// 画出地图
void drawMap(struct Snake *snake, struct Food food) {
system("cls"); // 清屏
for (int i = 0; i < WIDTH + 2; i++) {
printf("#");
}
printf("\n");
for (int i = 0; i < HEIGHT; i++) {
printf("#");
for (int j = 0; j < WIDTH; j++) {
if (i == food.y && j == food.x) {
printf("F");
} else if (i == snake->y && j == snake->x) {
printf("S");
} else {
struct Snake *p = snake->next;
int flag = 0;
while (p != NULL) {
if (i == p->y && j == p->x) {
printf("s");
flag = 1;
break;
}
p = p->next;
}
if (!flag) {
printf(" ");
}
}
}
printf("#\n");
}
for (int i = 0; i < WIDTH + 2; i++) {
printf("#");
}
printf("\n");
printf("Score: %d\n", score);
}
// 蛇移动
void move(struct Snake *snake, int direction) {
int x = snake->x;
int y = snake->y;
switch (direction) {
case 1: // 上
y--;
break;
case 2: // 下
y++;
break;
case 3: // 左
x--;
break;
case 4: // 右
x++;
break;
}
struct Snake *p = snake;
while (p->next != NULL) {
p = p->next;
}
free(p);
struct Snake *newHead = (struct Snake*)malloc(sizeof(struct Snake));
newHead->x = x;
newHead->y = y;
newHead->next = snake;
snake = newHead;
}
// 判断是否吃到食物
int eatFood(struct Snake *snake, struct Food food) {
if (snake->x == food.x && snake->y == food.y) {
struct Snake *newHead = (struct Snake*)malloc(sizeof(struct Snake));
newHead->x = food.x;
newHead->y = food.y;
newHead->next = snake;
snake = newHead;
score++;
return 1;
}
return 0;
}
// 判断是否撞墙或者撞到自己
int isOver(struct Snake *snake) {
if (snake->x < 0 || snake->x >= WIDTH || snake->y < 0 || snake->y >= HEIGHT) {
return 1;
}
struct Snake *p = snake->next;
while (p != NULL) {
if (p->x == snake->x && p->y == snake->y) {
return 1;
}
p = p->next;
}
return 0;
}
int main() {
struct Snake *snake = initSnake();
struct Food food = initFood();
int direction = 4; // 初始方向向右
while (1) {
drawMap(snake, food);
if (eatFood(snake, food)) {
food = initFood();
}
if (isOver(snake)) {
printf("Game Over!\n");
break;
}
if (_kbhit()) { // 判断是否有键盘输入
char ch = _getch();
switch (ch) {
case 'w':
if (direction != 2) {
direction = 1;
}
break;
case 's':
if (direction != 1) {
direction = 2;
}
break;
case 'a':
if (direction != 4) {
direction = 3;
}
break;
case 'd':
if (direction != 3) {
direction = 4;
}
break;
}
}
move(snake, direction);
Sleep(speed); // 控制速度
}
return 0;
}
```
阅读全文