码迷,mamicode.com
首页 > 其他好文 > 详细

贪吃蛇

时间:2019-06-15 09:49:55      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:change   rand   nio   and   int   bsp   sse   over   cti   

/*
1活动范围怎么设计
2 蛇身设计实现
3 控制
4 食物
5 吃食物
*/

#include <iostream>
#include <cstdlib>
#include <conio.h>
#include <time.h>
#include <Windows.h>
#include <assert.h>
using namespace std;
char game[20][20];
//活动范围
void InitFace()
{
 for (int i = 0; i < 20; i++)
 {
  for (int j = 0; j < 20; j++)
  {
   if (i == 0 || i == 19 || j == 0 || j == 19)
   {
    game[i][j] = ‘ ‘;
    
   }
   else game[i][j] = ‘ ‘;
  }
 }
}
void OutputF()
{
 for (int i = 0; i < 20; i++)
 {
  for (int j = 0; j < 20; j++)
  {
   cout << game[i][j];
  }
  cout << endl;
 }

}
//链表
typedef struct node
{
 int i;
 int j;
 struct node* next, * prior;
}SnakeNode;

SnakeNode* head = NULL, * tail = NULL;
int get_i(SnakeNode*& L)
{
 return L->i;

}
int get_j(SnakeNode *&L)
{
 return L->j;
}
//添加节点
void add_head(int i, int j, SnakeNode*& L)
{
 SnakeNode* p;
 p = (SnakeNode*)malloc(sizeof(SnakeNode));
 
 assert(p);
 p->i = i;
 p->j = j;
 p->next = head;
 p->prior = NULL;
 if (head) head->prior = p;
 head = p;
 if (!tail) tail = head;
 game[i][j] = ‘*‘;
 L = head;
}
//删除
void delete_tail()
{

 SnakeNode* p = tail;
 game[get_i(tail)][get_j(tail)] = ‘ ‘;
 if (tail == head)
  tail = head = NULL;
 else
 {
  tail = tail->prior;
  tail->next = NULL;
 }
  free(p);

}
//控制方向
enum dir{up=0,down,l,r};
dir point;
int food_x;
int food_y;
void change_Point(char keydown)
{
 switch (keydown)
 {
 case ‘w‘: point = up; break;
 case ‘s‘: point = down; break;
 case ‘a‘: point = l; break;
 case ‘d‘: point = r; break;

 }

}

//随机食物
void get_food()
{
 srand((unsigned int)time(NULL));
 food_x = rand() % 18 + 1;
 food_y = rand() % 18 + 1;
 game[food_x][food_y] = ‘*‘;


}

//移动更新位置

void moving()
{
 int a, b;
 a = get_i(head);
 b = get_j(head);
 cout << point << endl;
 switch (point)
 {
 case up: --a; break;
 case down: ++a; break;
 case l: --b; break;
 case r: ++b; break;


 }
 if (a == 19 || b == 19 || a == 0 || b == 0)
 {
  cout << "game over" << endl;
  exit(0);
 }

 if (a == food_x && b == food_y)
 {
  add_head(a, b, head);
  get_food();
 }
 else
 {
  add_head(a, b, head);
  delete_tail();
 }
}
int main()
{
 cout << "Using w,s,a,d, to contrl direction"<<endl;
 InitFace();
 add_head(17, 10, head);
 add_head(17, 11, head);
 add_head(17, 12, head);
 get_food();
 OutputF();
 
 while (true)
 {
  
  char keydown= _getch();
  cout <<"input" <<keydown << endl;

  change_Point(keydown);

   while (!_kbhit())  //kbhit()在执行时,检测是否有按键按下,有按下返回非0值,没有按下则返回0,是非阻塞函数;
  {
   system("cls");
   moving();
   OutputF();
   Sleep(800);
  }
  

 }
 return 0;
}
/*
控制台闪屏厉害
*/

贪吃蛇

标签:change   rand   nio   and   int   bsp   sse   over   cti   

原文地址:https://www.cnblogs.com/countryboy666/p/11026178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!