⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 snake游戏.cpp

📁 一个用C++实现的游戏程序
💻 CPP
字号:
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <stdio.h>

#define BEAN  rand()%3+2

//using namespace std;

volatile char key='w';
volatile char delay=0;

void setDelay(char a)
{
	switch(a)
	{
	    case '1':
			delay=125;
			break;
		case '2':
			delay=60;
			break;
		case '3':
			delay=30;
			break;
		case '4':
			delay=15;
			break;
		case '5':
			delay=1;
			break;
	}
}//--------------------end of setDelay------------------

void control()
{
	char temp;
	while(key!=' ')
	{
		temp=getch();
		if(key=='w' || key=='s'||key=='W'||key=='S')
		{
			if(temp=='a'||temp=='A'|| temp=='d'|| temp=='D')
				key=temp;
		}else if(key=='a' || key=='A'||key=='d'||key=='D')
		{
			if(temp=='w'||temp=='W'|| temp=='s'|| temp=='S')
				key=temp;
		}
	}
}//---------------end of thread function------------------

template <class T>
class  Queue;

class Point
{
friend class Queue<Point>;
friend class SMatrix;
private:
    int x;
    int y;
    char flag;
    Point():x(0),y(0),flag(0){}
    Point(int x,int y):x(x),y(y),flag(1){}
    Point& operator =(const Point &pt)
    {
        this->x=pt.x;
        this->y=pt.y;
        this->flag=pt.flag;
		return *this;
    }
};//---------------end of Point---------------------

template<class T>
class Queue                 //队列,用于广度优先算法的顶点缓冲,动态
{
friend class SMatrix;
private:
    typedef int Flag;
    const int space;
    int head;
    int tail;
    static const int MAX;
    T *body;
public:
    Queue();
    Queue(const int n);
    //暂时还没提供拷贝构造函数,需要小心使用
    ~Queue();
    void in(int x,int y);
    T out();
    int full();
    int empty();
    void dis();
    void check();
	void increase(int ,int);
	T first() const;
    const T& operator[](int i)
    {
        return body[i];
    }
};

template <class T>
const int Queue<T>::MAX=1000;

template <class T>
Queue<T>::Queue():space(100),head(0),tail(0)
{
    body=new T[space];
}
template <class T>
Queue<T>::Queue(const int n):space(n),head(0),tail(0)
{
    if(n>MAX)
    {
		std::cout<<"queue to lang\n";
        return;
    }
    body=new T[space];
}

template <class T>
Queue<T>::~Queue()
{
    if(body!=NULL)
    delete body;
}

template<class T>
inline int Queue<T>::full()
{
    if(tail==space-1)return 1;
    else return 0;
}

template<class T>
inline int Queue<T>::empty()
{
    if(tail!=head)return 0;
    else return 1;
}


template<class T>
inline void Queue<T>::in(int x,int y)
{
    if(this->full())
    {
		std::cout<<"queue full\n";
        return;
    }
    body[tail].x=x;
    body[tail].y=y;
    body[tail].flag=1;
    tail++;
}

template<class T>
inline T Queue<T>::first() const
{
    return body[head];
}

template<class T>
inline T Queue<T>::out()
{
    T node;
    int i;
    if(this->empty())
    {
		std::cout<<"queue empty\n";
        return *(new Point);
    }
    node = body[head];
    for(i=head;i<=tail;i++)
        body[i]=body[i+1];
    body[tail].flag=0;
    tail--;
    return node;
}

template <class T>
inline void Queue<T>::increase(int x,int y)
{
	if(this->full())return;
	for(int i=tail-1;i>=0;i--)
		body[i+1]=body[i];
    body[head].x=x;
	body[head].y=y;
}

template <class T>
inline void Queue<T>::dis()
{
    int i=0;
    while(body[i].flag!=0)
    {
		std::cout<<"("<<body[i].x<<","<<body[i].y<<")"<<' ';
        i++;
    }
	std::cout<<'\n';
}

template <class T>
inline void Queue<T>::check()
{
    std::cout<<"queue body: ";
    for(int i=head;i<space;i++)
        std::cout<<"("<<body[i].x<<","<<body[i].y<<")"<<' ';
    std::cout<<'\n';
}//-----------end of Queue-----------------------

class SMatrix                      //邻接矩阵,方阵,动态
{
private:
    char **m;
    int row;
    int posi;
    int posj;
    int bx;
    int by;
    int haveB;
	int score;
	char bb;
    Queue<Point> snake;
	static const char HEAD;
    static const char BGD;
    static const char ABAR;
    static const char BBAR;
//    static const char BEAN;
	static const char BODY;
    static const int POI;
public:
    SMatrix();
    SMatrix(const int n);
    ~SMatrix();
    int get(int i,int j) const;
    void set(int,int,int e=1);
    void dis() const;
	void move(char c);
	void reset();
	void fresh();
	void bean();
	void noBean();
	void setSnake();
	int inSnake(int x,int y);
	void dead();
};

const char SMatrix::HEAD=1;
const char SMatrix::BGD=' ';
const char SMatrix::ABAR=3;
const char SMatrix::BBAR=3;
//const char SMatrix::BEAN=3;
const char SMatrix::BODY=15;
const int SMatrix::POI=9;

SMatrix::SMatrix()
{
    m=NULL;
    row=0;
    posi=posj=0;
    bx=0;
    by=0;
	score=0;
	bb=0;
}

SMatrix::SMatrix(const int n):row(n),posi(row/2),posj(row/2),bx(0),by(0),haveB(0),snake(row*row/2),score(0),bb(0)
{
	m=new char*[n];
    for(int i=0;i<n;i++)
    {
        m[i]=new char[n];
        for(int j=0;j<n;j++)
            
            {
                if(i==0 || i==row -1)
                    m[i][j]=ABAR;
                else if(j==0 || j==row -1)
                    m[i][j]=BBAR;
                else m[i][j]=BGD;
            }
    }
    m[posi][posj]=HEAD;
    
}

SMatrix::~SMatrix()
{
    if(m!=NULL)
        for(int i=0;i<row;i++)
        {
            delete m[i];
            m[i]=NULL;
        }
    
}

inline void SMatrix::reset()
{
    for(int i=0;i<row;i++) 
        for(int j=0;j<row;j++)
            {
                if(i==0 || i==row -1)
                    m[i][j]=ABAR;
                else if(j==0 || j==row -1)
                    m[i][j]=BBAR;
                else m[i][j]=BGD;
            }
    posi=posj=row/2;
	if(haveB)
		m[bx][by]=BEAN;
    m[posi][posj]=BGD; 
}

void SMatrix::setSnake()
{
    for(int i=0;i<snake.tail;i++)
	{
		if(i==snake.tail-1)
			m[snake[i].x][snake[i].y]=HEAD;
		else m[snake[i].x][snake[i].y]=BODY;
	}
}

void SMatrix::dead()
{
	for(int j=1200;j<300;j--)
	{
		Beep(j,100);
        Sleep(100);
	}
    this->setSnake();
    this->dis();
    std::cout<<"game over!\n";
    std::cout<<"得分:"<<score<<'\n';
    key=' ';
}

void SMatrix::move(char c)
{
     Point p;
	 if(snake.empty())
         snake.in(posi,posj);
	 this->setSnake();
//     this->dis();

         if (posi==row-1 || posj== row -1 || posi==0 || posj==0)
         {
			 this->dead();
         }
//         cout<<"请输入移动方向(w,s,a,d):\n";
//         cout<<"x,y,row:"<<posi<<' '<<posj<<' '<<row<<'\n';
         switch(c)
         {
		     case 'W':
             case 'w':
                    system("cls");
				    if(this->inSnake(posi-1,posj))
                    {
						this->dead();
					}					
					snake.in(posi-1,posj);
				    if(m[posi-1][posj]!=bb)
					{
                        p=snake.out();
						
					}else
					{
						score+=POI;
						Beep (500,50);
						p=snake.first();
                        this->noBean();
					}
                    if(m[p.x][p.y]!=bb)
                        this->set(p.x,p.y,BGD);               
                    this->setSnake();
                    this->dis();
					posi--;
					if(!haveB)
					   this->bean();
					//snake.dis();
					break;
			 case 'S':
             case 's':
                    system("cls");
                    if(this->inSnake(posi+1,posj))
                    {
						this->dead();
					}
					snake.in(posi+1,posj);

                    if(m[posi+1][posj]!=bb)
					{
                        p=snake.out();
					}else
					{
						score+=POI;
						Beep (500,50);
						p=snake.first();
                        this->noBean();
					}
                    if(m[p.x][p.y]!=bb)
                        this->set(p.x,p.y,BGD);               
                    this->setSnake();
                    this->dis();			
					posi++;
					if(!haveB)
					   this->bean();
					break;
			 case 'A':
             case 'a':
                    system("cls");
				   
					
					 if(this->inSnake(posi,posj-1))
                    {
						this->dead();
					}
					 snake.in(posi,posj-1);
                    if(m[posi][posj-1]!=bb)
					{
                        p=snake.out();
					}else
					{
						score+=POI;
						Beep (500,50);
						p=snake.first();
                        this->noBean();
					}
                    if(m[p.x][p.y]!=bb)
                        this->set(p.x,p.y,BGD);               
                    this->setSnake();
                    this->dis();
					posj--;
					if(!haveB)
					   this->bean();
					break;
			 case 'D':
             case 'd': 
                    system("cls");
					
					if(this->inSnake(posi,posj+1))
                    {
						this->dead();
					}
					snake.in(posi,posj+1);
                    if(m[posi][posj+1]!=bb)
					{
                        p=snake.out();
					}else
					{
						score+=POI;
						Beep (500,50);
						p=snake.first();
                        this->noBean();
					}
                    if(m[p.x][p.y]!=bb)
                        this->set(p.x,p.y,BGD);               
                    this->setSnake();
                    this->dis();
					posj++;
					if(!haveB)
					   this->bean();
					break;
            default:return;    
         }

}

inline int SMatrix::inSnake(int x,int y)
{
	int i=snake.head;
    while(snake.body[i].flag!=0)
	{
		if(x==snake.body[i].x && y==snake.body[i].y)
			return 1;
		i++;
	}
    return 0;
}

inline void SMatrix::bean()
{
	do{
       bx=(rand()%(row-3)+1);
       by=(rand()%(row-3)+1);
	}while(this->inSnake(bx,by));
    m[bx][by]=bb=BEAN;
    haveB=1;
}

inline void SMatrix::noBean()
{
    if(bx && by)
        m[bx][by]=BGD;
    haveB=0;
}

inline void SMatrix::fresh()
{
     this->reset();
}



inline void SMatrix::dis() const
{
    std::cout<<"你是一个猪,哈哈: bean = "<<haveB<<","<<bb<<",bx,by:"<<bx<<" , "<<by<<"级别"<<(int)delay<<'\n';
    for(int i=0;i<row;i++)
    {
        for(int j=0;j<row;j++)
            //cout<<m[i][j]<<' ';
			printf("%c ",m[i][j]);
        std::cout<<'\n';
    }
}

inline void SMatrix::set(int i,int j,int e)
{
    m[i][j]=e;
}

inline int SMatrix::get(int i,int j) const
{
    if(m!=NULL)
		return m[i][j];
	else return -1;
}//--------------end of SMatrix-------------


int main()
{
    SMatrix S(18);
    S.bean();
    HANDLE tHandle;
	DWORD tID;
	std::cout<<"请输入难度(1-5):";
	char de=getch();
	setDelay(de);
	system("cls");
	std::cout<<"方向键开始游戏(w,s,a,d),空格键退出游戏";
//	while(key!='w'&&key!='W'&&key!='s'&&key!='S'&&key!='a'&&key!='A'&&key!='d'&&key!='D')
//    {
        key=getch();
//    }
    tHandle=CreateThread(0,0,(LPTHREAD_START_ROUTINE)control,0,0, &tID);
	while(key!=' ')
	{	
		S.move(key);
		Beep(200,20);
		Sleep(delay);
	}
	system("cls");
	S.dead();
	getchar();
    return 0; 
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -