下面是一个简单的C语言贪吃蛇的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
int snakeX[100], snakeY[100]; // 蛇身的位置
int snakeLength; // 蛇身长度
int fruitX, fruitY; // 水果的位置
enum eDirecton { STOP = 0, LEFT, RIGHT, UP, DOWN }; // 方向枚举
enum eDirecton dir; // 当前移动方向
// 初始化游戏
void Setup()
{
dir = STOP;
snakeX[0] = WIDTH / 2;
snakeY[0] = HEIGHT / 2;
snakeLength = 1;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
}
// 画出当前游戏状态
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 == snakeY[0] && j == snakeX[0])
printf("O"); // 蛇头
else if (i == fruitY && j == fruitX)
printf("F"); // 水果
else
{
int snakeBody = 0;
for (int k = 1; k < snakeLength; k++)
{
if (snakeY[k] == i && snakeX[k] == j)
{
printf("o"); // 蛇身
snakeBody = 1;
}
}
if (!snakeBody)
printf(" ");
}
if (j == WIDTH - 1)
printf("#");
}
printf("\n");
}
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
}
// 处理输入
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':
exit(0);
break;
}
}
}
// 更新游戏状态
void Logic()
{
int prevX = snakeX[0];
int prevY = snakeY[0];
int prev2X, prev2Y;
snakeX[0] += dir == RIGHT ? 1 : dir == LEFT ? -1 : 0;
snakeY[0] += dir == DOWN ? 1 : dir == UP ? -1 : 0;
if (snakeX[0] >= WIDTH) snakeX[0] = 0; else if (snakeX[0] < 0) snakeX[0] = WIDTH - 1;
if (snakeY[0] >= HEIGHT) snakeY[0] = 0; else if (snakeY[0] < 0) snakeY[0] = HEIGHT - 1;
for (int i = 1; i < snakeLength; i++)
{
prev2X = snakeX[i];
prev2Y = snakeY[i];
snakeX[i] = prevX;
snakeY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
if (snakeX[0] == fruitX && snakeY[0] == fruitY)
{
snakeLength++;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
}
}
int main()
{
Setup();
while (1)
{
Draw();
Input();
Logic();
Sleep(10); // 控制游戏速度
}
return 0;
}
这是一个简单的贪吃蛇游戏,使用了Windows API中的conio.h和windows.h库来实现控制台界面和按键监听。游戏中使用箭头键来控制蛇的移动方向,吃到水果后蛇的长度会增加。