为什么设置光标这X要=2y,改成X=y不对。
struct{char *ch;
int color;
char type;
}
charBorder = {"□", 4, 1}, //边框
charBg = {"■", 2, 2}, //背景
charSnake = {"★", 0xe, 3}, //贪吃蛇节点
charFood = {"●", 0xc, 4}; //食物
//用一个结构体数组保存地图中的各个点
struct{
char type;
int index;
}globalMap[MAXWIDTH][MAXHEIGHT];
//贪吃蛇有效活动范围地图的索引
struct{
int x;
int y;
} snakeMap[ (MAXWIDTH-2)*(MAXHEIGHT-2) ], scoresPostion;
int scores = 0; //得分
int snakeMapLen = (MAXWIDTH-2)*(MAXHEIGHT-2);
int headerIndex, tailIndex; //蛇头蛇尾对应的snakeMap中的索引(下标)
HANDLE hStdin; //控制台句柄
// 设置光标位置,x为行,y为列
void setPosition(int x, int y){
COORD coord;
coord.X = 2*y;
coord.Y = x;
SetConsoleCursorPosition(hStdin, coord);
}
// 设置颜色
void setColor(int color){
SetConsoleTextAttribute(hStdin, color);
}
//创建食物
void createFood(){
int index, rang, x, y;
//产生随机数,确定 snakeMap 数组的索引
srand((unsigned)time(NULL));
if(tailIndex<headerIndex){
rang = headerIndex-tailIndex-1;
index = rand()%rang + tailIndex + 1;
}else{
rang = snakeMapLen - (tailIndex - headerIndex+1);
index = rand()%rang;
if(index>=headerIndex){
index += (tailIndex-headerIndex+1);
}
}
x = snakeMap[index].x;
y = snakeMap[index].y;
setPosition(x, y);
setColor(charFood.color);
printf("%s", charFood.ch);
globalMap[x][y].type=charFood.type;
}
//死掉
void die(){
int xCenter = MAXHEIGHT%2==0 ? MAXHEIGHT/2 : MAXHEIGHT/2+1;
int yCenter = MAXWIDTH%2==0 ? MAXWIDTH/2 : MAXWIDTH/2+1;
setPosition(xCenter, yCenter-5);
setColor(0xC);
printf("You die! Game Over!");
getch();
exit(0);
}
// 蛇移动
void move(char direction){
int newHeaderX, newHeaderY; //新蛇头的坐标
int newHeaderPreIndex; //新蛇头坐标以前对应的索引
int newHeaderPreX, newHeaderPreY; //新蛇头的索引以前对应的坐标
int newHeaderPreType; //新蛇头以前的类型
int oldTailX, oldTailY; //老蛇尾坐标
// -----------------------------------------------
//新蛇头的坐标
switch(direction){
case 'w':
newHeaderX = snakeMap[headerIndex].x-1;
newHeaderY = snakeMap[headerIndex].y;
break;
case 's':
newHeaderX = snakeMap[headerIndex].x+1;
newHeaderY = snakeMap[headerIndex].y;
break;
case 'a':
newHeaderX = snakeMap[headerIndex].x;
newHeaderY = snakeMap[headerIndex].y-1;
break;
case 'd':
newHeaderX = snakeMap[headerIndex].x;
newHeaderY = snakeMap[headerIndex].y+1;
break;
}
//新蛇头的索引
headerIndex = headerIndex==0 ? snakeMapLen-1 : headerIndex-1;
// -----------------------------------------------
//新蛇头坐标以前对应的索引
newHeaderPreIndex = globalMap[newHeaderX][newHeaderY].index;
//新蛇头的索引以前对应的坐标
newHeaderPreX = snakeMap[headerIndex].x;
newHeaderPreY = snakeMap[headerIndex].y;
//双向绑定新蛇头索引与坐标的对应关系
snakeMap[headerIndex].x = newHeaderX;
snakeMap[headerIndex].y = newHeaderY;
globalMap[newHeaderX][newHeaderY].index = headerIndex;
//双向绑定以前的索引与坐标的对应关系
snakeMap[newHeaderPreIndex].x = newHeaderPreX;
snakeMap[newHeaderPreIndex].y = newHeaderPreY;
globalMap[newHeaderPreX][newHeaderPreY].index = newHeaderPreIndex;