c++贪吃蛇游戏
一、源代码
1、头文件
snake.h
#ifndef SNAKE_H
#define SNAKE_H
class Snake
{
public:
Snake(){
row=0;col=0;num=0;}
Snake(int r,int c,int n){
row=r;col=c;num=n;}
int returnr();
int returnc();
int returnn();
void setr(int);
void setc(int);
void setn(int);
private:
int row;
int col;
int num;
};
#endif
2、Snake类的成员函数定义
snake.cpp
#include <iostream>
#include <iomanip>
#include "snake.h"
using namespace std;
int Snake::returnr()
{
return row;
}
int Snake::returnc()
{
return col;
}
int Snake::returnn()
{
return num;
}
void Snake::setr(int r)
{
row=r;
}
void Snake::setc(int c)
{
col=c;
}
void Snake::setn(int n)
{
num=n;
}
3、用户源文件
client.cpp
#include <iostream>
#include <iomanip>
#include <windows.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include "snake.h"
#define LEN 20
#define WID 40
#define INILEN 5
#define UP 'w'
#define DOWN 's'
#define LEFT 'a'
#define RIGHT 'd'
#define PAUSE ' '
#define EXIT '0'
#define CONTINUE '1'
using namespace std;
// menu function
char menu()
{
char ch;
cout<<"Welcome to gluttonous snake!"<<endl<<endl
<<"1.Start Game 0.exit"<<endl<<endl
<<"Please enter your choice:"<<endl;
cin>>ch;
while(ch!='0'&&ch!='1')
{
cout<<"Error! Please enter your choice again:"<<endl;
cin>>ch;
}
return ch;
}
//initialize the map
void inimap(char **s)
{
int i=0,j=0;
for(i=0;i<LEN;i++)
for(j=0;j<WID;j++)
if(i==0||i==LEN-1) s[i][j]='*';
else if(j==0||j==WID-1) s[i][j]='*';
else s[i][j]=' ';
}
//initialize the snake
void inisnake(Snake *sk[(LEN-2)*(WID-2)])
{
int r=0,c=0,i=0,n=1;
//蛇身纵坐标1~18
srand((unsigned)time(NULL));
r=rand()%(LEN-2)+1;
//蛇身横坐标1~36
srand((unsigned)time(NULL));
c=rand()%(WID-5)+1;
sk[0]=new Snake(r,c,n);
for(int i=1;i<INILEN;i++)