用c++写一个贪吃蛇代码
时间: 2023-03-30 07:03:57 浏览: 136
好的,我可以回答这个问题。以下是一个简单的贪吃蛇代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define ROW 20
#define COL 30
int snake[ROW*COL][2];
int food[2];
int len = 3;
int score = ;
void init();
void draw();
void update();
void generate_food();
int main()
{
init();
while (1)
{
draw();
update();
if (snake[][] < || snake[][] >= ROW || snake[][1] < || snake[][1] >= COL)
{
printf("Game over! Your score is %d.\n", score);
break;
}
for (int i = 1; i < len; i++)
{
if (snake[][] == snake[i][] && snake[][1] == snake[i][1])
{
printf("Game over! Your score is %d.\n", score);
return ;
}
}
if (snake[][] == food[] && snake[][1] == food[1])
{
len++;
score++;
generate_food();
}
Sleep(100);
}
return ;
}
void init()
{
srand((unsigned)time(NULL));
snake[][] = rand() % ROW;
snake[][1] = rand() % COL;
for (int i = 1; i < len; i++)
{
snake[i][] = snake[i - 1][] + 1;
snake[i][1] = snake[i - 1][1];
}
generate_food();
}
void draw()
{
system("cls");
for (int i = ; i < ROW; i++)
{
for (int j = ; j < COL; j++)
{
if (i == snake[][] && j == snake[][1])
{
printf("O");
}
else if (i == food[] && j == food[1])
{
printf("*");
}
else
{
int flag = ;
for (int k = 1; k < len; k++)
{
if (i == snake[k][] && j == snake[k][1])
{
printf("o");
flag = 1;
break;
}
}
if (!flag)
{
printf(" ");
}
}
}
printf("\n");
}
printf("Score: %d\n", score);
}
void update()
{
if (_kbhit())
{
char c = _getch();
switch (c)
{
case 'w':
for (int i = len - 1; i > ; i--)
{
snake[i][] = snake[i - 1][];
snake[i][1] = snake[i - 1][1];
}
snake[][]--;
break;
case 's':
for (int i = len - 1; i > ; i--)
{
snake[i][] = snake[i - 1][];
snake[i][1] = snake[i - 1][1];
}
snake[][]++;
break;
case 'a':
for (int i = len - 1; i > ; i--)
{
snake[i][] = snake[i - 1][];
snake[i][1] = snake[i - 1][1];
}
snake[][1]--;
break;
case 'd':
for (int i = len - 1; i > ; i--)
{
snake[i][] = snake[i - 1][];
snake[i][1] = snake[i - 1][1];
}
snake[][1]++;
break;
default:
break;
}
}
else
{
for (int i = len - 1; i > ; i--)
{
snake[i][] = snake[i - 1][];
snake[i][1] = snake[i - 1][1];
}
snake[][1]++;
}
}
void generate_food()
{
int flag = ;
while (!flag)
{
food[] = rand() % ROW;
food[1] = rand() % COL;
flag = 1;
for (int i = ; i < len; i++)
{
if (food[] == snake[i][] && food[1] == snake[i][1])
{
flag = ;
break;
}
}
}
}
```
这个代码使用了 Windows 系统的 conio.h 库,所以在 Linux 或 Mac 上可能无法编译运行。如果需要在 Linux 或 Mac 上运行,需要使用相应的替代库来实现键盘输入和清屏等功能。
阅读全文