贪吃蛇c语言代码600行
时间: 2023-10-12 22:05:14 浏览: 40
以下是一个基于C语言的简单贪吃蛇游戏代码,共计约600行。
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#define WIDTH 40
#define HEIGHT 20
#define SNAKE_LEN_MAX 100
int map[HEIGHT][WIDTH];
int snake[SNAKE_LEN_MAX][2];
int snake_len;
int food_x, food_y;
int score;
int gameover;
void gotoxy(int x, int y) {
COORD pos = {x, y};
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOut, pos);
}
void init() {
int i, j;
// 初始化地图
for (i = 0; i < HEIGHT; i++) {
for (j = 0; j < WIDTH; j++) {
if (i == 0 || j == 0 || i == HEIGHT-1 || j == WIDTH-1) {
map[i][j] = -1; // 围墙
} else {
map[i][j] = 0;
}
}
}
// 初始化蛇
snake_len = 3;
snake[0][0] = HEIGHT/2; snake[0][1] = WIDTH/2;
snake[1][0] = snake[0][0]+1; snake[1][1] = snake[0][1];
snake[2][0] = snake[1][0]+1; snake[2][1] = snake[1][1];
// 初始化食物
srand(time(NULL));
food_x = rand() % (WIDTH-2) + 1;
food_y = rand() % (HEIGHT-2) + 1;
// 初始化分数和游戏结束标志
score = 0;
gameover = 0;
}
void draw() {
int i, j;
// 绘制地图
for (i = 0; i < HEIGHT; i++) {
for (j = 0; j < WIDTH; j++) {
if (map[i][j] == -1) {
putchar('#');
} else if (map[i][j] == 0) {
putchar(' ');
} else if (map[i][j] == 1) {
putchar('*');
} else if (map[i][j] == 2) {
putchar('o');
}
}
putchar('\n');
}
// 显示分数
gotoxy(WIDTH+5, 5);
printf("Score: %d\n", score);
}
void update() {
int i;
// 移动蛇身
for (i = snake_len-1; i > 0; i--) {
snake[i][0] = snake[i-1][0];
snake[i][1] = snake[i-1][1];
}
// 移动蛇头
if (_kbhit()) {
char ch = _getch();
if (ch == 'w' || ch == 'W') {
snake[0][0]--;
} else if (ch == 's' || ch == 'S') {
snake[0][0]++;
} else if (ch == 'a' || ch == 'A') {
snake[0][1]--;
} else if (ch == 'd' || ch == 'D') {
snake[0][1]++;
}
} else {
snake[0][1]++;
}
// 判断是否撞墙或撞到自己
if (map[snake[0][0]][snake[0][1]] == -1 || map[snake[0][0]][snake[0][1]] == 1) {
gameover = 1;
return;
}
// 判断是否吃到食物
if (snake[0][0] == food_y && snake[0][1] == food_x) {
snake_len++;
score += 10;
// 生成新的食物
do {
food_x = rand() % (WIDTH-2) + 1;
food_y = rand() % (HEIGHT-2) + 1;
} while (map[food_y][food_x] != 0);
}
// 更新地图
for (i = 0; i < HEIGHT; i++) {
for (j = 0; j < WIDTH; j++) {
map[i][j] = 0;
}
}
for (i = 0; i < snake_len; i++) {
map[snake[i][0]][snake[i][1]] = 1;
}
map[food_y][food_x] = 2;
}
int main() {
init();
while (!gameover) {
draw();
update();
Sleep(100);
system("cls");
}
printf("Game Over!\n");
printf("Your Score: %d\n", score);
system("pause");
return 0;
}
```