c语言编程贪吃蛇代码
时间: 2023-12-22 16:28:45 浏览: 147
以下是一个简单的C语言编写的贪吃蛇游戏代码示例:
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
int width = 20, height = 20;
int gameover, score;
int x, y, fruitX, fruitY, flag;
int tailX[100], tailY[100];
int countTail = 0;
void setup()
{
gameover = 0;
x = width / 2;
y = height / 2;
label1:
fruitX = rand() % width;
if (fruitX == 0)
goto label1;
label2:
fruitY = rand() % height;
if (fruitY == 0)
goto label2;
score = 0;
}
void draw()
{
system("cls");
int i, j;
for (i = 0; i < width; i++)
{
for (j = 0; j < height; j++)
{
if (i == 0 || i == width - 1 || j == 0 || j == height - 1)
{
printf("#");
}
else
{
if (i == x && j == y)
{
printf("O");
}
else if (i == fruitX && j == fruitY)
{
printf("F");
}
else
{
int printTail = 0;
for (int k = 0; k < countTail; k++)
{
if (i == tailX[k] && j == tailY[k])
{
printf("o");
printTail = 1;
}
}
if (printTail == 0)
{
printf(" ");
}
}
}
}
printf("\n");
}
printf("Score: %d", score);
}
void input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
flag = 1;
break;
case 'd':
flag = 2;
break;
case 'w':
flag = 3;
break;
case 's':
flag = 4;
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 < countTail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (flag)
{
case 1:
y--;
break;
case 2:
y++;
break;
case 3:
x--;
break;
case 4:
x++;
break;
default:
break;
}
if (x < 0 || x >= width || y < 0 || y >= height)
{
gameover = 1;
}
for (int i = 0; i < countTail; i++)
{
if (tailX[i] == x && tailY[i] == y)
{
gameover = 1;
}
}
if (x == fruitX && y == fruitY)
{
label3:
fruitX = rand() % width;
if (fruitX == 0)
goto label3;
label4:
fruitY = rand() % height;
if (fruitY == 0)
goto label4;
score += 10;
countTail++;
}
}
int main()
{
int m, n;
char c;
printf("Enter the width and height of the game screen: ");
scanf("%d%d", &m, &n);
width = m;
height = n;
setup();
while (!gameover)
{
draw();
input();
logic();
Sleep(10); // 控制游戏速度
}
printf("\nGame Over!\n");
printf("Your Score: %d\n", score);
return 0;
}
```
阅读全文