贪吃蛇
#include<bits/stdc++.h>
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#include<windows.h>
using namespace std;
int tailx[105], taily[105];
int dir = 4, high = 20, wide = 50, x = 10, y = 10, fx, fy, fenshu = 0, len = 2;
int bok[100][100];
void gotoxy(int x, int y) {
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
void fruit() {
srand((unsigned int)(time(NULL)));
fx = rand() % 20 + 1;
fy = rand() % 20 + 1;
}
void da();
int pan() {
if (x < 1 || y < 1 || x > high || y > wide) {
da();
srand((unsigned int)(time(NULL)));
int suiji = rand() % 2 + 1;
if (suiji == 1) {
cout << "贪吃蛇因为失恋一头撞死在了墙上。";
}
if (suiji == 2) {
cout << "贪吃蛇因为吃水果吃多了一头撞死在了墙上。";
}
return 1;
}
if (bok[x][y] == 1) {
cout << "贪吃蛇用贪吃蛇的毒毒贪吃蛇,贪吃蛇会被毒死吗?";
return 1;
}
if (x == fx && y == fy) {
fenshu++;
len++;
fruit();
return 0;
} else {
return 0;
}
}
void da() {
//fenshu是吃的苹果数
Sleep(150-min(fenshu,29)*5);//速度(可改)
gotoxy(0, 0);
// cout<<150-min(fenshu,29)*5<<endl;
// system("cls");
for (int i = 0; i <= high + 1; i++) {
for (int j = 0; j <= wide + 1; j++) {
if (i == 0 || j == 0 || i == high + 1 || j == wide + 1) {
cout << '#';
} else if (i == fx && j == fy) {
cout << '*';
} else if (i == x && j == y) {
cout << 'O';
} else if (bok[i][j] == 1) {
cout << 'o';
} else {
cout << ' ';
}
}
cout << endl;
}
cout<<"你的蛇长:"<<len+1<<" 你的分数:"<<fenshu<<endl;
cout<<"目前速度:"<<150-min(fenshu,29)*5<<endl;
}
void cz() {
if (_kbhit()) {
char ch = _getch();
if (((dir == 1 && (ch == 's'||ch=='5')) || (dir == 2 &&(ch == 'w'||ch=='8')) || (dir == 3 && (ch == 'd'||ch=='6')) || (dir == 4 && (ch == 'a'||ch=='4')))) {
return;
} else if (dir != ch) {
if (ch == 'a'||ch == '4') {
dir = 3;
} else if (ch == 'd'||ch == '6') {
dir = 4;
} else if (ch == 'w'||ch == '8') {
dir = 1;
} else if (ch == 's'||ch == '5') {
dir = 2;
}
}
} else {
return;
}
}
void yd() {
if (len > 1) {
// cout<<bok[tailx[2]]<<' '<<bok[taily[2]]<<endl;
bok[tailx[len]][taily[len]] = 0;
for (int i = len; i > 1; i--) {
tailx[i] = tailx[i - 1];
taily[i] = taily[i - 1];
}
tailx[1] = x, taily[1] = y;
bok[x][y] = 1;
}
if (dir == 1) {
x--;
} else if (dir == 2) {
x++;
} else if (dir == 3) {
y--;
} else if (dir == 4) {
y++;
}
}
int main() {
tailx[1] = x, taily[1] = y + 1;
tailx[2] = x, taily[2] = y;
srand((unsigned int)(time(NULL)));
fruit();
while (1) {
if (pan()) {
cout<<endl<<"本次你获得了"<<fenshu<<"分,游戏结束";
return 0;
}
da();
cz();
yd();
}
return 0;
}