用C语言写一个控制台的贪吃蛇游戏
时间: 2023-05-29 10:01:36 浏览: 38
由于文字排版限制,无法在答案中直接插入代码,请根据以下代码进行编写。
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#define MAP_WIDTH 20
#define MAP_HEIGHT 20
#define SNAKE_INIT_LENGTH 3
int map[MAP_WIDTH][MAP_HEIGHT];
int snake[SNAKE_INIT_LENGTH][2];
int snake_length = SNAKE_INIT_LENGTH;
int food[2];
int direction = 0;
int score = 0;
void init_map() {
int i, j;
for (i = 0; i < MAP_WIDTH; i++) {
for (j = 0; j < MAP_HEIGHT; j++) {
map[i][j] = 0;
}
}
}
void init_snake() {
int i;
for (i = 0; i < SNAKE_INIT_LENGTH; i++) {
snake[i][0] = MAP_WIDTH / 2 + i;
snake[i][1] = MAP_HEIGHT / 2;
map[snake[i][0]][snake[i][1]] = 1;
}
}
void init_food() {
srand((unsigned int)time(NULL));
food[0] = rand() % MAP_WIDTH;
food[1] = rand() % MAP_HEIGHT;
while (map[food[0]][food[1]] == 1) {
food[0] = rand() % MAP_WIDTH;
food[1] = rand() % MAP_HEIGHT;
}
map[food[0]][food[1]] = 2;
}
void print_map() {
int i, j;
system("cls");
printf("Score: %d\n", score);
for (i = 0; i < MAP_HEIGHT; i++) {
for (j = 0; j < MAP_WIDTH; j++) {
if (map[j][i] == 0) {
printf(" ");
}
else if (map[j][i] == 1) {
printf("O");
}
else if (map[j][i] == 2) {
printf("*");
}
if (j == MAP_WIDTH - 1) {
printf("\n");
}
}
}
}
void update_snake() {
int i, j;
int next_head[2];
switch (direction) {
case 0:
next_head[0] = snake[0][0] - 1;
next_head[1] = snake[0][1];
break;
case 1:
next_head[0] = snake[0][0] + 1;
next_head[1] = snake[0][1];
break;
case 2:
next_head[0] = snake[0][0];
next_head[1] = snake[0][1] - 1;
break;
case 3:
next_head[0] = snake[0][0];
next_head[1] = snake[0][1] + 1;
break;
}
if (next_head[0] == food[0] && next_head[1] == food[1]) { // 吃到食物
map[snake[snake_length - 1][0]][snake[snake_length - 1][1]] = 0;
snake_length++;
snake[snake_length - 1][0] = snake[snake_length - 2][0];
snake[snake_length - 1][1] = snake[snake_length - 2][1];
score += 10;
init_food();
}
else { // 没有吃到食物
map[snake[snake_length - 1][0]][snake[snake_length - 1][1]] = 0;
}
for (i = snake_length - 1; i > 0; i--) {
snake[i][0] = snake[i - 1][0];
snake[i][1] = snake[i - 1][1];
}
snake[0][0] = next_head[0];
snake[0][1] = next_head[1];
if (snake[0][0] < 0 || snake[0][0] >= MAP_WIDTH
|| snake[0][1] < 0 || snake[0][1] >= MAP_HEIGHT
|| map[snake[0][0]][snake[0][1]] == 1) { // 判断游戏结束
printf("Game Over!\n");
exit(0);
}
for (i = 0; i < snake_length; i++) { // 更新蛇在地图上的位置
map[snake[i][0]][snake[i][1]] = 1;
}
}
void update_direction() {
int ch;
if (_kbhit()) {
ch = _getch();
if (ch == 224) {
ch = _getch();
switch (ch) {
case 75: // 左
if (direction != 1) {
direction = 0;
}
break;
case 77: // 右
if (direction != 0) {
direction = 1;
}
break;
case 72: // 上
if (direction != 3) {
direction = 2;
}
break;
case 80: // 下
if (direction != 2) {
direction = 3;
}
break;
}
}
}
}
int main() {
init_map();
init_snake();
init_food();
while (1) {
print_map();
update_snake();
update_direction();
Sleep(100); // 让循环运行速度慢一点,不然蛇动起来很快闪眼睛
}
return 0;
}