#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <windows.h> // 游戲區(qū)域的大小 #define WIDTH 60 #define HEIGHT 20 // 蛇的移動(dòng)方向 typedef enum { UP, DOWN, LEFT, RIGHT } Direction; // 食物的結(jié)構(gòu)體 typedef struct { int x; int y; } Food; // 蛇的結(jié)構(gòu)體 typedef struct { int x[WIDTH * HEIGHT]; int y[WIDTH * HEIGHT]; int length; Direction dir; } Snake; // 初始化蛇 void initSnake(Snake *snake) { snake->x[0] = WIDTH / 2; snake->y[0] = HEIGHT / 2; snake->length = 1; snake->dir = RIGHT; } // 初始化食物 void initFood(Food *food) { food->x = rand() % WIDTH; food->y = rand() % HEIGHT; } // 判斷蛇是否吃到食物 int isEatFood(Snake snake, Food food) { if (snake.x[0] == food.x && snake.y[0] == food.y) { return 1; } return 0; } // 判斷蛇是否撞到自己或邊界 int isGameOver(Snake snake) { // 撞到邊界 if (snake.x[0] < 0 || snake.x[0] >= WIDTH || snake.y[0] < 0 || snake.y[0] >= HEIGHT) { return 1; } // 撞到自己 for (int i = 1; i < snake.length; i++) { if (snake.x[0] == snake.x[i] && snake.y[0] == snake.y[i]) { return 1; } } return 0; } // 移動(dòng)蛇 void moveSnake(Snake *snake) { int prevX = snake->x[0]; int prevY = snake->y[0]; switch (snake->dir) { case UP: snake->y[0]--; break; case DOWN: snake->y[0]++; break; case LEFT: snake->x[0]--; break; case RIGHT: snake->x[0]++; break; } for (int i = snake->length - 1; i > 0; i--) { snake->x[i] = snake->x[i - 1]; snake->y[i] = snake->y[i - 1]; } snake->x[1] = prevX; snake->y[1] = prevY; } // 繪制游戲界面 void draw(Snake snake, Food food) { system("cls"); for (int i = 0; i < WIDTH + 2; i++) { printf("#"); } printf("\n"); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { if (j == 0) { printf("#"); } int isSnake = 0; for (int k = 0; k < snake.length; k++) { if (snake.x[k] == j && snake.y[k] == i) { printf("*"); isSnake = 1; break; } } if (!isSnake && food.x == j && food.y == i) { printf("@"); } else if (!isSnake) { printf(" "); } if (j == WIDTH - 1) { printf("#"); } } printf("\n"); } for (int i = 0; i < WIDTH + 2; i++) { printf("#"); } printf("\n"); } int main() { Snake snake; Food food; initSnake(&snake); initFood(&food); while (1) { draw(snake, food); if (isEatFood(snake, food)) { snake.length++; initFood(&food); } if (isGameOver(snake)) { printf("Game Over!\n"); break; } if (_kbhit()) { char key = _getch(); switch (key) { case 'w': if (snake.dir!= DOWN) { snake.dir = UP; } break; case 's': if (snake.dir!= UP) { snake.dir = DOWN; } break; case 'a': if (snake.dir!= RIGHT) { snake.dir = LEFT; } break; case 'd': if (snake.dir!= LEFT) { snake.dir = RIGHT; } break; } } moveSnake(&snake); Sleep(100); } return 0; } |
|