c++入门小程序:1.今日活动计划

/*函数名:kbhit()功能及返回值: 检查当前是否有键盘输入,若有则返回一个非0值,否则返回0。
用 法:int kbhit(void);C++语言包含头文件:include <conio.h>。
2020.7.9 已弃用 kbhit(),需替换为_kbhit()。
C语言不需包含额外头文件。在VC++6.0下为_kbhit()。功能及返回值同上。*/

#include<windows.h>
#include<iostream>
#include<conio.h>//提供了kbhit()函数
using namespace std;

class RandChoice
{
    
    
private:
	char option[6][20];
	short size;//记录当前可选择数
	HANDLE handle_out;
	COORD crd;
	short pointer;//保存当前箭头指向选项的下标
	short delay;//箭头切换位置的延时时间
public:
	RandChoice(const char* option1, const char* option2, const char* option3 = NULL,
		const char* option4 = NULL, const char* option5 = NULL, const char* option6 = NULL)
	{
    
    
		pointer = 0;
		strcpy_s(option[0], option1);
		strcpy_s(option[1], option2);
		size = 2;
		handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
		crd.X = 5;
		crd.Y = 4 + (pointer << 1);//向左移1相当于乘以2
		if (option3 != NULL)
		{
    
    
			strcpy_s(option[2], option3);
			size++;
		}
		if (option4 != NULL)
		{
    
    
			strcpy_s(option[3], option4);
			size++;
		}
		if (option5 != NULL)
		{
    
    
			strcpy_s(option[4], option5);
			size++;
		}
		if (option6 != NULL)
		{
    
    
			strcpy_s(option[5], option6);
			size++;
		}

	}

	void Start()//显示出选项
	{
    
    
		cout << "\n你今天的活动安排是什么?来做个选择吧。\n\n\n";
		for (short i = 0; i < size; i++)
			cout << "       " << option[i] << endl << endl;
	}

	void Refresh()//更新箭头的显示位置
	{
    
    
		SetConsoleCursorPosition(handle_out, crd);//将输出坐标定位在上一次显示箭头的位置
		cout << "  ";//擦掉上次输出的箭头
		pointer = (pointer + 1) % size;//让pointer值在0~size-1之间循环
		crd.Y = 4 + (pointer << 1);
		SetConsoleCursorPosition(handle_out, crd);//将输出坐标定位在新的位置
		cout << "->";
	}
	short SetDelay(short d) {
    
     return delay = d; }//设置延迟时间
	void Wait() {
    
     Sleep(delay); }

	short Play()
	{
    
    
		while (!_kbhit())
		{
    
    
			Refresh();//擦掉上一次画的箭头,并在新的位置画出箭头,更新pointer的值
			Wait();
		}
		return pointer;
	}
	void ShowResult()
	{
    
    
		crd.Y = 18;
		SetConsoleCursorPosition(handle_out, crd);
		cout << "今天就" << option[pointer] << "吧。这是天意!\n\n";
	}

};

int main()
{
    
    
	RandChoice rc("看电影", "写代码", "逛公园", "约会妹子", "睡懒觉");
	rc.SetDelay(100);
	char choice;
	do
	{
    
    
		system("cls");//清屏
		rc.Start();//重新显示选项
		rc.Play();
		rc.ShowResult();
		_getch();
		cout << "是否再来一次?(y/n)";
		cin >> choice;
	} while (choice == 'y' || choice == 'Y');
	return 0;
}

结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_60534571/article/details/130514473