贪吃蛇(四)向前移动蛇身

实现思路

上节实现了蛇身的绘制,通过扫描的方式,这次我们要通过增加蛇身和删除蛇尾来实现移动蛇。

这里增加了几个函数,都是链表的基本操作
1.增加节点
2.删除节点
3.创建节点

#include"curses.h"
#include "stdlib.h"
struct SnakeNode
{
  int row;
  int col;
  struct SnakeNode* next; 
};

struct SnakeNode* head;
struct SnakeNode* tail;

void addNode();

void initSnake()
{
  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();
}

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");
  }
}

int main()
{
  int key;
  cursesinit();
  initSnake();
  mapinit();

  while(1)
  {
     key = getch();
     if(key == KEY_RIGHT)
     {
	moveSnake();
	mapinit(); // fresh map	
     }
  }

  getch();  
  endwin();
  return 0;
}


学习打卡

贪吃蛇(四)向前移动蛇身_第1张图片

你可能感兴趣的:(c语言)