C ++ Snake-D

#include <iostream>
#include <conio.h>
#include <windows.h>
#include <time.h>

int g_Dir = 3;
#define UP         0
#define DOWN  1
#define LEFT       2
#define RIGHT   3

struct FOOD
{
    int X = 0;
    int Y = 0;
    bool State = 0;
}Food;

//方向控制
void SnekeMove()
{
    if (::GetAsyncKeyState(VK_UP) & 1)
        g_Dir = 0;
    if (::GetAsyncKeyState(VK_DOWN) & 1)
        g_Dir = 1;
    if (::GetAsyncKeyState(VK_LEFT) & 1)
        g_Dir = 2;
    if (::GetAsyncKeyState(VK_RIGHT) & 1)
        g_Dir = 3;
}

//主函数
int main()
{
    srand((unsigned int)time(NULL));
    int W = 20;
    int H = 20;
    int Len = 3;
    int Map[20][20] = { 0 };
    int Snake[50][2] = { 0 };
    //Snake[0] = 2;//为蛇头
    
    for (int i = 0; i < Len; i++)
    {
        Snake[i][0] = Len - i - 1;
    }
    Food.X = W / 2;
    Food.Y = H / 2;
    Map[Food.Y][Food.X] = 2;

    const char *SNAKE[] = { "  ", "" ,""};
    while (true)
    {
        system("cls");
        int x = 0;
        int y = 0;
        for (int i = 0; i < Len; i++)
        {
            // 2 1 0
            // 1 1 1

            // 321
             // 0111
             // noted here that 
            X = Snake [I] [ 0 ]; 
            Y = Snake [I] [ . 1 ];
             // here depends on understanding the two-dimensional array
             // although Y is always 0
             // the Map [Y] addresses headed
             // through inference to obtain these types of writing
             // * (the Map [Y] + X) =. 1;
             // the Map [Y] [X] =. 1; 
            * (the Map [ 0 ] + X) = . 1 ;
             // the Map [0] [X] =. 1; 
        }
         for ( int I = 0; i < H; i++)
        {
            for (int j = 0; j < W; j++)
            {
                std::cout << SNAKE[Map[i][j]];
            }
            std::cout << std::endl;
        }
        memset(Map, 0, sizeof(Map));
        SnekeMove();
        for (int i = Len; i > 0; i--)
        {
            Snake[i][0] = Snake[i - 1][0];
        }

        if (g_Dir == UP)
        {
            Snake[0][0] -= W;
        }
        if (g_Dir == DOWN)
        {
            Snake[0][0] += W;
        }
        if (g_Dir == LEFT)
        {
            Snake[0][0]--;
        }
        if (g_Dir == RIGHT)
        {
            Snake[0][0]++;
        }

        Sleep(50);
    }


    //https://www.bilibili.com/video/av29007126/?spm_id_from=333.788.videocard.1
    system("pause");
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/YZFHKMS-X/p/11780545.html