c语言贪吃蛇最简单代码50行
时间: 2023-09-02 12:02:09 浏览: 308
C语言贪吃蛇最简单的代码可以在50行以内实现。以下是一个简单的示例:
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
int score = 0;
enum direction {
STOP = 0,
UP,
DOWN,
LEFT,
RIGHT
};
struct point {
int x;
int y;
};
struct point head, fruit;
enum direction dir;
bool gameOver;
void Draw() {
system("cls");
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (j == 0)
printf("#");
if (i == head.y && j == head.x)
printf("O");
else if (i == fruit.y && j == fruit.x)
printf("@");
else
printf(" ");
if (j == WIDTH - 1)
printf("#");
}
printf("\n");
}
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
printf("Score: %d\n", score);
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'x':
gameOver = true;
break;
}
}
}
void Logic() {
struct point prev = head;
switch (dir) {
case UP:
head.y--;
break;
case DOWN:
head.y++;
break;
case LEFT:
head.x--;
break;
case RIGHT:
head.x++;
break;
}
if (head.x == fruit.x && head.y == fruit.y) {
score++;
fruit.x = rand() % WIDTH;
fruit.y = rand() % HEIGHT;
}
if (head.x < 0 || head.y < 0 || head.x >= WIDTH || head.y >= HEIGHT)
gameOver = true;
// Add additional collision detection logic here if needed
}
int main() {
head.x = WIDTH / 2;
head.y = HEIGHT / 2;
fruit.x = rand() % WIDTH;
fruit.y = rand() % HEIGHT;
gameOver = false;
dir = STOP;
while (!gameOver) {
Draw();
Input();
Logic();
Sleep(10);
}
return 0;
}
```
以上代码使用了Windows.h头文件中的Sleep函数来控制游戏的速度。在绘制方面使用了简单的ASCII字符来表示蛇和食物,同时使用了conio.h头文件中的_kbhit函数和_getch函数来读取用户输入。通过不断更新蛇的位置,检测碰撞和得分,以及控制游戏的运行,实现了一个简单的贪吃蛇游戏。此代码仅为示例代码,可能还需要根据实际需求进行进一步修改和完善。
阅读全文