c++贪吃蛇游戏

本文介绍了一款使用C++编写的贪吃蛇游戏。文章包含源代码的三个部分:头文件snake.h,Snake类的成员函数定义snake.cpp,以及用户源文件client.cpp。游戏可以通过w、s、a、d键进行上下左右移动,1键开始游戏,空格键暂停,0键退出。详细运行结果和操作说明可参考链接:[C++贪吃蛇游戏-哔哩哔哩](https://b23.tv/mhCJhg)。
摘要由CSDN通过智能技术生成

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++)
	
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安海yyz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值