C语言贪吃蛇
时间: 2023-06-22 15:30:16 浏览: 194
以下是一个简单的C语言贪吃蛇游戏程序,使用了windows.h库和conio.h库:
```
#include <stdio.h>
#include <windows.h>
#include <conio.h>
#define MAP_WIDTH 40
#define MAP_HEIGHT 20
int map[MAP_HEIGHT][MAP_WIDTH] = { 0 };
int snake[100][2] = { 0 };
int length = 3;
int direction = 3;
int score = 0;
void gotoxy(int x, int y) {
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void initMap() {
int i, j;
for (i = 0; i < MAP_HEIGHT; i++) {
for (j = 0; j < MAP_WIDTH; j++) {
if (i == 0 || i == MAP_HEIGHT - 1 || j == 0 || j == MAP_WIDTH - 1) {
map[i][j] = 1;
}
}
}
}
void showMap() {
int i, j;
for (i = 0; i < MAP_HEIGHT; i++) {
for (j = 0; j < MAP_WIDTH; j++) {
gotoxy(j, i);
if (map[i][j] == 0) {
printf(" ");
}
else if (map[i][j] == 1) {
printf("#");
}
else if (map[i][j] == 2) {
printf("@");
}
else if (map[i][j] == 3) {
printf("*");
}
}
}
}
void initSnake() {
int i;
for (i = 0; i < length; i++) {
snake[i][0] = MAP_WIDTH / 2 + i;
snake[i][1] = MAP_HEIGHT / 2;
map[snake[i][1]][snake[i][0]] = 3;
}
}
void showSnake() {
int i;
for (i = 0; i < length; i++) {
gotoxy(snake[i][0], snake[i][1]);
printf("*");
}
}
void createFood() {
int x, y;
do {
x = rand() % (MAP_WIDTH - 2) + 1;
y = rand() % (MAP_HEIGHT - 2) + 1;
} while (map[y][x] != 0);
map[y][x] = 2;
}
void updateSnake() {
int i, tail_x, tail_y;
tail_x = snake[length - 1][0];
tail_y = snake[length - 1][1];
for (i = length - 1; i > 0; i--) {
snake[i][0] = snake[i - 1][0];
snake[i][1] = snake[i - 1][1];
}
if (direction == 0) {
snake[0][1]--;
}
else if (direction == 1) {
snake[0][0]++;
}
else if (direction == 2) {
snake[0][1]++;
}
else if (direction == 3) {
snake[0][0]--;
}
if (map[snake[0][1]][snake[0][0]] == 1 || map[snake[0][1]][snake[0][0]] == 3) {
gotoxy(MAP_WIDTH / 2 - 4, MAP_HEIGHT / 2);
printf("Game Over!");
getch();
exit(0);
}
if (map[snake[0][1]][snake[0][0]] == 2) {
length++;
score += 10;
createFood();
}
map[tail_y][tail_x] = 0;
map[snake[0][1]][snake[0][0]] = 3;
}
void showScore() {
gotoxy(MAP_WIDTH + 5, 5);
printf("Score: %d", score);
}
int main() {
initMap();
initSnake();
createFood();
while (1) {
showMap();
showSnake();
showScore();
Sleep(100);
updateSnake();
if (_kbhit()) {
int ch = _getch();
if (ch == 'w' && direction != 2) {
direction = 0;
}
else if (ch == 'd' && direction != 3) {
direction = 1;
}
else if (ch == 's' && direction != 0) {
direction = 2;
}
else if (ch == 'a' && direction != 1) {
direction = 3;
}
}
}
return 0;
}
```
该程序使用二维数组表示地图,使用二维数组表示蛇,通过调用控制台API函数来实现显示,并使用conio.h库来实现键盘输入。程序运行后,使用wasd来控制蛇的移动,吃到食物后蛇的长度会增加,分数也会增加。当蛇撞到墙或自己时,游戏结束。
阅读全文