用vs写贪吃蛇代码c语言,用C语言编写贪吃蛇代码(难度可选)
时间: 2024-02-25 08:56:29 浏览: 64
tanchishe.rar_c 小游戏代码_c语言 小游戏_c语言 贪吃蛇_c语言小游戏_贪吃蛇
好的,这是一个比较基础的贪吃蛇游戏代码,你可以根据需求进行修改和优化。
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define WIDTH 30 // 地图宽度
#define HEIGHT 20 // 地图高度
#define INIT_LENGTH 4 // 初始蛇长
#define FOOD_SCORE 10 // 食物分数
typedef struct {
int x, y;
} Point;
typedef struct {
Point head;
Point body[WIDTH * HEIGHT];
int length;
int score;
} Snake;
typedef struct {
Point pos;
int score;
} Food;
void initSnake(Snake* s) {
s->head.x = WIDTH / 2;
s->head.y = HEIGHT / 2;
s->length = INIT_LENGTH;
s->score = 0;
for (int i = 0; i < s->length; i++) {
s->body[i].x = s->head.x;
s->body[i].y = s->head.y + i;
}
}
void initFood(Food* f, Snake s) {
srand((unsigned int)time(NULL));
do {
f->pos.x = rand() % WIDTH;
f->pos.y = rand() % HEIGHT;
} while (s.head.x == f->pos.x && s.head.y == f->pos.y);
f->score = FOOD_SCORE;
}
void printMap(Snake s, Food f) {
system("cls"); // 清空屏幕
printf("Score: %d\n", s.score);
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (x == s.head.x && y == s.head.y) {
printf("O");
} else if (x == f.pos.x && y == f.pos.y) {
printf("*");
} else {
int isBody = 0;
for (int i = 0; i < s.length; i++) {
if (x == s.body[i].x && y == s.body[i].y) {
printf("o");
isBody = 1;
break;
}
}
if (!isBody) {
printf(" ");
}
}
}
printf("\n");
}
}
void moveSnake(Snake* s, Food f, int dir) {
// 记录尾巴位置
Point tail = s->body[s->length - 1];
for (int i = s->length - 1; i > 0; i--) {
s->body[i] = s->body[i - 1];
}
s->body[0] = s->head;
switch (dir) {
case 'w':
s->head.y--;
break;
case 's':
s->head.y++;
break;
case 'a':
s->head.x--;
break;
case 'd':
s->head.x++;
break;
}
// 判断是否吃到食物
if (s->head.x == f.pos.x && s->head.y == f.pos.y) {
s->length++;
s->body[s->length - 1] = tail;
s->score += f.score;
initFood(&f, *s);
}
// 判断是否撞墙或撞到自己
for (int i = 0; i < s->length; i++) {
if (s->head.x == s->body[i].x && s->head.y == s->body[i].y) {
printf("Game Over! Score: %d\n", s->score);
exit(0);
}
}
if (s->head.x < 0 || s->head.x >= WIDTH || s->head.y < 0 || s->head.y >= HEIGHT) {
printf("Game Over! Score: %d\n", s->score);
exit(0);
}
}
int main() {
Snake snake;
Food food;
initSnake(&snake);
initFood(&food, snake);
printMap(snake, food);
while (1) {
if (_kbhit()) { // 判断是否有键盘输入
char c = _getch(); // 获取键盘输入
if (c == 'w' || c == 's' || c == 'a' || c == 'd') {
moveSnake(&snake, food, c);
}
}
moveSnake(&snake, food, ' '); // 没有键盘输入时默认向前移动
printMap(snake, food);
Sleep(100); // 休眠100毫秒
}
return 0;
}
```
这个代码使用了控制台窗口,可以在Windows系统中运行。如果需要在其他平台上运行,需要修改清屏和获取键盘输入的方法。
阅读全文