1.1初始化curses
初始化curses
void initscr_func(){
initscr();
keypad(stdscr,true);
}
1.2创建贪吃蛇
点击查看代码
//贪吃蛇创建
snake_t* create_snake(int row, int col){
snake_head = (snake_t*)malloc(sizeof(snake_t)); //蛇头分配内存
snake_head->row = row; //蛇头在的行数
snake_head->col = col; //蛇头在的列数
snake_head->next = NULL;
snake_tail=snake_head; //初始化蛇头和蛇尾的位置
add_snake_body(); //添加蛇身体
add_snake_body();
return snake_head;
}
点击查看代码
//添加贪吃蛇身体
void add_snake_body(){
snake_t *snake_body = (snake_t*)malloc(sizeof(snake_t)); //蛇身体分配内存
while (snake_tail->next!=NULL){
snake_tail=snake_tail->next; //找到尾节点
}
snake_body->row = snake_tail->row; //蛇身体行坐标与尾节点坐标相同
snake_body->col = snake_tail->col+1; //蛇身体纵坐标在尾节点的右边
snake_body->next = NULL; //蛇身体的下一个节点为空
snake_tail->next = snake_body; //尾节点的下一个节点指向蛇身体
snake_tail=snake_body; //更新尾节点
}
1.4蛇的尾部删除和判断是否需要重新初始化蛇子(在蛇撞墙后)
点击查看代码
//delete snake body(head delete)
void rig_delete_snake_body(){
snake_t *p;
if(snake_head!=NULL){
p=snake_head; //保存头节点
snake_head=snake_head->next; //头节点指向下一个节点
}
free(p); //释放头节点内存
}
//judge has snake body
int has_snake_body(int row, int col){
snake_t *p = snake_head;
while(p!=NULL){
if(p->row==row&&p->col==col){
return 1;
}
p = p->next;
}
return 0;
}
bool snake_need_init(){
// if(snake_head->row==0||snake_head->col==0||snake_head->row==20||snake_head->col==20){
// return true;
// }
// else
if (snake_tail->row==MIN||snake_tail->col==MIN||snake_tail->row==HEIGHT-1||snake_tail->col==HEIGHT-1){
return true;
}
else{
return false;
}
}
1.5蛇的移动
点击查看代码
//right move
void rig_move_snake(){
//判读是否需要重新开始游戏
if (snake_need_init()==true){
snake_t *old_sanke_head =NULL;
//游戏初始前,回收上一次蛇身子
while(snake_head!=NULL){
old_sanke_head = snake_head;
snake_head = snake_head->next;
free(old_sanke_head);
}
create_snake(6,6); //创建蛇
map_init(WIDHT,HEIGHT);
}
//不需要重新开始游戏
else{
rig_delete_snake_body();
add_snake_body();
map_init(WIDHT,WIDHT);
}
}
1.6蛇的向右移动
点击查看代码
//right move
void rig_move_snake(){
//判读是否需要重新开始游戏
if (snake_need_init()==true){
snake_t *old_sanke_head =NULL;
//游戏初始前,回收上一次蛇身子
while(snake_head!=NULL){
old_sanke_head = snake_head;
snake_head = snake_head->next;
free(old_sanke_head);
}
create_snake(6,6); //创建蛇
map_init(WIDHT,HEIGHT);
}
//不需要重新开始游戏
else{
rig_delete_snake_body();
add_snake_body();
map_init(WIDHT,WIDHT);
}
}
1.7初始化地图
点击查看代码
//初始化地图
void map_init(int witdh, int height)
{
int row,col;
move(MIN,MIN); //复位光标
for (row = 0; row < witdh; row++) //打印地图边界
{
if(row==0){
for (col = 0; col < height; col++){
printw("--");
}
}
printw("\n");
for (col = 0; col <= height; col++){
if (col==0||col==height)
{
printw("|");
}
else if(has_snake_body(row,col)){
printw("[]");
}
else{
printw(" ");
}
}
printf("\n");
}
printw("\n");
for (col = 0; col < height; col++){
printw("--");
}
move(MIN,MIN); //复位光标,防止光标在最后一行
}