解决展示的设计思路及代码(新人从0到1调试按键监控及运行逻辑正常大概需要1~2个小时,如果再带深究一些内容点,半天怎么都能完成的)
day3解决的问题:
- 蛇移动方位的更改。在蛇类里面增加一个setstatus函数,通过判断char c来移动。这里使用上下左右来移动,当然根据个人爱好,可以吧case改成asdw对应的char。显然,不能往反方向走。
class Snake{
public:
void setstatus(char c) {
switch (c)
{
case 72:
if(getstatus()!= Status::down)
this->stat = Status::up;
break;
case 80:
if (getstatus() != Status::up)
this->stat = Status::down;
break;
case 75:
if (getstatus() != Status::right)
this->stat = Status::left;
break;
case 77:
if (getstatus() != Status::left)
this->stat = Status::right;
break;
default:
break;
}
}
};
- char监听。可以使用conio.h里面的两个函数_kbhit,_getch来完成非阻塞式键盘监听。(这里自己从0开始着实有点难,毕竟cin,getchar什么的都要回车,阻塞主线程,好烦。)正好,原来函数deley中有个while循环什么都没做,我们把这个内容放进去即可。(如果有输入就把它传给c)
#include <conio.h>
char c;
const int max_size = norm_size * norm_size;
void delay(int time) {
clock_t now = clock();
while (clock() - now < time) {
if (_kbhit()) {
c = _getch();
}
}
}
int main(){
while (snake.size() < max_size && snake.live()){
delay(500);
snake.setstatus(c);
snake.eat(food);
}
}
- Food随机生成。用到了随机数生成引擎,使用均匀分布生成x,y,同时reset函数进行了修改,如果当前位置
#include<random>
std::default_random_engine dre;
std::uniform_int_distribution<int> di;
const char food_smb = 'o';
struct Food {
int x = di(dre);
int y = di(dre);
bool flag = 1;
bool eated() {
return !flag;
}
void reset() {
if (vvc[x][y] == food_smb) vvc[x][y] = ' ';
x = di(dre);
y = di(dre);
flag = 1;
}
};
int main() {
Snake snake;
Food food;
auto beg = snake.gethead();
auto end = snake.gettail();
while (snake.size() < max_size && snake.live()) {
vvc[beg.first][beg.second] = body_smb;
system("cls");
while (vvc[food.x][food.y] == body_smb||
food.eated())
food.reset();
vvc[food.x][food.y] = food_smb;
print_all(vvc);
delay(500);
snake.setstatus(c);
snake.eat(food);
beg = snake.gethead();
if (end != snake.gettail()) {
vvc[end.first][end.second] = ' ';
end = snake.gettail();
}
}
cout << "your grade is: " <<grade<< endl;
}
- 至此,贪吃是已经可以正常运行了。下一节将v1版本贪吃蛇全部代码展示出来。
|