cinclude include nclude iclude eine WIDTH 20dfne HEIGHT 20eie MAX_SNAKE_SIZE 100// 定義方向dfn UP 1#eieDOWN 2#dfn EFT 3#deieRGHT 4// 游戲區(qū)域int map[HEIGHT][WIDTH];// 蛇的結(jié)構(gòu)體typedef struct {int x[MAX_SNAKE_SIZE];int y[MAX_SNAKE_SIZE];int length;} Snake;// 蛇頭位置int headX, headY, foodX, foodY, score;int direction, gameOver;// 初始化游戲void Setup() {headX = WIDTH / 2;headY = HEIGHT / 2;foodX = rand() % WIDTH;foodY = rand() % HEIGHT;score = 0;direction = RIGHT;gameOver = 0;}// 繪制地圖void Draw() {system("cls");for (int i = 0; i < HEIGHT; i++) {for (int j = 0; j < WIDTH; j++) {if (i == 0 || i == HEIGHT - 1 || j == 0 || j == WIDTH - 1)printf("#"); else if (i == foodY j == foodX)printf("");else if (i == headY j == headX)printf("O");elseprintf(" ");}printf("\n");}printf("Score: %d\n", score);}// 獲取玩家輸入void Input() {if (_kbhit()) {char current = _getch();if (current == 'w' direction != DOWN)direction = UP;if (current == 's' direction != UP)direction = DOWN;if (current == 'a' direction != RIGHT)direction = LEFT;if (current == 'd' direction != LEFT)direction = RIGHT;}}// 移動蛇void Logic() {int prevX = headX, prevY = headY;int prev2X, prev2Y;int i;switch (direction) {case UP:headY--;break;case DOWN:headY++;break;case LEFT:headX--;break;case RIGHT:headX++;break;}if (headX >= WIDTH || headX < 0 || headY >= HEIGHT || headY < 0)gameOver = 1;if (headX == foodX headY == foodY) {foodX = rand() % WIDTH;foodY = rand() % HEIGHT;score += 10;}// 更新蛇的位置for (i = 0; i < MAX_SNAKE_SIZE; i++) {prev2X = headX;prev2Y = headY;headX = prevX;headY = prevY;}}int main() {Setup();while (!gameOver) {Draw();Input();Logic();Sleep(100);}return 0;}
轉(zhuǎn)載請注明來自夕逆IT,本文標(biāo)題:《貪吃蛇程序代碼c語言》

每一天,每一秒,你所做的決定都會改變你的人生!
還沒有評論,來說兩句吧...