以下是一个用C语言编写的简单贪吃蛇游戏:

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

#define WIDTH 20 #define HEIGHT 20 #define SIZE (WIDTH*HEIGHT)

int snake[SIZE][2]; int length; int fruit[2]; int direction; int gameover;

void gotoxy(int x, int y) { COORD coord; coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }

void init() { length = 1; snake[0][0] = WIDTH / 2; snake[0][1] = HEIGHT / 2; fruit[0] = rand() % WIDTH; fruit[1] = rand() % HEIGHT; direction = ' '; gameover = 0; }

void draw() { system("cls"); for (int i = 0; i < WIDTH + 2; i++) { printf("#"); } printf("\n");

for (int y = 0; y < HEIGHT; y++) {
    for (int x = 0; x < WIDTH; x++) {
        if (x == 0) {
            printf("#");
        }

        if (x == fruit[0] && y == fruit[1]) {
            printf("F");
        } else {
            int isBodyPart = 0;
            for (int i = 0; i < length; i++) {
                if (snake[i][0] == x && snake[i][1] == y) {
                    printf("O");
                    isBodyPart = 1;
                    break;
                }
            }
            if (!isBodyPart) {
                printf(" ");
            }
        }

        if (x == WIDTH - 1) {
            printf("#");
        }
    }
    printf("\n");
}

for (int i = 0; i < WIDTH + 2; i++) {
    printf("#");
}
printf("\n");

}

void input() { if (_kbhit()) { switch (_getch()) { case 'a': direction = 'a'; break; case 'd': direction = 'd'; break; case 'w': direction = 'w'; break; case 's': direction = 's'; break; case 'x': gameover = 1; break; } } }

void logic() { int prevX = snake[0][0]; int prevY = snake[0][1]; int prev2X, prev2Y; snake[0][0] = snake[0][0] - (direction == 'a') + (direction == 'd'); snake[0][1] = snake[0][1] - (direction == 'w') + (direction == 's'); for (int i = 1; i < length; i++) { prev2X = snake[i][0]; prev2Y = snake[i][1]; snake[i][0] = prevX; snake[i][1] = prevY; prevX = prev2X; prevY = prev2Y; }

if (snake[0][0] == fruit[0] && snake[0][1] == fruit[1]) {
    length++;
    fruit[0] = rand() % WIDTH;
    fruit[1] = rand() % HEIGHT;
}

if (snake[0][0] < 0 || snake[0][0] >= WIDTH || snake[0][1] < 0 || snake[0][1] >= HEIGHT) {
    gameover = 1;
}

for (int i = 1; i < length; i++) {
    if (snake[i][0] == snake[0][0] && snake[i][1] == snake[0][1]) {
        gameover = 1;
    }
}

}

int main() { srand(time(NULL));

init();
while (!gameover) {
    draw();
    input();
    logic();
    Sleep(100); // 控制游戏速度
}

printf("Game Over!\n");
return 0;
用C语言编写贪吃蛇游戏

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

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