写一个贪吃蛇代码c++语言
时间: 2023-03-14 17:24:01 浏览: 113
#include <stdio.h>
#include <conio.h>#define N 40
#define M 20int x[100], y[100];
int food_x, food_y;
int length;
int direction;void init()
{
int i;
x[0] = 0;
y[0] = 0;
length = 3;
for (i = 1; i < length; i++)
{
x[i] = x[i-1] - 1;
y[i] = y[i-1];
}
food_x = 20;
food_y = 10;
direction = 'd';
}void gotoxy(int x, int y)
{
printf("\033[%d;%dH", x, y);
}void draw_food()
{
gotoxy(food_x, food_y);
printf("*");
}void draw_snake()
{
int i;
gotoxy(x[0], y[0]);
printf("@");
for (i = 1; i < length; i++)
{
gotoxy(x[i], y[i]);
printf("#");
}
}void delete_tail()
{
gotoxy(x[length-1], y[length-1]);
printf(" ");
}void move()
{
int i;
delete_tail();
for (i = length-1; i > 0; i--)
{
x[i] = x[i-1];
y[i] = y[i-1];
}
if (direction == 'w')
x[0]--;
else if (direction == 's')
x[0]++;
else if (direction == 'a')
y[0]--;
else
y[0]++;
}void check_food()
{
if (x[0] == food_x && y[0] == food_y)
{
length++;
x[length-1] = x[length-2];
y[length-1] = y[length-2];
food_x = rand() % N;
food_y = rand() % M;
}
}void check_boundary()
{
if (x[0] < 0 || x[0] >= N || y[0] < 0 || y[0] >= M)
exit(0);
}void main()
{
char ch;
init();
while (1)
{
draw_food();
draw_snake();
ch = getch();
if (ch == 'w' || ch == 's' || ch == 'a' || ch == 'd')
direction = ch;
move();
check_food();
check_boundary();
Sleep(200);
}
}这是一段贪吃蛇代码,它使用C语言编写,用来模拟贪吃蛇游戏的运行。
阅读全文