C++实现贪吃蛇小游戏分析

Windows、VS2017、不用图形库。

链接:点这里 密码:n5nc

C++基础学习完后的小项目课程。


首先在cmd这个黑框框下绘制图像还是一样,定位,设置颜色,输出形状。我们要有一个工具类,来帮助我们定位,设置颜色(前景色&后景色),隐藏光标,设置标题等……在我们后面要重复利用到这里的工具函数,可以省一些事情。

Tools.h 

//Tools.h
#pragma once
#include <iostream>
#include <Windows.h>
using namespace std;
void set_windows_size(int x, int y);
void hide_cursor();
void set_cursor_position(const int x, const int y);
void set_text_color(int color_id);
void set_background_color();

 Tools.cpp

#include "stdafx.h"
#include "Tools.h"

//设置窗口
void set_windows_size(int x, int y)
{
	system("title GAME");	//设置窗口标题
	char cmd[30];	//存储cmd命令
	sprintf_s(cmd, "mode con cols=%d lines=%d", x * 2, y);//拼接命令//x*2是因为在cmd中字符是长的,一个字符的高=2*宽
	system(cmd);
}

//隐藏光标
void hide_cursor()
{
	CONSOLE_CURSOR_INFO cursor_info = { 1,0 };
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}

//设置光标坐标
void set_cursor_position(const int x, const int y)
{
	COORD position;
	position.X = x * 2;
	position.Y = y;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), position);
}

//设置文本颜色
void set_text_color(int color_id)
{
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_id);
}

//设置背景颜色、前景色
void set_background_color() 
{
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 
		FOREGROUND_BLUE|
		BACKGROUND_BLUE|
		BACKGROUND_GREEN|
		BACKGROUND_RED
	);
}

 


下来咋弄呢?我们要绘制地图,当然需要绘制点、方框什么的了,那在这个游戏里,点是一个二维点,我们创建一个Point的类,需要x,y两个成员变量,这个类可以根据xy绘制出正方形和圆形(还可以加别的形状)。在后面我们用方块来表示地图,开始界面动画,食物等。圆形用来表示蛇。

Point.h

#pragma once
class Point
{
public:
	Point():m_x(0),m_y(0){}
	Point(const int x,const int y):m_x(x),m_y(y){}
	void print_rect();	//输出方框 ■
	void print_circular();	//输出圆 ●

	void clear();
	void move(const int x,const int y);

	bool operator ==(const Point& point)
	{
		return (point.m_x == m_x) && (point.m_y == m_y);
	}
	int get_x()
	{
		return m_x;
	}
	int get_y()
	{
		return m_y;
	}
	
private:
	int m_x, m_y;
};

Point.cpp

#include "stdafx.h"
#include "Point.h"
#include "Tools.h"


void Point::print_rect()
{
	set_cursor_position(m_x, m_y);
	cout << "■";
}

void Point::print_circular()
{
	set_cursor_position(m_x, m_y);
	cout << "●";
}

void Point::clear()
{
	set_cursor_position(m_x, m_y);
	cout << " ";
}

void Point::move(const int x, const int y)
{
	m_x = x;
	m_y = y;
}

未完待续……

猜你喜欢

转载自blog.csdn.net/Hanoi_ahoj/article/details/81513325