1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
| #include<cstdlib> #include<windows.h> #include<conio.h> #include<vector> #include<iostream> #include<ctime>
#define COL 30 #define ROW 50
const int InitLength=5;
enum Dir{UP,DOWN,LEFT,RIGHT}; int dir=RIGHT;
int is_food=1; int food_x,food_y;
struct Snake{ Snake(){} Snake(int x,int y){_x=x; _y=y;} int _x,_y; }; std::vector<Snake> nodes;
void SetCCPos(int x, int y) { HANDLE hOut; hOut = GetStdHandle(STD_OUTPUT_HANDLE); COORD pos; pos.X = x; pos.Y = y; SetConsoleCursorPosition(hOut, pos); }
void InitSnake(){ for(int i = InitLength;i >= 1;i--) nodes.push_back(Snake(i,1)); }
bool collision(){ int x=nodes[0]._x; int y=nodes[0]._y; if(x <= 0 || x >= ROW || y <= 0 || y >= COL) return false; for(int i = 1;i < nodes.size();i++) if(x==nodes[i]._x && y==nodes[i]._y) return false; return true; }
void CreateFood(){ food_x=rand()%(ROW - 2) + 1; food_y=rand()%(COL - 2) + 1; SetCCPos(food_x,food_y); std::cout<<"*"; }
void DrawFood(){ if(is_food) { SetCCPos(food_x,food_y); std::cout<<"*"; } }
void DrawSnake(){ for(int i = 0;i < nodes.size();i++) { SetCCPos(nodes[i]._x,nodes[i]._y); std::cout<<"O"; } }
void MoveSnake(){ for(int i = nodes.size() - 1;i > 0;i--) nodes[i]=nodes[i-1]; if(_kbhit()){ if(GetAsyncKeyState(VK_UP)) dir=UP; else if(GetAsyncKeyState(VK_DOWN)) dir=DOWN; else if(GetAsyncKeyState(VK_LEFT)) dir=LEFT; else if(GetAsyncKeyState(VK_RIGHT)) dir=RIGHT; } switch(dir){ case(UP): nodes[0]._y -= 1;break; case(DOWN): nodes[0]._y += 1;break; case(LEFT): nodes[0]._x -= 1;break; case(RIGHT): nodes[0]._x += 1;break; } }
void Drawbackground(){ for(int i = 0; i < ROW; i++) { SetCCPos(i,0); std::cout<<"#"; } for(int i = 0; i < ROW; i++) { SetCCPos(i,COL-1); std::cout<<"#"; } for(int i = 1; i < COL - 1; i++) { SetCCPos(0,i); std::cout<<"#"; } for(int i = 1; i < COL - 1; i++) { SetCCPos(ROW-1,i); std::cout<<"#"; } }
void InitGame(){ InitSnake(); system("mode con cols=50 lines=30"); Drawbackground(); CONSOLE_CURSOR_INFO cursor_info = {1, 0}; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info); CreateFood(); }
|