贪吃蛇

· · 休闲·娱乐

小豆玩贪吃蛇!!!

#include <bits/stdc++.h>
#include <conio.h>
#include <windows.h>
using namespace std;
struct Node {
   int x, y;
} snake[1000];
int length = 5, direction = 3;
Node food;
int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
void locate(int x, int y) {
   COORD coord = {short(y), short(x)};
   SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void printWall(int m, int n) {
   for (int i = 0; i <= m + 1; i++) {
       for (int j = 0; j <= n + 1; j++) {
           if (i == 0 || i == m + 1 || j == 0 || j == n + 1) cout << "#";
           else cout << " ";
       }
       cout << endl;
   }
}
void printSnake() {
   locate(snake[0].x, snake[0].y);
   cout << "@";
   for (int i = 1; i < length; i++) {
       locate(snake[i].x, snake[i].y);
       cout << "*";
   }
}
bool isValid(int x, int y, int m, int n) {
   if (x <= 0 || x > m || y <= 0 || y > n) return false;
   for (int i = 1; i < length; i++) {
       if (snake[i].x == x && snake[i].y == y) return false;
   }
   return true;
}
void generateFood(int m, int n) {
   do {
       food.x = rand() % m + 1;
       food.y = rand() % n + 1;
   } while (!isValid(food.x, food.y, m, n));
   locate(food.x, food.y);
   cout << "$";
}
void moveSnake(int m, int n) {
   Node prev = snake[length - 1];
   for (int i = length - 1; i > 0; i--) {
       snake[i] = snake[i - 1];
   }
   snake[0].x += dx[direction];
   snake[0].y += dy[direction];
   if (snake[0].x == food.x && snake[0].y == food.y) {
       length++;
       snake[length - 1] = prev;
       generateFood(m, n);
   } else {
       locate(prev.x, prev.y);
       cout << " ";
   }
   printSnake();
}
int main() {
   int m = 20, n = 40;
   srand(time(0));
   for (int i = 0; i < length; i++) {
       snake[i].x = 1;
       snake[i].y = 5 - i;
   }
   system("cls");
   printWall(m, n);
   generateFood(m, n);
   printSnake();
   while (true) {
       if (_kbhit()) {
           char ch = _getch();
           if (ch == 'w' && direction != 1) direction = 0;
           else if (ch == 's' && direction != 0) direction = 1;
           else if (ch == 'a' && direction != 3) direction = 2;
           else if (ch == 'd' && direction != 2) direction = 3;
       }
       moveSnake(m, n);
       Sleep(200);
       if (!isValid(snake[0].x, snake[0].y, m, n)) break;
   }
   cout << "Game Over! Length: " << length << endl;
   return 0;
}