今天分析到蛇身这里。这里用的是数组的手法。
于是写的代码如下:`插入插入插入#include;
#include<windows.h>;
#include<conio.h>;
using namespace std;
bool gameOver;
const int width = 20;
const int height = 5;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
int i, j;
enum eDirection { STOP = 0,LEFT,RIGHT,UP,DOWN };
eDirection dir;
void Initial()
{
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
}
void Draw()
{
system("cls");
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
int textColor = 0x06;
SetConsoleTextAttribute(h, textColor);
for (int i = 0; i < width+2; i++)
cout << "1";
cout << endl;
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
if (i == 0)
cout << "2";
if (i == x && j == y) {
textColor = 0X0a;
SetConsoleTextAttribute(h, textColor);
cout << "O";
}
else if (i == fruitX && j == fruitY)
{
textColor = 0x084;
SetConsoleTextAttribute(h, textColor);
cout << "F";
}
else
{
bool flagPrint = false;
for (int k = 0; k < nTail; k++)
{
if (tailX[k] == i && tailY[k] == j)
{
cout << "o";
flagPrint = true;
}
}
textColor = 0x06;
SetConsoleTextAttribute(h,textColor);
if(flagPrint)
cout << " ";
}
if (i == width - 1)
cout << "3";
}
cout << endl;
}
for (i = 0; i < width+2; i++)
cout << "4";
cout << endl;
cout << "游戏得分" << score << endl;
}
void Input()
{
if (_kbhit())
{
switch (_getch())
{
case'a':
dir = LEFT;
x--;
break;
case'd':
dir = RIGHT;
x++;
break;
case'w':
dir = UP;
y--;
break;
case's':
dir = DOWN;
y++;
break;
case'x':
gameOver = true;
break;
default:
break;
}
}
}
void Logic()
{
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X;
int prev2Y;
tailX[0] = x;
tailY[0] = y;
for (i = 1; i < nTail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevX;
prevX = prev2X;
prevY = prev2Y;
}
for (int i = 0; i < nTail; i++)
if (tailX[i] == x && tailY[i] == y)
gameOver == true;
for (int i = 0; i < nTail; i++)
if (tailX[i] == x && tailY[i] == y)
gameOver == true;
if (x > width || x<0 || y>height || y < 0)
gameOver = true;
if (x >= width) x = 0;else if (x < 0);x = width - 1;
if (x >= height)y = 0; else if (y < 0)y = height - 1;
if (x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
nTail++;
}
}
int main()
{
Initial();
while (!gameOver)
{
Draw();
Input();
Logic();
}
system("pause");
return 0;
}`
自我感觉非常良好。但是却出了问题
哼心情极差。烦死了。
然后发现自己的widthheight设置不合理。改正之后是这样
害。3号墙又作什么妖了。我感觉这一点问题都没有。
下 先把绘制蛇身o的部分注释掉。成了这个样子
初始蛇头坐标在最右侧。并且不能左右移动。当我把所写的数组部分注释掉时,发现水果坐标竟然无法自动更新位置。
迅速做出一个公主落泪的动作