写段贪吃蛇的c语言代码
时间: 2023-10-14 10:06:37 浏览: 96
贪吃蛇c语言代码
以下是一个简单的贪吃蛇游戏的C语言代码示例:
```
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_X 20
#define MAX_Y 20
int x, y, foodX, foodY, score;
int gameOver;
int tailX[100], tailY[100];
int nTail;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
enum eDirection dir;
void Setup() {
gameOver = 0;
dir = STOP;
x = MAX_X / 2;
y = MAX_Y / 2;
foodX = rand() % MAX_X;
foodY = rand() % MAX_Y;
score = 0;
}
void Draw() {
system("cls");
for (int i = 0; i < MAX_X + 2; i++)
printf("#");
printf("\n");
for (int i = 0; i < MAX_Y; i++) {
for (int j = 0; j < MAX_X; j++) {
if (j == 0)
printf("#");
if (i == y && j == x)
printf("O");
else if (i == foodY && j == foodX)
printf("F");
else {
int printTail = 0;
for (int k = 0; k < nTail; k++) {
if (tailX[k] == j && tailY[k] == i) {
printf("o");
printTail = 1;
}
}
if (!printTail)
printf(" ");
}
if (j == MAX_X - 1)
printf("#");
}
printf("\n");
}
for (int i = 0; i < MAX_X + 2; i++)
printf("#");
printf("\n");
printf("Score: %d\n", score);
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameOver = 1;
break;
}
}
}
void Logic() {
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < nTail; i++) {
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
if (x > MAX_X || x < 0 || y > MAX_Y || y < 0)
gameOver = 1;
for (int i = 0; i < nTail; i++) {
if (tailX[i] == x && tailY[i] == y)
gameOver = 1;
}
if (x == foodX && y == foodY) {
score += 10;
foodX = rand() % MAX_X;
foodY = rand() % MAX_Y;
nTail++;
}
}
int main() {
srand(time(NULL));
Setup();
while (!gameOver) {
Draw();
Input();
Logic();
_sleep(100);
}
return 0;
}
```
代码中使用了 `conio.h` 库中的 `_kbhit()` 和 `_getch()` 函数来实现键盘输入的检测和读取,可以使用其他库或者 API 来完成相同的功能。此外,代码中使用了数组来保存蛇的身体坐标,以及一个枚举类型来表示蛇的运动方向。
阅读全文