给好盆友@cgy @hxf写的~
大概应该可能没有用C++特有的语法吧。。
#include#include #include #include using namespace std; struct pos {//坐标点 int x;//列 int y;//行 }; const int X = 35; const int Y = 18; char screen[Y][X]; pos head{ 4,5 };//蛇头初始位置 pos foodpos{ 19, 9 }; //食物初始位置 pos body[100];//存储蛇身位置的pos数组 bool life = 1; int score = 0; const int speed = 1; int moveX, moveY;//x,y坐标的增量 int lenth = 3;//蛇的初始长度 int os;//用户的输入,见get_input()函数 int get_rannum(int left, int right); void get_input(); void hide_cursor(bool Visible); bool food_eaten(); void update_pos(); bool is_body(int y, int x); void fill_screen(); void draw(); int main() { for (int i = 0; i < lenth; i++) { body[i] = head; } hide_cursor(true); while (life) { get_input(); update_pos(); fill_screen(); draw(); } } int get_rannum(int left, int right)//返回一个[left,right]内的整型数据 { srand((unsigned)time(NULL)); return (rand() % (right - left + 1)) + left; } void get_input() {//获取用户输入 if (_kbhit()) os = _getch();//这一段可以直接抄 if (char(os) == 'a') { moveX = -speed; moveY = 0; } if (char(os) == 'd') { moveX = speed; moveY = 0; } if (char(os) == 'w') { moveY = -speed; moveX = 0; } if (char(os) == 's') { moveY = speed; moveX = 0; } } void hide_cursor(bool Visible)//隐藏光标 直接抄就完事了 { CONSOLE_CURSOR_INFO Cursor; Cursor.bVisible = !Visible; Cursor.dwSize = sizeof(Cursor); HANDLE Hand = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorInfo(Hand, &Cursor); } bool food_eaten() { if (head.x == foodpos.x && head.y == foodpos.y) {//若蛇头碰到了食物 return true; } return false; } void update_pos() {//蛇的身体坐标更新,食物位置更新 for (int i = 0; i < lenth - 1; i++) {//这是贪吃蛇实现中唯一一个需要动脑子的地方,注释说不清楚,自己想想吧~ body[i] = body[i + 1]; } body[lenth - 1] = head; head.x += moveX; head.y += moveY; if (food_eaten()) { lenth++; foodpos.x = get_rannum(5, 30); foodpos.y = get_rannum(5, 15); } } bool is_body(int y, int x) {//坐标点x,y是不是蛇的身体 for (int i = 0; i < lenth; i++) { if (y == body[i].y && x == body[i].x) { return true; } } return false; } void fill_screen() {//填充屏幕矩阵 for (int y = 0; y < Y; y++) { for (int x = 0; x < X; x++) { if (x == head.x && y == head.y) { screen[y][x] = 'O'; } else if (y == 0 || y == Y - 1) { screen[y][x] = '-'; } else if (x == 0 || x == X - 1) { screen[y][x] = '|'; } else if (is_body(y, x)) { screen[y][x] = 'o'; } else if (y == foodpos.y && x == foodpos.x) { screen[y][x] = '%'; } else { screen[y][x] = ' '; } } } } void draw() {//绘制图案 system("cls"); for (int y = 0; y < Y; y++) { for (int x = 0; x < X; x++) { printf("%c", screen[y][x]); } printf("n"); } }



