用c语言写贪吃蛇游戏
时间: 2023-08-18 07:07:54 浏览: 88
用C语言写的贪吃蛇游戏
以下是一个简单的贪吃蛇游戏的C语言实现,包括基本的游戏逻辑和图形输出:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
const int Width = 20;
const int Height = 20;
int Snake[100][2], Length = 1, FoodX, FoodY, Score = 0;
int Direction = 0; //0:up 1:right 2:down 3:left
void InitSnake() {
Snake[0][0] = Width / 2;
Snake[0][1] = Height / 2;
FoodX = rand() % Width;
FoodY = rand() % Height;
}
void PrintMap() {
system("cls");
for (int i = 0; i <= Width + 1; i++)
printf("#");
printf("\n");
for (int i = 0; i < Height; i++) {
printf("#");
for (int j = 0; j < Width; j++)
if (i == Snake[0][1] && j == Snake[0][0])
printf("O");
else if (i == FoodY && j == FoodX)
printf("F");
else {
int k;
for (k = 1; k < Length; k++)
if (i == Snake[k][1] && j == Snake[k][0]) {
printf("o");
break;
}
if (k == Length)
printf(" ");
}
printf("#\n");
}
for (int i = 0; i <= Width + 1; i++)
printf("#");
printf("\n");
printf("Score: %d\n", Score);
}
void Move() {
switch (Direction) {
case 0:
for (int i = Length - 1; i > 0; i--) {
Snake[i][0] = Snake[i - 1][0];
Snake[i][1] = Snake[i - 1][1];
}
Snake[0][1]--;
break;
case 1:
for (int i = Length - 1; i > 0; i--) {
Snake[i][0] = Snake[i - 1][0];
Snake[i][1] = Snake[i - 1][1];
}
Snake[0][0]++;
break;
case 2:
for (int i = Length - 1; i > 0; i--) {
Snake[i][0] = Snake[i - 1][0];
Snake[i][1] = Snake[i - 1][1];
}
Snake[0][1]++;
break;
case 3:
for (int i = Length - 1; i > 0; i--) {
Snake[i][0] = Snake[i - 1][0];
Snake[i][1] = Snake[i - 1][1];
}
Snake[0][0]--;
break;
}
}
int main() {
srand(time(NULL));
InitSnake();
while (1) {
PrintMap();
if (kbhit()) {
char c = getch();
if (c == 'w' || c == 'W')
Direction = 0;
else if (c == 'd' || c == 'D')
Direction = 1;
else if (c == 's' || c == 'S')
Direction = 2;
else if (c == 'a' || c == 'A')
Direction = 3;
}
Move();
if (Snake[0][0] == FoodX && Snake[0][1] == FoodY) {
Length++;
Score += 10;
FoodX = rand() % Width;
FoodY = rand() % Height;
}
if (Snake[0][0] < 0 || Snake[0][0] >= Width || Snake[0][1] < 0 || Snake[0][1] >= Height) {
printf("Game Over!\n");
break;
}
for (int i = 1; i < Length; i++)
if (Snake[0][0] == Snake[i][0] && Snake[0][1] == Snake[i][1]) {
printf("Game Over!\n");
return 0;
}
Sleep(200);
}
return 0;
}
```
这个实现使用了Windows.h库的Sleep函数来控制游戏速度,使用了conio.h库的kbhit和getch函数来获取键盘输入,以及使用了随机数生成函数 rand。游戏界面使用字符画来展示,O代表蛇头,o代表蛇身,F代表食物。
阅读全文