代码敲了一半了,但是运行的结果和理论上不一样
运行以下代码,应该会在中间出现一条小蛇,小蛇默认头向右,wsad控制方向
但是运行后小蛇没有动,然后就按任意键退出了
问题在哪?
#include<stdio.h>
#include<windows.h>
#include<conio.h>
#include<stdlib.h>
#define HIGH 25
#define WIDTH 60
int moveDirection; //小蛇移动方向,1,2,3,4分别表示上下左右
int canvas[HIGH][WIDTH] = {0};
//0为空格,-1为边框#,1为蛇头@,>1为蛇身*
void HideCursor()
{
CONSOLE_CURSOR_INFO cursor_info={1,0};//第二个值为0表示隐藏光标
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
}
void gotoxy(int x,int y)//光标移动到(x,y)位置
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle,pos);
}
void startup()
{
int i,j;
//以下设置边框
for(i=0;i<HIGH;i++)
{
canvas[i][0] = -1;
canvas[i][WIDTH-1] = -1;
}
for(j=0;j<WIDTH;j++)
{
canvas[0][j] = -1;
canvas[HIGH-1][j] = -1;
}
//以下设置蛇
canvas[HIGH/2][WIDTH/2] = 1;
for(i=0;i<=4;i++)
canvas[HIGH/2][WIDTH/2-i] = i+1;
moveDirection = 4;
HideCursor();//隐藏光标
}
void moveSnake()
{
int i,j;
int max = 0;
int oldtail_i,oldtail_j; //旧蛇尾位置
int oldhead_i,oldhead_j; //旧蛇头位置
int newhead_i,newhead_j; //新蛇头位置
for(i=1;i<HIGH-1;i++)
for(j=1;WIDTH-1;j++)
{
if(canvas[i][j]>0) //对所有大于零的元素加一
{
canvas[i][j]++;
if(max<canvas[i][j]) //求出最大值
{
max = canvas[i][j];
oldtail_i = i; //旧蛇尾位置
oldtail_j = j;
}
if (canvas[i][j]==2)
{
oldhead_i = i; //旧蛇头位置
oldhead_j = j;
}
}
}
canvas[oldtail_i][oldtail_j] = 0; //最大值所在元素变为0
if(moveDirection == 1) //向上
{
canvas[oldhead_i-1][oldhead_j] = 1;
newhead_i = oldhead_i-1;
newhead_j = oldhead_j;
}
if(moveDirection == 2) //向下
{
canvas[oldhead_i+1][oldhead_j] = 1;
newhead_i = oldhead_i+1;
newhead_j = oldhead_j;
}
if(moveDirection == 3) //向左
{
canvas[oldhead_i][oldhead_j-1] = 1;
newhead_i = oldhead_i;
newhead_j = oldhead_j-1;
}
if(moveDirection == 4) //向右
{
canvas[oldhead_i][oldhead_j+1] = 1;
newhead_i = oldhead_i;
newhead_j = oldhead_j+1;
}
}
void show()
{
int i,j;
gotoxy(0,0);
for(i=0;i<HIGH;i++)
{
for(j=0;j<WIDTH;j++)
{
if(canvas[i][j] == 0)
printf(" "); //输出空格
else if(canvas[i][j] == -1)
printf("#"); //输出边框
else if(canvas[i][j] == 1)
printf("@"); //输出蛇头
else if(canvas[i][j] > 1)
printf("*"); //输出蛇身
}
printf("\n");
}
Sleep(100);
}
void updateWithoutInput()
{
moveSnake();
}
void updateWithInput()
{
char input;
if(kbhit())
{
input = getch();
if(input=='a')
moveDirection = 3;
if(input=='d')
moveDirection = 4;
if(input=='w')
moveDirection = 1;
if(input=='s')
moveDirection = 2;
}
}
int main()
{
startup();//游戏初始化
while(1)
{
show();//显示画面
updateWithoutInput();//与用户输入无关的更新
updateWithInput();//与用户输入有关的更新
}
return 0;
}