#include<bits/stdc++.h>
#include<conio.h>
#include<windows.h>
void gotoxy(short x, short y) {
COORD pos = {short(2 * y), x };
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOut, pos);
}
class game {
const int ix[4] = {-1, 1, 0, 0};
const int iy[4] = {0, 0, -1, 1};
int move_head(int w) {
head.X += ix[w], head.Y += iy[w];
if (map[head.X][head.Y] > -2 && map[head.X][head.Y] != 0)return 0;
if (draw) {
gotoxy(head.X + 1, head.Y);
std::cout << "█";
}
if (map[head.X][head.Y] == -2) {
if (draw) {
gotoxy(0, 0);
std::cout << "score:" << ++score;
}
food();
map[head.X][head.Y] = ++len;
return 1;
}
map[head.X][head.Y] = len + 1;
return 2;
}
public:
bool draw = 1;
int **map, way = 0, score = 0, x, y, len;
COORD head;
game(int n, int m) {
x = n, y = m;
//创建+初始化数组
map = new int*[x];
for (int i = 0; i != x; ++i) {
map[i] = new int[y];
memset(map[i], 0, sizeof(int[y]));
}
for (int i = 0; i != x; ++i) map[i][0] = map[i][y - 1] = -1;
for (int i = 0; i != y; ++i) map[0][i] = map[x - 1][i] = -1;
head.X = x / 2 - 1, head.Y = x / 2 - 1;
map[head.X][head.Y] = 1;
len = 1;
food();
if (draw) {
gotoxy(0, 0);
std::cout << "score:" << score;
for (int i = 0; i != x; ++i)
for (int j = 0; j != y; ++j) {
gotoxy(i + 1, j);
if (map[i][j] == -1)std::cout << "▓";
else if (map[i][j] > 0)std::cout << "█";
}
}
}
~game() {
//删除二维数组
for (int i = 0; i != x; ++i)delete map[i];
delete map;
}
void food() {
COORD f;
do f.X = rand() % x, f.Y = rand() % y;
while (map[f.X][f.Y] != 0);
map[f.X][f.Y] = -2;
if (draw) {
gotoxy(f.X + 1, f.Y);
std::cout << "╬";
}
}
bool move(int w = 0) {//方向1234
if (w != 0 && !(ix[way] + ix[w - 1] == 0 && iy[way] + iy[w - 1] == 0))way = w - 1;
switch (move_head(way)) {
case 0:
return 0;
case 1:
return 1;
case 2:
for (int i = 0; i != x; ++i)
for (int j = 0; j != y; ++j)
if (map[i][j] > 0) {
--map[i][j];
if (draw && !map[i][j]) {
gotoxy(i + 1, j);
std::cout << " ";
}
}
return 1;
}
abort();
}
};
int getDirection() {
if (_kbhit()) { // 检查是否有键盘输入
switch (_getch()) { // 获取键盘输入的字符
case 'w':
case 'W':
return 1; // 返回上
case 's':
case 'S':
return 2; // 返回下
case 'a':
case 'A':
return 3; // 返回左
case 'd':
case 'D':
return 4; // 返回右
}
}
return 0; // 如果没有输入或输入无效,则返回0
}
////////////////////////////////////////////AI
class AIPlayer {
private:
game& g;
public:
AIPlayer(game& g) : g(g) {}
int Direction() {
}
int evaluateChromosome(){
g.draw = 0;
while (g.move(Direction()));
return g.score;
}
};
///////////////////////////////////////////
int main() {
Sleep(100);
system("color F0");
system("mode con cols=40 lines=20");
system("title 贪吃蛇");
CONSOLE_CURSOR_INFO cursor_info = {20, 0};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
srand((unsigned)time(NULL));
system("pause");
system("cls");
game g(16, 16);
AIPlayer ai(g);
// while (g.move(getDirection()))Sleep(100);
system("cls");
std::cout << "you dead(score:" << g.score << ")\n";
system("pause");
return 0;
}剪贴板
剪贴板 l1ve8813
剪贴板信息
剪贴板信息
- 收录
- 更新