devc++编写c语言贪吃蛇
时间: 2023-10-24 21:07:33 浏览: 525
devc++贪吃蛇 源码
5星 · 资源好评率100%
在DevC++中编写C语言贪吃蛇的示例代码如下:
```c
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
int score;
int gameover;
int x, y, fruitX, fruitY, flag;
int tailX[100], tailY[100];
int nTail;
void Setup()
{
gameover = 0;
x = WIDTH / 2;
y = HEIGHT / 2;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
score = 0;
}
void Draw()
{
int i, j, k;
system("cls");
for (i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
for (i = 0; i < HEIGHT; i++)
{
for (j = 0; j < WIDTH; j++)
{
if (j == 0)
printf("#");
if (i == y && j == x)
printf("O");
else if (i == fruitY && j == fruitX)
printf("F");
else
{
int printTail = 0;
for (k = 0; k < nTail; k++)
{
if (tailX[k] == j && tailY[k] == i)
{
printf("o");
printTail = 1;
}
}
if (!printTail)
printf(" ");
}
if (j == WIDTH - 1)
printf("#");
}
printf("\n");
}
for (i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
printf("Score: %d\n", score);
printf("Press X to quit the game");
}
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 i;
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (i = 1; i < nTail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (flag)
{
case 1:
x--;
break;
case 2:
x++;
break;
case 3:
y--;
break;
case 4:
y++;
break;
}
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)
gameover = 1;
for (i = 0; i < nTail; i++)
{
if (tailX[i] == x && tailY[i] == y)
gameover = 1;
}
if (x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
nTail++;
}
}
int main()
{
char c;
do
{
Setup();
while (!gameover)
{
Draw();
Input();
Logic();
Sleep(10);
}
printf("Game over!\n");
printf("Do you want to play again? (Y/N) ");
c = getchar();
} while (c == 'y' || c == 'Y');
return 0;
}
```
阅读全文