C++ 实现贪吃蛇游戏

源码下载:点击下载

记得初学编程时,学习的第一个游戏就是贪吃蛇游戏,碍于技术有限,只能在一旁欣赏大神的代码,很疑惑是怎么做到控制蛇的移动和吃食物的,而且别人的程序思路也不是那么容易弄懂的,直到今天也是略知一二,且容我在程序说明中细细道来。

首先,蛇必须有身体,这里依然用的是Easy-X来做蛇身体和地图(障碍物)的绘制。

都是用小正方形来表示。程序中body.h和body.cpp做蛇身体控制部分。Snake.h和Snake.cpp是游戏逻辑控制。

在蛇的每一节身体使用链表的方式进行管理,其中在蛇移动的过程中,很容易发现,在蛇的移动的过程中,看上去只有头和尾的身体节点发生变化,所以我认为,在游戏过程中,没有必要在每一步的移动过程中都重绘一下整个蛇的身体,我们只需要在蛇的前进方向上的第一的身体节点前新绘制一个一个头,并把原来的头作为现在蛇靠最近头的一节身体,最后把原来的尾巴擦掉,把之前靠近尾巴的节身体作为现在的尾巴即可。总之,这样就只进行了蛇一节身体的绘制和擦除工作,这对程序界面响应是有很大帮助的。


当蛇吃到事物后,蛇的身体自动的增长一节但是,这一节身体在蛇身完全通过事物的坐标后才出现。

另外在产生蛇所吃的事物上,使用随机函数产生事物的有效的食物的坐标,即在预定的游戏界面之内。然后调用绘制函数绘制事物即可。

关于地图的绘制,使用读取本地txt文件的方式读取本地的地图数据,小畔在这里在txt文件中用0和1来表示在游戏界面中某一个点是否有障碍。0表示无障碍,1表示有障碍,在程序中读取文件,然后将地图数据存储到数组中,最后绘制地图的函数只需要按照这个数组中的地图蓝板进行绘制即可。地图数据文件如下图。


同时障碍和游戏结束的判断息息相关,使用的是将蛇的身体的每一节身体坐标和地图进行比对,有过在有障碍的坐标处同时出现蛇的身体坐标及判断出蛇碰到了障碍物,游戏结束。

在蛇的移动中,如果没有按方向键的话,蛇会在原有的方向上继续保持移动的态势,所以程序中做的是一个每隔一段时间判断蛇目前的前进方向,然后根据目前的前进方向,按照上面所诉的蛇身体的控制方法进行移动。按键控制反向,只是改变蛇目前的移动方向。

以上是这个游戏中比较重要的几个点。话不多说,直接上代码:

body.h & body.cpp

#ifndef __BODY_H_
#define __BODY_H_
#include <graphics.h>
#include <conio.h>
#include <stdio.h>

class Body
{
	int x;
	int y;
	int width;
	COLORREF color;
	int stat;
	Body *next;
public:
	enum Statu{ON, OFF};
public:
	Body(int x = 0, int y = 0, int width = 10, COLORREF color = WHITE, Body *next = NULL, int stat = ON);
	void setX(int x);
	void setY(int y);
	int getX();
	int getY();
	void setColor(COLORREF color);
	COLORREF getColor();
	void setNext(Body *next);
	Body *getNext();
	void setStat(int stat);
	int getStat();
	void update();
	void moveLeft();
	void moveRight();
	void moveUp();
	void moveDown();
};
#endif
#include "body.h"

Body::Body(int x, int y, int width, COLORREF color, Body *next, int stat)
{
	this->x = x;
	this->y = y;
	this->width = width;
	this->color = color;
	this->next = next;
	this->stat = stat;
}

void Body::setX(int x)
{
	this->x = x;
}
void Body::setY(int y)
{
	this->y = y;
}
int Body::getX()
{
	return x;
}
int Body::getY()
{
	return y;
}
void Body::setColor(COLORREF color)
{
	this->color = color;
}
COLORREF Body::getColor()
{
	return color;
}
void Body::setNext(Body *next)
{
	this->next = next;
}
Body* Body::getNext()
{
	return next;
}
void Body::setStat(int stat)
{
	this->stat = stat;
}
int Body::getStat()
{
	return stat;
}

void Body::update()
{
	if (stat == ON)
	{
		setfillcolor(WHITE);
		setlinecolor(RED);
	}
	else
	{
		setfillcolor(BLACK);
		setlinecolor(BLACK);
	}
	fillrectangle(x, y, x+ width, y + width);
}
void Body::moveLeft()
{
	x -= 10;
}
void Body::moveRight()
{
	x += 10;
}

void Body::moveUp()
{

	y -= 10;
}
void Body::moveDown()
{
	y += 10;
}

Snake.h & Snake.cpp

#ifndef __SANKE_H_
#define __SNAKE_H_
#include "body.h"

#ifndef _SCREEN_SIZE_
#define _SCREEN_SIZE_
#define WIDTH 640
#define HEIGHT 480
#endif

class Snake
{
	Body *head;
	int dir;
	int foodX;
	int foodY;
	enum Direction{UP, DOWN, LEFT, RIGHT};
	char map[48][65];  //注意地图文件多一个换行符
public:
	Snake(int x = 100, int y =  50, int dir = DOWN);
	void update();
	void setDir(int dir);
	void move();
	void start();
	void getFoodLocation(int &x, int &y);
	void createFood();
	bool isTouchFood();    //判断是否碰到事物
	void eatFoodAddBody(); // 吃食物长身体
	bool isGameOver();
	void initMap();
	bool isTouchMap();
};
#endif
#include "Snake.h"
#include <Windows.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>

Snake::Snake(int x, int y, int dir)
{
	head = new Body(x, y);
	head->setNext(new Body(x,y-10));
	this->dir = dir;
	foodX = -1;
	foodY = -1;
}

void Snake::start()
{
	update();
	int ch = 0;

	createFood(); // 初始食物
	while (1)
	{
		if (_kbhit())
		{
			ch = _getch();     // 一个方向键要用两个getch才能获取完
			if (ch == 0xe0)   //如果高位相等
			{
				ch = _getch(); //那么再获取一个
				switch (ch)
				{
				case  0x004b: if (dir != RIGHT) dir = LEFT; break; // 设置蛇的移动方向
				case  0x004d: if (dir != LEFT) dir = RIGHT; break;
				case  0x0048: if (dir != DOWN) dir = UP;  break;
				case  0x0050: if (dir != UP)   dir = DOWN; break;
				}
			}
			//move();
		}
		move();
		if (isTouchFood())
		{
			eatFoodAddBody();  //长身体
			createFood(); // 产生新的食物
		}
		Sleep(100);
	}
}

void Snake::setDir(int dir)
{
	this->dir = dir;
}

void Snake::update()
{
	Body *p = head;
	do
	{
		p->update();
		p = p->getNext();
	} while (p != NULL);
}


void Snake::move()
{
	Body *p = head;
	Body *newTail = NULL;

	//找到蛇靠近尾部的那个节点
	while (p->getNext()->getNext()!= NULL)
	{
		p = p->getNext();
	}
	newTail = p;
	p = p->getNext();
	newTail->setNext(NULL);//将新节点的下一个节点置空

	p->setStat(p->OFF); // 将原尾巴擦掉
	p->update();
   
	p->setX(head->getX());
	p->setY(head->getY());
	p->setNext(head->getNext());

	head->setNext(p);
	//更新蛇的头部
	switch (dir)
	{
	case LEFT:  head->moveLeft();   break;
	case UP:    head->moveUp();     break;
	case DOWN:  head->moveDown();   break;
	case RIGHT:  head->moveRight(); break;
	}

	if (isGameOver())
	{
		LOGFONT f;
		gettextstyle(&f);                     // 获取当前字体设置
		f.lfHeight = 48;                      // 设?米痔甯叨任? 48
		_tcscpy_s(f.lfFaceName, _T("方正舒体"));    // 设置字体为(高版本 VC 推荐使用 _tcscpy_s 函数)
		f.lfQuality = ANTIALIASED_QUALITY;    // 设置输出效果为抗锯齿  
		settextstyle(&f);                     // 设置字体样式
		outtextxy(100, 200, _T("蛇撞死了 Game Over"));
		Sleep(5000);
		exit(0);
	}
	head->update();    // 重绘新的头
}

void Snake::getFoodLocation(int &x, int &y)
{
	Body * p = NULL;
	int mapy = 0;
	int mapx = 0;
	srand(time(NULL)); // 设置随机数种子

	while (1)
	{
		x = (rand() % (WIDTH - 10)) / 10 *10;  // 在指定的范围内产生随机数(屏幕范围内)并取10的倍数
		y = (rand() % (HEIGHT - 10))/ 10 * 10;

		p = head;
		while (p != NULL)                                     //是否是身体
		{
			if (p->getX() == x && p->getY() == y)
			{
				p = head;
				break;
			}
			p = p->getNext();
		}
		for (int i = 0; i < 48; i++  ) // 是否是墙
		{
			mapy = i * 10;
			for (int j = 0; j < 64; j++)
			{
				if (map[i][j] == '1')
				{
					mapx = j * 10;
					if (x == mapx && y == mapy)
					{
						p = head;
						break;
					}
				}
			}
			if (p == head)
			{
				break;
			}
		}
		if (p == NULL)   //遍历之后,满足食物坐标不是身体坐标的条件,则返回,否则生成新的事物坐标
		{
			return;
		}
	}
}

void Snake::createFood()
{
	//得到事物坐标
	getFoodLocation(foodX, foodY);

	setfillcolor(YELLOW);// 设置填充颜色
	setlinecolor(GREEN);// 设置划线颜色
	fillrectangle(foodX, foodY, foodX + 10, foodY + 10);
}


bool Snake::isTouchFood()  //判断是否碰到事物
{
	Body *p = head;

	if (p->getX() == foodX && p->getY() == foodY)
	{
		return true; // 如果碰到食物
	}
	return false;
}

void Snake::eatFoodAddBody() 
{
	Body *p = head;

	//在身体的后面加一个身体,实际上坐标和原尾巴坐标一致,这样就会使蛇在下一次移动长长一节

	while ( p->getNext() != NULL)//找到尾巴
	{
		p = p->getNext();
	}

	Body *newBody = new Body(p->getX(), p->getY());

	p->setNext(newBody);
	newBody->setNext(NULL);
}


bool Snake::isGameOver()
{
	Body *p = head;
	Body *q = p ->getNext();

	int x;
	int y;

	while (q != NULL)
	{
		x = p->getX();
		y = p->getY();
		if (x == q->getX() && y == q->getY()) // 头碰到了自己的身体 die
		{
			return true;
		}
		if (x < 0 || y < 0 || x >= WIDTH || y >= HEIGHT)  // 头撞向边界, 并且头都跑出去了
		{
			return true;
		}
		if (isTouchMap())  //碰到了地图
		{
			return true;
		}

		q = q->getNext();
	}
	return false;
}

void Snake::initMap()
{
	FILE *fp = NULL;
	int x = 0;
	int y = 0;
	fopen_s(&fp, "Map/map1.txt", "r ");   // 只读方式打开文件
	if (fp == NULL)
	{
		printf("地图文件打开失败\n");
		return;
	}
	else
	{
		printf("地图文件打开成功, 文件编号:%d\n", fp);
	}

	//fread(map, 1, 64*48, fp);
	for (int i = 0; i < 48; i++)
	{
		for (int j = 0; j < 65; j++)
		{
			map[i][j]=fgetc(fp);
		}
	}
	//根据地图文件生成地图
	setfillcolor(BROWN);
	setlinecolor(BLACK);
	for (int i = 0; i < 48; i++)
	{
		y = i*10; 
		for (int j = 0; j < 64; j++)
		{
			//printf("%c", map[i][j]);
			if (map[i][j] == '1')
			{
				x = j*10; 
				fillrectangle(x, y, x + 10, y + 10);
			}
		}
	}
	fclose(fp);
}

bool Snake::isTouchMap()
{
	Body *p = head;
	int px = p->getX();
	int py = p->getY();
	int mapx = 0;
	int mapy = 0;

	for (int i = 0; i < 48; i++)
	{
		mapy = i * 10;
		for (int j = 0; j < 64; j++)
		{
			if (map[i][j] == '1')
			{
				mapx = j * 10;
				if (px == mapx && py == mapy)
				{
					return true;
				}
			}
		}
	}
	return false;
}

main.cpp

#include <iostream>
#include <graphics.h>
#include <conio.h>
#include "body.h"
#include "Snake.h"

#ifndef _SCREEN_SIZE_
#define _SCREEN_SIZE_
#define WIDTH 640
#define HEIGHT 480
#endif

using namespace std;

int main()
{
	initgraph(640, 480, SHOWCONSOLE);

	Snake snake;
	snake.initMap();
	snake.start();
	
	_getch();
	return 0;
}


注:程序运行之前需要事先安装好Easy-X 哦 偷笑

程序运行效果如下:

 

  • 24
    点赞
  • 91
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
以下是一个简单的 C++ 贪吃游戏代码,仅供参考: ```c++ #include <iostream> #include <cstdlib> #include <ctime> #include <conio.h> #include <windows.h> using namespace std; const int width = 20; const int height = 20; int snakeX[100], snakeY[100]; // 贪吃身体的坐标 int fruitX, fruitY; // 水果的坐标 int snakeLength = 3; // 贪吃的长度 enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN }; // 贪吃的方向 eDirection dir; bool gameOver; // 游戏是否结束 void Setup() { // 初始化游戏 gameOver = false; dir = STOP; snakeX[0] = width / 2; snakeY[0] = height / 2; fruitX = rand() % width; fruitY = rand() % height; } void Draw() { // 绘制游戏界面 system("cls"); // 清屏 for (int i = 0; i < width + 2; i++) cout << "#"; cout << endl; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (j == 0) cout << "#"; if (i == snakeY[0] && j == snakeX[0]) cout << "O"; else if (i == fruitY && j == fruitX) cout << "F"; else { bool print = false; for (int k = 1; k < snakeLength; k++) { if (snakeX[k] == j && snakeY[k] == i) { cout << "o"; print = true; } } if (!print) cout << " "; } if (j == width - 1) cout << "#"; } cout << endl; } for (int i = 0; i < width + 2; i++) cout << "#"; cout << endl; } void Input() { // 处理用户输入 if (_kbhit()) { // 判断是否有按键输入 switch (_getch()) { // 获取按键输入 case 'a': dir = LEFT; break; case 'd': dir = RIGHT; break; case 'w': dir = UP; break; case 's': dir = DOWN; break; case 'x': gameOver = true; break; } } } void Logic() { // 处理游戏逻辑 int prevX = snakeX[0]; int prevY = snakeY[0]; int prev2X, prev2Y; snakeX[0] = snakeX[0] + (dir == RIGHT) - (dir == LEFT); snakeY[0] = snakeY[0] + (dir == DOWN) - (dir == UP); for (int i = 1; i < snakeLength; i++) { prev2X = snakeX[i]; prev2Y = snakeY[i]; snakeX[i] = prevX; snakeY[i] = prevY; prevX = prev2X; prevY = prev2Y; } if (snakeX[0] == fruitX && snakeY[0] == fruitY) { // 判断是否吃到水果 snakeLength++; fruitX = rand() % width; fruitY = rand() % height; } for (int i = 1; i < snakeLength; i++) { // 判断是否碰到自己或墙壁 if (snakeX[i] == snakeX[0] && snakeY[i] == snakeY[0]) gameOver = true; } if (snakeX[0] >= width || snakeX[0] < 0 || snakeY[0] >= height || snakeY[0] < 0) gameOver = true; } int main() { srand(time(0)); // 随机数种子 Setup(); // 初始化游戏 while (!gameOver) { // 游戏循环 Draw(); // 绘制游戏界面 Input(); // 处理用户输入 Logic(); // 处理游戏逻辑 Sleep(100); // 休眠一定时间,控制游戏速度 } return 0; } ``` 这个代码实现贪吃游戏比较简单,游戏界面由 "#" 和空格组成, "#" 代表墙壁, "O" 代表贪吃头部, "o" 代表贪吃身体, "F" 代表水果。贪吃的方向由用户输入的 "a"、 "d"、 "w"、 "s" 控制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值