由于贪吃蛇游戏比较复杂,代码量较大,我在此提供一个基本的框架供参考。

#include <stdio.h> #include <stdlib.h> #include <time.h> #include <conio.h> #include <windows.h>

#define ROWS 20 #define COLS 20

typedef struct Node // 蛇身结点 { int row; int col; struct Node* next; }Node;

typedef struct Food // 食物结构体 { int row; int col; }Food;

Node* head = NULL; // 蛇头 Node* tail = NULL; // 蛇尾 Food food; // 食物

void init(); // 初始化 void draw(); // 绘制界面 void move(); // 移动 void generateFood(); // 生成食物 int isGameOver(); // 判断游戏是否结束

int main() { init(); while (!isGameOver()) { draw(); move(); Sleep(100); // 控制帧率 } printf("Game Over!\n"); system("pause"); return 0; }

void init() { srand((unsigned)time(NULL)); head = (Node*)malloc(sizeof(Node)); head->row = ROWS / 2; head->col = COLS / 2; head->next = NULL; tail = head; generateFood(); }

void draw() { system("cls"); for (int i = 0; i < ROWS + 2; i++) { for (int j = 0; j < COLS + 2; j++) { if (i == 0 || i == ROWS + 1 || j == 0 || j == COLS + 1) { printf("#"); } else if (i == food.row && j == food.col) { printf("o"); } else { Node* p = head; while (p != NULL) { if (p->row == i && p->col == j) { printf("*"); break; } p = p->next; } if (p == NULL) { printf(" "); } } } printf("\n"); } }

void move() { int direction = getch(); // 获取方向键 Node* newHead = (Node*)malloc(sizeof(Node)); newHead->next = head; switch (direction) { case 'w': // 上 newHead->row = head->row - 1; newHead->col = head->col; break; case 's': // 下 newHead->row = head->row + 1; newHead->col = head->col; break; case 'a': // 左 newHead->row = head->row; newHead->col = head->col - 1; break; case 'd': // 右 newHead->row = head->row; newHead->col = head->col + 1; break; } head = newHead; if (head->row == food.row && head->col == food.col) // 吃到食物 { generateFood(); } else { Node* p = head; while (p->next != tail) { p = p->next; } p->next = NULL; free(tail); tail = p; } }

void generateFood() { int row, col; do { row = rand() % ROWS + 1; col = rand() % COLS + 1; } while (row == head->row && col == head->col); // 食物不能在蛇头上 food.row = row; food.col = col; }

int isGameOver() { if (head->row == 0 || head->row == ROWS + 1 || head->col == 0 || head->col == COLS + 1) // 撞墙 { return 1; } Node* p = head->next; while (p != NULL) { if (head->row == p->row && head->col == p->col) // 撞到自己 { return 1; } p = p->next; } return 0; }

c语言编制一个贪吃蛇游戏

原文地址: https://www.cveoy.top/t/topic/9yE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录