一、數據結構和演算法
C語言貪吃蛇主要運用了以下數據結構和演算法:
1. 鏈表
typedef struct body { int x; int y; struct body *next; } body;
貪吃蛇身體使用鏈表來儲存,每個節點包括x,y坐標和下一個節點的指針。新的節點插入在頭部,舊的節點從尾部刪除。
2. 隨機數
#include srand(time(NULL)); int rand_num = rand() % 4;
每次移動時,貪吃蛇會隨機生成一個隨機數,決定下一步往上、下、左、右哪個方向移動。
3. 碰撞檢測
for (body *ptr = snake->next; ptr != NULL; ptr = ptr->next) { if (snake->x == ptr->x && snake->y == ptr->y) { return true; } }
貪吃蛇在移動時需要檢測是否與自己相撞,通過遍歷鏈表來檢查貪吃蛇的頭部與身體的坐標是否重複。
二、遊戲邏輯實現
貪吃蛇的整個遊戲邏輯包括遊戲的啟動、渲染、輸入接收和移動。
1. 啟動
遊戲啟動時需要生成初始的貪吃蛇身體節點和食物坐標,以及初始化遊戲地圖。
body *snake = malloc(sizeof(body)); // 初始化蛇的頭部節點 snake->x = 10; snake->y = 10; snake->next = NULL; int food_x = rand() % map_width; int food_y = rand() % map_height;
2. 渲染
遊戲需要在終端上進行渲染,包括遊戲地圖、貪吃蛇身體和食物。
printf("Score: %d\n", score); for (int i = 0; i < map_height; i++) { for (int j = 0; j
3. 輸入接收
遊戲需要接收玩家的鍵盤輸入,來控制貪吃蛇的方向。
char input = getch(); switch (input) { case 'w': if (direction != 2) direction = 0; break; case 's': if (direction != 0) direction = 2; break; case 'a': if (direction != 1) direction = 3; break; case 'd': if (direction != 3) direction = 1; break; }
4. 移動
貪吃蛇每隔一段時間就會向前移動一格,玩家需要控制方向來移動貪吃蛇。
int next_x = snake->x; int next_y = snake->y; switch (direction) { case 0: // 上 next_y--; break; case 1: // 右 next_x++; break; case 2: // 下 next_y++; break; case 3: // 左 next_x--; break; }
三、代碼示例
以下是完整的C語言貪吃蛇代碼示例:
#include #include #include #include #include #define map_width 20 #define map_height 20 typedef struct body { int x; int y; struct body *next; } body; int score = 0; int direction = 1; body *snake; void generate_food(int *food_x, int *food_y) { do { *food_x = rand() % map_width; *food_y = rand() % map_height; } while (*food_x == snake->x && *food_y == snake->y); } bool check_collision(int x, int y) { if (x = map_width || y = map_height) { // 超出邊界 return true; } for (body *ptr = snake->next; ptr != NULL; ptr = ptr->next) { // 撞到自己 if (x == ptr->x && y == ptr->y) { return true; } } return false; } void game_over() { printf("\nGame over!\nYour Score: %d\n", score); exit(0); } void game_loop() { int food_x, food_y; generate_food(&food_x, &food_y); while (true) { system("cls"); printf("Score: %d\n", score); for (int i = 0; i < map_height; i++) { for (int j = 0; j
原創文章,作者:PSJMI,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/373241.html