BadApple(控制台改进版,消除闪烁)

向该老哥的代码学习了一手,原地址

具体思路还是与上次的那个一样

#include 
#include 
#include 
#include 
#include 

#pragma comment(lib, "winmm.lib")

using namespace std;

#define DATAFILE "BadApple.txt"

#define FRAME_WIDTH		80
#define FRAME_HEIGHT	32

#define DATA_TOKEN_SIZE	( 5 + 1 )	//	$0000\n
#define DATA_PITCH_SIZE	( FRAME_WIDTH + 1 )		// ###...\n
#define DATA_FRAME_SIZE	( DATA_TOKEN_SIZE + ( DATA_PITCH_SIZE * FRAME_HEIGHT ) )

#define FRAME_COUNT	3271

#define VIDEO_TIME	218000.0f	// 3:38 (218000ms)


int main()
{
	HANDLE hOutput;

	hOutput = GetStdHandle(STD_OUTPUT_HANDLE);

	CONSOLE_CURSOR_INFO coc = { 1, FALSE };
	COORD co = { FRAME_WIDTH, FRAME_HEIGHT };
	SMALL_RECT rc = { 0, 0, FRAME_WIDTH - 1, FRAME_HEIGHT - 1 };			//设置控制台的大小

	SetConsoleCursorInfo(hOutput, &coc);
	SetConsoleScreenBufferSize(hOutput, co);							//重要点:设置缓冲,消除闪烁
	SetConsoleWindowInfo(hOutput, TRUE, &rc);							//实习控制台的大小

	SetConsoleTitle(L"Bad Apple");
	FILE	*fp;
	int		size;
	char	*buf;
	char	*cur;
	int		start;

	buf = NULL;
	errno_t err = fopen_s(&fp, DATAFILE, "rb");
	if (err)
	{
		printf("%s not found.\n", DATAFILE);
		goto err;
	}

	size = DATA_FRAME_SIZE * FRAME_COUNT;	// Data size per frame (2598)

	buf = new char[size];

	if (fread_s(buf,size-1, size - 1, 1, fp) != 1)
	{
		printf("Failed to read in data file.\n");
		goto err;
	}

	buf[size - 1] = '\0';

	fclose(fp);

	mciSendString(L"open BadApple.wma alias BGM", NULL, 0, NULL);		//加载音频资源
	mciSendString(L"play BGM", NULL, 0, NULL);							//播放音频

	start = GetTickCount();

	while (1)
	{
		int		time;
		float	percen;
		int		frame;
		COORD	xy = { 0, 0 };
		DWORD	written;

		time = GetTickCount();
		percen = (time - start) / VIDEO_TIME;

		if (percen > 1)
		{
			printf("End of play.\n");
			break;
		}

		frame = percen * FRAME_COUNT;								//计算下一次所需要的字符个数
		cur = &buf[(DATA_FRAME_SIZE * frame) + DATA_TOKEN_SIZE];  //不断更新地址

		for (; xy.Y < FRAME_HEIGHT; xy.Y++, cur += DATA_PITCH_SIZE)
			WriteConsoleOutputCharacterA(hOutput, cur, DATA_PITCH_SIZE - 1, xy, &written);		//在控制台上显示

		Sleep(60);
	}

	mciSendString(L"stop", NULL, 0, NULL);							//停止播放音频
	mciSendString(L"close", NULL, 0, NULL);

err:
	if (buf)
		delete[] buf;

	Sleep(500);

	return 0;
}

代码逻辑结构不是特别好。
链接:https://pan.baidu.com/s/1eE2LP7smfrBpc7bdrVlnRw
提取码:sh4d
CSDN下载

你可能感兴趣的:(随笔)