#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 // 3 2 1 // 0 1 1 1 //这里需要注意 x = Snake[i][0]; y = Snake[i][1]; //这里取决于对二维数组的理解 //虽然Y始终为0 //Map[y] 为首地址 //经过推理得到这几种写法 //*(Map[y] + x) = 1; //Map[y][x] = 1; *(Map[0] + x) = 1; //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; }
原文地址:https://www.cnblogs.com/YZFHKMS-X/p/11780545.html
时间: 2024-10-16 19:49:47