用C语言实现贪吃蛇小游戏,内附代码。
```cint map[MAP_HEIGHT][MAP_WIDTH];int snake_x, snake_y, food_x, food_y, score;void init_map() {int i, j;for (i = 0; i < MAP_HEIGHT; i++) {for (j = 0; j < MAP_WIDTH; j++) {if (i == 0 || i == MAP_HEIGHT - 1 || j == 0 || j == MAP_WIDTH - 1) {map[i][j] = -1;} else {map[i][j] = 0;}}}snake_x = MAP_WIDTH / 2;snake_y = MAP_HEIGHT / 2;map[snake_y][snake_x] = 1;food_x = rand() % (MAP_WIDTH - 2) + 1;food_y = rand() % (MAP_HEIGHT - 2) + 1;map[food_y][food_x] = 2;score = 0;}void draw_map() {int i, j;system("cls");for (i = 0; i < MAP_HEIGHT; i++) {for (j = 0; j < MAP_WIDTH; j++) {switch (map[i][j]) {case -1:printf("#");break;case 0:printf(" ");break;case 1:printf("O");break;case 2:printf("*");break;}}printf("\n");}printf("Score: %d\n", score);}void update_snake() {int dx = 0, dy = 0;if (_kbhit()) {switch (_getch()) {case 'w':case 'W':dy = -1;break;case 'a':case 'A':dx = -1;break;case 's':case 'S':dy = 1;break;case 'd':case 'D':dx = 1;break;}}int new_x = snake_x + dx;int new_y = snake_y + dy;if (map[new_y][new_x] == -1 || map[new_y][new_x] == 1) {printf("Game over!\n");exit(0);}if (map[new_y][new_x] == 2) {score++;food_x = rand() % (MAP_WIDTH - 2) + 1;food_y = rand() % (MAP_HEIGHT - 2) + 1;map[food_y][food_x] = 2;} else {int tail_x, tail_y;for (tail_y = 0; tail_y < MAP_HEIGHT; tail_y++) {for (tail_x = 0; tail_x < MAP_WIDTH; tail_x++) {if (map[tail_y][tail_x] == 1) {map[tail_y][tail_x] = 0;break;}}if (tail_x < MAP_WIDTH) {break;}}}snake_x = new_x;snake_y = new_y;map[snake_y][snake_x] = 1;}int main() {init_map();while (1) {draw_map();update_snake();Sleep(200);}return 0;}```
评论
