对象:贪吃蛇小程序
(原代码见 https://blog.csdn.net/leslie5205912/article/details/78980006)
测试过程:
程序改动部分:
1.bug修复
经过测试,发现了一个bug:豆子的生成并不是随机产生的。
生成豆子部分代码如下:
void Creatfood(char map[Row_max][Line_max], int snake[Row_max][Line_max]) {//生成豆子
do{
food_x = rand() % (Line_max - 2) + 1;
food_y = rand() % (Row_max - 2) + 1;
} while (snake[food_y][food_x] != 0||map[food_y][food_x]=='#');
map[food_y][food_x] = '*';
}
此处原作者显然是准备随机生成豆子,然鹅没有给与随机数种子,可能是忘记了?
于是加上srand(time(NULL)); 语句根据时间生成随机数种子
(此处原作者使用 do{ }while (snake[food_y][food_x] != 0||map[food_y][food_x]=='#');语句保证随机生成的豆子不在蛇身上且没有落在游戏边框上)
经测试改动后无bug,种子能够正常随机生成了
2.主页面美化
原作者为了代码简洁,主页面仅显示一句"Press any key to start this game!"
还是美化一下吧orz
代码如下:
cout << " *** ****" << endl;
cout << " **** * **Q *<--food" << endl;
cout << " *****" << endl;
cout << "" << endl;
cout << "-------The Gluttonous Snake-------" << endl;
cout << "" << endl;
cout << " Use ↑ W" << endl;
cout << " ←↓→ or A S D to control" << endl;
cout << "" << endl;
cout << "" << endl;
cout << " Press any key to start this game!" << endl;
改动后:
3.实时显示分数
玩家可能需要一个实时显示分数的功能?
于程序运行主要循环代码,也就是switch (ch) 部分添加语句如下
printf("\nScore:%d\n",score*10);
即可在每一次循环时输出当时分数的值
改动后:
疑问部分:
想要实现按下指定按键即重新执行程序,按下除此外任意键退出
但是使用while语句后,的确可以重新回到主页,但是不能正常继续执行程序,Creatsnake(snake);Creatmap(map);Creatfood(map, snake);Run(map, snake);均无法运行,会直接跳转到结束页Result();
使用代码如下:
int main() {
int k;
while(1){
system("cls");
cout << " *** ****" << endl;
cout << " **** * **Q *<--food" << endl;
cout << " *****" << endl;
cout << "" << endl;
cout << "-------The Gluttonous Snake-------" << endl;
cout << "" << endl;
cout << " Use ↑ W" << endl;
cout << " ←↓→ or A S D to control" << endl;
cout << "" << endl;
cout << "" << endl;
cout << " Press any key to start this game!" << endl;
getch();
Creatsnake(snake);
Creatmap(map);
Creatfood(map, snake);
Run(map, snake);
Result();
k=getch();
if(k!='Y')break;
}
}