#include <stdlib.h>
#include <iostream>
#include <list>
#include <conio.h>
#include <time.h>
#include <algorithm>
#include <windows.h>
using namespace std;
const int MAXR = 20;
const int MAXC = 50;
void gotoxy(int x, int y) //定位到第y行的第x列
{
int xx=0x0b;
HANDLE hOutput;
COORD loc;
loc.X = x;
loc.Y=y;
hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOutput, loc);
return;
}
struct point
{
int x;
int y;
point& operator=(const point &p)
{
if(&p == this)
return *this;
x = p.x;
y = p.y;
return *this;
}
bool operator==(const point &p)
{
if(&p == this)
return true;
else if(x == p.x && y == p.y)
return true;
return false;
}
};
list<point> snake;
point randP;
void randPoint()
{
randP.x = 0 + (MAXR - 1 + 1) * rand() / RAND_MAX;
randP.y = 0 + (MAXC - 1 + 1) * rand() / RAND_MAX;
list<point>::iterator itor = find(snake.begin(), snake.end(), randP);
if(itor == snake.end())
return;
else
randPoint();
}
void initSnake()
{
point p;
p.x = MAXR / 2;
p.y = 2;
snake.push_back(p);
p.y--;
snake.push_back(p);
p.y--;
snake.push_back(p);
randPoint();
}
void printArr(char arr[][MAXC])
{
gotoxy(0, 0);
cout << "w a s d控制方向,q退出:" << endl;
for(int i = 0; i < MAXR; i++)
for(int j = 0; j < MAXC; j++)
arr[i][j] = '-';
arr[randP.x][randP.y] = '*';
list<point>::iterator itor;
for(itor = snake.begin(); itor != snake.end(); itor++)
arr[(*itor).x][(*itor).y] = '*';
for(int i = 0; i < MAXR; i++)
{
for(int j = 0; j < MAXC; j++)
cout << arr[i][j];
cout << endl;
}
}
int main(int argc, char* argv[])
{
srand((int)time(0));
char arr[MAXR][MAXC];
initSnake();
printArr(arr);
char inputC;
bool effInput;
point p = snake.front();
char state = 'd';
while((inputC = getch()) != 'q')
{
switch(inputC)
{
case 'w':
if(state == 's')
continue;
state = 'w';
p.x--;
break;
case 'a':
if(state == 'd')
continue;
state = 'a';
p.y--;
break;
case 's':
if(state == 'w')
continue;
state = 's';
p.x++;
break;
case 'd':
if(state == 'a')
continue;
state = 'd';
p.y++;
break;
default:
continue;
}
if(p.x >= MAXR)
p.x = 0;
if(p.x < 0)
p.x = MAXR - 1;
if(p.y >= MAXC)
p.y = 0;
if(p.y < 0)
p.y = MAXC - 1;
snake.push_front(p);
if(p == randP)
randPoint();
else
snake.pop_back();
//system("cls");
printArr(arr);
}
system("pause");
return 0;
}
简单Windows控制台贪吃蛇(二维数组模拟地图, 链表模拟贪吃蛇, WASD控制行走, gotoxy替换刷新操作)
最新推荐文章于 2022-11-09 00:37:50 发布