上节我们实现了撞墙重置,本节继续实现自行游走的逻辑。
实现思路
实际上,自行游走只需要取消键盘监听即可。但是注意需要控制循环的速度,以及屏幕的刷新情况。
#include"curses.h"
#include "stdlib.h"
struct SnakeNode
{
int row;
int col;
struct SnakeNode* next;
};
struct SnakeNode* head = NULL;
struct SnakeNode* tail = NULL;
void addNode();
void mapinit();
void snakeinit()
{
// free
struct SnakeNode* p;
while(head != NULL)
{
p = head;
head = head->next;
free(p);
}
head = (struct SnakeNode*)malloc(sizeof(struct SnakeNode));
head->row = 2;
head->col = 2;
head->next = NULL;
tail = head;
addNode();
addNode();
}
void addNode()
{
struct SnakeNode* node = (struct SnakeNode*)malloc(sizeof(struct SnakeNode));
node->row = tail->row;
node->col = tail->col + 1;
node->next = NULL;
tail->next = node;
tail = node;
}
void deleteNode()
{
struct SnakeNode* p;
p = head;
head = head->next;
free(p);
}
void moveSnake()
{
addNode();
deleteNode();
// if snake is over.
if(tail->row == 0 || tail->col == 0 || tail->row >= 20 || tail->col >= 19)
{
snakeinit();
}
}
void cursesinit()
{
initscr();
keypad(stdscr,1);
}
int hasSnake(int row,int col)
{
struct SnakeNode* p = head;
while(p!=NULL)
{
if(row == p->row && col == p->col)
return 1;
p = p->next;
}
return 0;
}
void mapinit()
{
int row;
int col;
move(0,0);
for(row = 0;row < 20;row++)
{
// one
if(row == 0 || row == 19)
{
for(col = 0;col < 19;col++)
printw("--");
}
// two
else
{
for(col = 0;col < 20;col++)
{
if(col == 0 || col == 19 ) printw("|");
else if(hasSnake(row,col))
{
printw("[]");
}
else
{
printw(" ");
}
}
}
printw("\n");
}
// game start
printw("By hongzhe\n");
}
int main()
{
int key;
cursesinit();
snakeinit();
mapinit();
while(1)
{
moveSnake();
mapinit(); // fresh map
refresh(); // fresh screen
usleep(500000);
}
getch();
endwin();
return 0;
}
学习打卡