《贪吃蛇》
2026-06-07 16:47:13
发布于:江苏
#include<bits/stdc++.h>
#include<windows.h>
#include<conio.h>
using namespace std;
const int n = 20;
bool die = false;
int len = 3;
int d[4][2] = {0, -1, 0, 1, -1, 0, 1, 0};
int snake[n * n][2], food[2];
bool in_snake(int x, int y){
for (int i = 0; i < len; i++){
if (snake[i][0] == x && snake[i][1] == y){
return true;
}
}
return false;
}
void init(){
for (int i = 0; i < len; i++){
snake[i][0] = len - i - 1;
}
food[0] = rand() % n;
food[1] = rand() % n;
}
void draw_line(int l){
for (int i = 0; i < n; i++){
if (in_snake(i, l)){
cout << "@ ";
}else if (i == food[0] && l == food[1]){
cout << "# ";
}else{
cout << " ";
}
}
cout << "|" << endl;
}
void move(int c){
if (snake[0][0] + d[c][0] == food[0] && snake[0][1] + d[c][1] == food[1]){
len = len + 1;
food[0] = rand() % n;
food[1] = rand() % n;
}
for (int i = len - 1; i > 0; i--){
snake[i][0] = snake[i - 1][0];
snake[i][1] = snake[i - 1][1];
}
snake[0][0] = snake[0][0] + d[c][0];
snake[0][1] = snake[0][1] + d[c][1];
if (snake[0][0] < 0 || snake[0][0] > n - 1 || snake[0][1] < 0 || snake[0][1] > n - 1){
die = true;
return ;
}
for (int i = 1; i < len; i++){
if (snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1]){
die = true;
return ;
}
}
}
void gotoxy(int x, int y){
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void hidden(){
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
GetConsoleCursorInfo(hOut, &cci);
cci.bVisible = 0;
SetConsoleCursorInfo(hOut, &cci);
}
int main(){
srand(time(0));
int dir = 3;
char c;
init();
system("cls");
for (int i = 0; i < n; i++){
draw_line(i);
}
for (int i = 0; i < n * 2; i++){
cout << "-";
}
cout << "+";
while (true){
if (_kbhit()){
c = _getch();
if (c == 'w' && dir != 1){
dir = 0;
}
if (c == 's' && dir != 0){
dir = 1;
}
if (c == 'a' && dir != 3){
dir = 2;
}
if (c == 'd' && dir != 2){
dir = 3;
}
}
gotoxy(0, food[1]);
draw_line(food[1]);
int tail[2] = {snake[len - 1][0], snake[len - 1][1]};
move(dir);
if (die){
break;
}
gotoxy(0, tail[1]);
draw_line(tail[1]);
gotoxy(0, snake[0][1]);
draw_line(snake[0][1]);
hidden();
Sleep(150);
}
gotoxy(0, n);
return 0;
}
这里空空如也















有帮助,赞一个