贪吃蛇 - Windows10

#include <queue>
#include <random>
#include <conio.h>
#include <cstring>
#include <iostream>
#include <windows.h>
using namespace std;

class Game { // 游戏项目 
	string mp[30][30]; // 地图 
	string snakeHead = "■", snakeBody = "〇", foodCell = "★", emptyCell = "·", wallCell = "██"; // 标记 
	char dis; // 方向 
	int mpSize, runTime, snkSiz, randFut; // 大小,计时器,蛇长,随机果子 
	struct Pos { int x, y, type; }fut; // 节点位置结构体(type:1.蛇头,2.蛇身),果子 
	deque <Pos> qSnake; // 蛇
	
	// 地形(关卡) 【标记墙】 
	char emptyLevel[30][30] = {
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"...................."
	}, classicLevel[30][30] = {
		"####################",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"####################"
	}, godLevel[30][30] = {
		"...............#....",
		".............#......",
		"............#.......",
		"#..........#........",
		"..........#.........",
		".#........#.........",
		"..#......#..........",
		"...#.....#..........",
		"....##..............",
		"......##...##.......",
		"..............#.....",
		".........#.....#....",
		".........#......#...",
		"........#........#..",
		"........#...........",
		".......#..........#.",
		"......#.............",
		".....#.............#",
		"...#................",
		".#.................."
	}, trainLevel[30][30] = {
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"####################",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"...................."
	}, roundLevel[30][30] = {
		"....................",
		"....................",
		"..################..",
		"..#.................",
		"..#.................",
		"..#..#############..",
		"..#..#...........#..",
		"..#..#...........#..",
		"..#..#..#######..#..",
		"..#..#..#.....#..#..",
		"..#..#..#.....#..#..",
		"..#..#..####..#..#..",
		"..#..#........#..#..",
		"..#..#........#..#..",
		"..#..##########..#..",
		"..#..............#..",
		"..#..............#..",
		"..################..",
		"....................",
		"...................."
	}, painLevel[30][30] = {
		"###.################",
		"#..............#...#",
		"#.....#.....#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#.....#.........#",
		"######.#####.#######",
		"#..#.....#.........#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#.....#.....#......#",
		"###.#####.##########"
	};
	// 关卡结构体
	struct level {
		string name, introduction; // 名字、简介 
		int difficulty;  // 难度 
		char levelMap[30][30]; // 地图
		// 构造函数
		level(string Name, string Intro, int Diff, char Mapl[30][30]) {
			name = Name; introduction = Intro;
			difficulty = Diff;
			for (int i = 0; i < 20; ++i) {
				for (int j = 0; j < 20; ++j) {
					levelMap[i][j] = Mapl[i][j];
				}
			}
		}
		
		level() {
			name = "空白"; introduction = "幻术世界有什么不好\n现实太残酷,只会让这空洞越来越大……";
			difficulty = 0;
			for (int i = 0; i < 20; ++i) {
				for (int j = 0; j < 20; ++j) {
					levelMap[i][j] = '.';
				}
			}
		}
		
		void PrintLevelIntro() {
			for (int i = 0; i < 20; ++i) {
				cout << "\t\t";
				for (int j = 0; j < 20; ++j) {
					cout << (levelMap[i][j] == '.' ? "·" : "██");
				}
				cout << "\n";
			}
			
			// 把鼠标移动到左上角 
			HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	    	COORD coord = {0, 0};
	    	SetConsoleCursorPosition(hOut, coord);
			
			string Tab = "\t\t\t\t\t\t";
			cout << "\n\n\n\n\n";
			cout << Tab << "\t\t关卡名称:\t" << name << "\n\n";
			cout << Tab << "\t\t简介:\n\t\t" << Tab << introduction << "\n\n";
			cout << Tab << "\t\t难度:";
			for (int i = 0; i < difficulty; ++i)cout << "★ ";
			for (int i = difficulty; i < 5; ++i)cout << "☆ ";
		}
	};
	
	level levels[10];
	int levelNum;
	
	void InitLevel() {
		levelNum = 6;
		levels[0] = level("空洞", "幻术世界有什么不好\n\t\t\t\t\t\t\t\t现实太残酷,只会让这空洞越来越大……", 0, emptyLevel);
		levels[1] = level("空间", "黑暗中陨落的闪光……你已无处可逃……", 1, classicLevel);
		levels[2] = level("有限月读", "九尾就永远沉睡在无限月读之中吧", 1, trainLevel);
		levels[3] = level("神威", "你的逞强也就到此为止,可以退场了……", 3, godLevel);
		levels[4] = level("漩涡", "憎恨和痛楚,这一切都由我来承受吧!", 4, roundLevel);
		levels[5] = level("痛楚", "向神挑战是愚蠢的!", 5, painLevel);
	}
	
	void cls() { // 清屏 
	    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	    COORD coord = {0, 0};
	    SetConsoleCursorPosition(hOut, coord);
	}
	
	int randint(int l, int r) { // 随机数 
		static random_device rd;  // 真随机数生成器(部分平台可能伪随机)
		static mt19937 gen(rd()); // 用真随机种子初始化 mt19937 引擎
	    uniform_int_distribution<int> dist(l, r);
	    return dist(gen);
	}
	
	void init() { // 初始化 
		InitLevel();
		mpSize = 20; // 大小:20*20 
		dis = 'd'; // 初始方向:右 
		runTime = 0; // 计时器归零 
		randFut = randint(10, 500);
		snkSiz = 1; // 初始蛇身:1(只有蛇头) 
		fut.x = randint(0, mpSize - 1); // 随机初始化水果 
		fut.y = randint(0, mpSize - 1);
		qSnake.clear(); // 清空 
		qSnake.push_back({mpSize / 2, mpSize / 2, 1}); // 压入蛇头 
	}
	
	// 选择关卡 
	int ChooseLevel() { // 返回关卡 id
		int levelId = 0;
		while (1) {
			char keyDown;
			if (_kbhit()) {
				keyDown = getch();
				if (keyDown == 'a' && levelId > 0) --levelId;
				else if (keyDown == 'd' && levelId < levelNum - 1) ++levelId;
				else if (keyDown == 'q') break;
			}
			
			system("cls");
			cout << "\t====================  选择关卡  ====================\n\n";
			cout << "按下 a,d 选择上一个/下一个关卡\n按下 q 确认\n\n";
			levels[levelId].PrintLevelIntro();
			
			while (!_kbhit());
		}
		system("cls");
		return levelId;
	}
	
	// 填充地图 
	void FillMap(int levelId) { // 传入关卡 id 
		for (int i = 0; i < mpSize; ++i) {
			for (int j = 0; j < mpSize; ++j) {
				mp[i][j] = (levels[levelId].levelMap[i][j] == '.' ? emptyCell : wallCell);
			}
		}
	}
	
	void PrintMap(int levelId) { // 打印地图 
		// 按照选择的关卡填充地图 
		FillMap(levelId); 
		
		// 处理蛇 
		deque <Pos> copySnake(qSnake); 
		for (int node = 1; node <= snkSiz; ++node) { // snkSiz 个节点 
			Pos fot = copySnake.front();
			copySnake.pop_front();
			mp[fot.x][fot.y] = (fot.type == 1 ? snakeHead : snakeBody); // 修改地图 
		}
		
		// 处理果子
		--randFut;
		if (randFut == 0) { // 达到刷新时间 
			fut.x = randint(0, mpSize - 1);
			fut.y = randint(0, mpSize - 1);
			randFut = randint(10, 500);
		}
		if (mp[fut.x][fut.y] != emptyCell) { // 是否加分 
			qSnake.push_back({fut.x, fut.y, 2}); // 成为蛇身 
			++snkSiz; // 蛇长加一 
			while (mp[fut.x][fut.y] != emptyCell) { // 找到空位 
				fut.x = randint(0, mpSize - 1);
				fut.y = randint(0, mpSize - 1);
			}
		}
		mp[fut.x][fut.y] = foodCell; // 标记为果子
		
		cls(); // 清屏 
		for (int i = 0; i < mpSize; ++i) { // 打印地图 
			for (int j = 0; j < mpSize; ++j) {
				cout << mp[i][j];
			}
			cout << '\n';
		}
		
		// 打印得分 
		cout << "得分:" << snkSiz - 1; 
	}
	
	void ModifyPos(int xRf, int yRf) {
		qSnake.pop_back(); // 弹出蛇尾 
		Pos head = qSnake.front();
		qSnake.front().type = 2; // 把蛇头改为蛇身
		
		Pos newHead = {head.x + xRf, head.y + yRf, 1}; // 新蛇头 
		// 判断出界
		if (newHead.x < 0)newHead.x = mpSize - 1;
		else if (newHead.x >= mpSize)newHead.x = 0;
		if (newHead.y < 0)newHead.y = mpSize - 1;
		else if (newHead.y >= mpSize)newHead.y = 0; 
		// 判断游戏结束:撞到蛇身、墙 
		if (mp[newHead.x][newHead.y] == snakeBody)GameOver(1); // OverType = 1 表示撞到自己 
		if (mp[newHead.x][newHead.y] == wallCell)GameOver(2);  // OverType = 2 表示撞到墙 
		
		qSnake.push_front(newHead); 
	}
	
	void RefreshPos() { // 更新位置 
		if (_kbhit()) dis = getch(); // 有新按键按下
		if (runTime == 0) { // 达到刷新时间 
			if (dis == 'w') ModifyPos(-1, 0);
			else if (dis == 's') ModifyPos(1, 0);
			else if (dis == 'a') ModifyPos(0, -1);
			else if (dis == 'd') ModifyPos(0, 1);
		} 
	}
	
	void GameOver(int OverType) { // 游戏结束 
		int score = snkSiz - 1; // 分数 
		cls();
		cout << "\n\n\t\t\t\t\t========================== 游戏结束! ==========================\n\n";
		cout << "\t\t\t\t\t\tOps! 撞到" << (OverType == 1 ? "自己" : "墙") << "了!\n"; 
		cout << "\n\n\t\t\t\t\t\t最终得分:" << score << " 分\n\n";
		mpSize -= 5;
		while (mpSize--)cout << '\n';
		exit(0); 
	}
public:
	void RunGame() { // 游戏主循环 
		system("cls"); // 开始时清屏以免有什么不好的东西留在终端 
		init();
		cout << "========================== 贪吃蛇小游戏 ==========================\n\n";
		cout << "\t\t按下 wsad 控制蛇移动\n\t\t吃到果子“" << foodCell << "”可以加分\n\t\t撞到自己会失败!\n请确保你的输入法是英文小写状态\n\n按下任意键开始选择关卡\n";
		while (!_kbhit()); // 等待按下按键 
		system("cls");
		
		int levelId = ChooseLevel(); // 选择关卡 
		FillMap(levelId);
		
		// init(); // 初始化 
		while (1) {
			PrintMap(levelId);
			RefreshPos();
			++runTime; // 更新计时器 
			runTime %= 10;
		}
	}
};

int main() {
	Game Program;
	Program.RunGame();
	return 0;
}

贪吃蛇 - Windows11

#include <queue>
#include <random>
#include <conio.h>
#include <cstring>
#include <iostream>
#include <windows.h>
using namespace std;

class Game { // 游戏项目 
	string mp[30][30]; // 地图 
	string snakeHead = "■ ", snakeBody = "〇", foodCell = "★ ", emptyCell = "· ", wallCell = "██"; // 标记 
	char dis; // 方向 
	int mpSize, runTime, snkSiz, randFut; // 大小,计时器,蛇长,随机果子 
	struct Pos { int x, y, type; }fut; // 节点位置结构体(type:1.蛇头,2.蛇身),果子 
	deque <Pos> qSnake; // 蛇
	
	// 地形(关卡) 【标记墙】 
	char emptyLevel[30][30] = {
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"...................."
	}, classicLevel[30][30] = {
		"####################",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"#..................#",
		"####################"
	}, godLevel[30][30] = {
		"...............#....",
		".............#......",
		"............#.......",
		"#..........#........",
		"..........#.........",
		".#........#.........",
		"..#......#..........",
		"...#.....#..........",
		"....##..............",
		"......##...##.......",
		"..............#.....",
		".........#.....#....",
		".........#......#...",
		"........#........#..",
		"........#...........",
		".......#..........#.",
		"......#.............",
		".....#.............#",
		"...#................",
		".#.................."
	}, trainLevel[30][30] = {
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"####################",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"....................",
		"...................."
	}, roundLevel[30][30] = {
		"....................",
		"....................",
		"..################..",
		"..#.................",
		"..#.................",
		"..#..#############..",
		"..#..#...........#..",
		"..#..#...........#..",
		"..#..#..#######..#..",
		"..#..#..#.....#..#..",
		"..#..#..#.....#..#..",
		"..#..#..####..#..#..",
		"..#..#........#..#..",
		"..#..#........#..#..",
		"..#..##########..#..",
		"..#..............#..",
		"..#..............#..",
		"..################..",
		"....................",
		"...................."
	}, painLevel[30][30] = {
		"###.################",
		"#..............#...#",
		"#.....#.....#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#.....#.........#",
		"######.#####.#######",
		"#..#.....#.........#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#..#..#..#..#..#...#",
		"#.....#.....#......#",
		"###.#####.##########"
	};
	// 关卡结构体
	struct level {
		string name, introduction; // 名字、简介 
		int difficulty;  // 难度 
		char levelMap[30][30]; // 地图
		// 构造函数
		level(string Name, string Intro, int Diff, char Mapl[30][30]) {
			name = Name; introduction = Intro;
			difficulty = Diff;
			for (int i = 0; i < 20; ++i) {
				for (int j = 0; j < 20; ++j) {
					levelMap[i][j] = Mapl[i][j];
				}
			}
		}
		
		level() {
			name = "空白"; introduction = "幻术世界有什么不好\n现实太残酷,只会让这空洞越来越大……";
			difficulty = 0;
			for (int i = 0; i < 20; ++i) {
				for (int j = 0; j < 20; ++j) {
					levelMap[i][j] = '.';
				}
			}
		}
		
		void PrintLevelIntro() {
			for (int i = 0; i < 20; ++i) {
				cout << "\t\t";
				for (int j = 0; j < 20; ++j) {
					cout << (levelMap[i][j] == '.' ? "· " : "██");
				}
				cout << "\n";
			}
			
			// 把鼠标移动到左上角 
			HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	    	COORD coord = {0, 0};
	    	SetConsoleCursorPosition(hOut, coord);
			
			string Tab = "\t\t\t\t\t\t";
			cout << "\n\n\n\n\n";
			cout << Tab << "\t\t关卡名称:\t" << name << "\n\n";
			cout << Tab << "\t\t简介:\n\t\t" << Tab << introduction << "\n\n";
			cout << Tab << "\t\t难度:";
			for (int i = 0; i < difficulty; ++i)cout << "★ ";
			for (int i = difficulty; i < 5; ++i)cout << "☆ ";
		}
	};
	
	level levels[10];
	int levelNum;
	
	void InitLevel() {
		levelNum = 6;
		levels[0] = level("空洞", "幻术世界有什么不好\n\t\t\t\t\t\t\t\t现实太残酷,只会让这空洞越来越大……", 0, emptyLevel);
		levels[1] = level("空间", "黑暗中陨落的闪光……你已无处可逃……", 1, classicLevel);
		levels[2] = level("有限月读", "九尾就永远沉睡在无限月读之中吧", 1, trainLevel);
		levels[3] = level("神威", "你的逞强也就到此为止,可以退场了……", 3, godLevel);
		levels[4] = level("漩涡", "憎恨和痛楚,这一切都由我来承受吧!", 4, roundLevel);
		levels[5] = level("痛楚", "向神挑战是愚蠢的!", 5, painLevel);
	}
	
	void cls() { // 清屏 
	    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	    COORD coord = {0, 0};
	    SetConsoleCursorPosition(hOut, coord);
	}
	
	int randint(int l, int r) { // 随机数 
		static random_device rd;  // 真随机数生成器(部分平台可能伪随机)
		static mt19937 gen(rd()); // 用真随机种子初始化 mt19937 引擎
	    uniform_int_distribution<int> dist(l, r);
	    return dist(gen);
	}
	
	void init() { // 初始化 
		InitLevel();
		mpSize = 20; // 大小:20*20 
		dis = 'd'; // 初始方向:右 
		runTime = 0; // 计时器归零 
		randFut = randint(10, 500);
		snkSiz = 1; // 初始蛇身:1(只有蛇头) 
		fut.x = randint(0, mpSize - 1); // 随机初始化水果 
		fut.y = randint(0, mpSize - 1);
		qSnake.clear(); // 清空 
		qSnake.push_back({mpSize / 2, mpSize / 2, 1}); // 压入蛇头 
	}
	
	// 选择关卡 
	int ChooseLevel() { // 返回关卡 id
		int levelId = 0;
		while (1) {
			char keyDown;
			if (_kbhit()) {
				keyDown = getch();
				if (keyDown == 'a' && levelId > 0) --levelId;
				else if (keyDown == 'd' && levelId < levelNum - 1) ++levelId;
				else if (keyDown == 'q') break;
			}
			
			system("cls");
			cout << "\t====================  选择关卡  ====================\n\n";
			cout << "按下 a,d 选择上一个/下一个关卡\n按下 q 确认\n\n";
			levels[levelId].PrintLevelIntro();
			
			while (!_kbhit());
		}
		system("cls");
		return levelId;
	}
	
	// 填充地图 
	void FillMap(int levelId) { // 传入关卡 id 
		for (int i = 0; i < mpSize; ++i) {
			for (int j = 0; j < mpSize; ++j) {
				mp[i][j] = (levels[levelId].levelMap[i][j] == '.' ? emptyCell : wallCell);
			}
		}
	}
	
	void PrintMap(int levelId) { // 打印地图 
		// 按照选择的关卡填充地图 
		FillMap(levelId); 
		
		// 处理蛇 
		deque <Pos> copySnake(qSnake); 
		for (int node = 1; node <= snkSiz; ++node) { // snkSiz 个节点 
			Pos fot = copySnake.front();
			copySnake.pop_front();
			mp[fot.x][fot.y] = (fot.type == 1 ? snakeHead : snakeBody); // 修改地图 
		}
		
		// 处理果子
		--randFut;
		if (randFut == 0) { // 达到刷新时间 
			fut.x = randint(0, mpSize - 1);
			fut.y = randint(0, mpSize - 1);
			randFut = randint(10, 500);
		}
		if (mp[fut.x][fut.y] != emptyCell) { // 是否加分 
			qSnake.push_back({fut.x, fut.y, 2}); // 成为蛇身 
			++snkSiz; // 蛇长加一 
			while (mp[fut.x][fut.y] != emptyCell) { // 找到空位 
				fut.x = randint(0, mpSize - 1);
				fut.y = randint(0, mpSize - 1);
			}
		}
		mp[fut.x][fut.y] = foodCell; // 标记为果子
		
		cls(); // 清屏 
		for (int i = 0; i < mpSize; ++i) { // 打印地图 
			for (int j = 0; j < mpSize; ++j) {
				cout << mp[i][j];
			}
			cout << '\n';
		}
		
		// 打印得分 
		cout << "得分:" << snkSiz - 1; 
	}
	
	void ModifyPos(int xRf, int yRf) {
		qSnake.pop_back(); // 弹出蛇尾 
		Pos head = qSnake.front();
		qSnake.front().type = 2; // 把蛇头改为蛇身
		
		Pos newHead = {head.x + xRf, head.y + yRf, 1}; // 新蛇头 
		// 判断出界
		if (newHead.x < 0)newHead.x = mpSize - 1;
		else if (newHead.x >= mpSize)newHead.x = 0;
		if (newHead.y < 0)newHead.y = mpSize - 1;
		else if (newHead.y >= mpSize)newHead.y = 0; 
		// 判断游戏结束:撞到蛇身、墙 
		if (mp[newHead.x][newHead.y] == snakeBody)GameOver(1); // OverType = 1 表示撞到自己 
		if (mp[newHead.x][newHead.y] == wallCell)GameOver(2);  // OverType = 2 表示撞到墙 
		
		qSnake.push_front(newHead); 
	}
	
	void RefreshPos() { // 更新位置 
		if (_kbhit()) dis = getch(); // 有新按键按下
		if (runTime == 0) { // 达到刷新时间 
			if (dis == 'w') ModifyPos(-1, 0);
			else if (dis == 's') ModifyPos(1, 0);
			else if (dis == 'a') ModifyPos(0, -1);
			else if (dis == 'd') ModifyPos(0, 1);
		} 
	}
	
	void GameOver(int OverType) { // 游戏结束 
		int score = snkSiz - 1; // 分数 
		cls();
		cout << "\n\n\t\t\t\t\t========================== 游戏结束! ==========================\n\n";
		cout << "\t\t\t\t\t\tOps! 撞到" << (OverType == 1 ? "自己" : "墙") << "了!\n"; 
		cout << "\n\n\t\t\t\t\t\t最终得分:" << score << " 分\n\n";
		mpSize -= 5;
		while (mpSize--)cout << '\n';
		exit(0); 
	}
public:
	void RunGame() { // 游戏主循环 
		system("cls"); // 开始时清屏以免有什么不好的东西留在终端 
		init();
		cout << "========================== 贪吃蛇小游戏 ==========================\n\n";
		cout << "\t\t按下 wsad 控制蛇移动\n\t\t吃到果子“" << foodCell << "”可以加分\n\t\t撞到自己会失败!\n请确保你的输入法是英文小写状态\n\n按下任意键开始选择关卡\n";
		while (!_kbhit()); // 等待按下按键 
		system("cls");
		
		int levelId = ChooseLevel(); // 选择关卡 
		FillMap(levelId);
		
		// init(); // 初始化 
		while (1) {
			PrintMap(levelId);
			RefreshPos();
			++runTime; // 更新计时器 
			runTime %= 10;
		}
	}
};

int main() {
	Game Program;
	Program.RunGame();
	return 0;
}

省练习(终于来正经的了)

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <windows.h>
using namespace std;

string map[50][5] = 
{
	{"北京市", "京", "北京"},
	{"天津市", "津", "天津"},
	{"河北省", "冀", "石家庄"},
	{"山西省", "晋", "太原"},
	{"内蒙古自治区", "内蒙古", "呼和浩特"},
	{"辽宁省", "辽", "沈阳"},
	{"吉林省", "吉", "长春"},
	{"黑龙江省", "黑", "哈尔滨"},
	{"上海市", "沪", "上海"},
	{"江苏省", "苏", "南京"},
	{"浙江省", "浙", "杭州"},
	{"安徽省", "皖", "合肥"},
	{"福建省", "闽", "福州"},
	{"江西省", "赣", "南昌"},
	{"山东省", "鲁", "济南"},
	{"河南省", "豫", "郑州"},
	{"湖北省", "鄂", "武汉"},
	{"湖南省", "湘", "长沙"},
	{"广东省", "粤", "广州"},
	{"广西壮族自治区", "桂", "南宁"},
	{"海南省", "琼", "海口"},
	{"重庆市", "渝", "重庆"},
	{"四川省", "川", "成都"},
	{"贵州省", "贵", "贵阳"},
	{"云南省", "云", "昆明"},
	{"西藏自治区", "藏", "拉萨"},
	{"陕西省", "陕", "西安"},
	{"甘肃省", "甘", "兰州"},
	{"青海省", "青", "西宁"},
	{"宁夏回族自治区", "宁", "银川"},
	{"新疆维吾尔自治区", "新", "乌鲁木齐"},
	{"香港特别行政区", "港", "香港"},
	{"澳门特别行政区", "澳", "澳门"},
	{"台湾省", "台", "台北"}
};

void sout(string str, int tim)
{
	for (char ch : str)
	{
		cout << ch;
		Sleep(tim);
	}
}

int main()
{
	srand(time(0));
	
	sout("这是练习中国省级行政区名称、简称、省会的程序\n\0", 25);
	Sleep(500);
	
	int gmtim = 0, wntim = 0;
	sout("输入要练习多少次\n", 25);
	cin >> gmtim;
	
	for (int ti = 1; ti <= gmtim; ++ti)
	{
		system("cls");
		int i = rand() % 34, j = rand() % 2 + 1;
		
		sout("请回答 " + map[i][0] + " 的", 25);
		if (j == 1)sout("简称\n", 25);
		else sout("省会\n", 25);
		
		string inpt;
		cin >> inpt;
		if (inpt == map[i][j])
		{
			sout("回答正确!\n", 25);
			++wntim;
			sout("正确率: " + to_string(wntim * 100 / ti) + " %", 25);
		}
		else
		{
			sout("回答错误!\n", 25);
			sout("正确答案是: " + map[i][j] + "\n", 25);
			sout("正确率: " + to_string(wntim * 100 / ti) + " %", 25);
			Sleep(1000);
		}
		Sleep(1000);
	}
	system("cls");
	sout("正确率: " + to_string(wntim * 100 / gmtim) + " %", 25);
	return 0;
}

work

#include <bits/stdc++.h>
using namespace std;

const int N = 2e5 + 5;
int n, m, k, a[N], b[N];

int main()
{
	//freopen("work.in", "r", stdin);
	//freopen("work.out", "w", stdout);
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	
	cin >> n >> m >> k;
	for (int i = 1; i <= n; ++i)
	{
		cin >> a[i];
	}
	for (int i = 1; i <= m; ++i)
	{
		cin >> b[i];
	}
	
	int l = 1, r = 1, cnt = 0;
	while (l <= n && r <= m && cnt <= k)
	{
		printf("l:%d r:%d cnt:%d\n", l, r, cnt);//
		if (a[l] < b[r])
		{
			cnt += a[l];
			++l;
		}
		else
		{
			cnt += b[r];
			++r;
		}
	}
	while (l <= n && cnt <= k)
	{
		cnt += a[l];
		++l;
	}
	while (r <= m && cnt <= k)
	{
		cnt += b[r];
		++r;
	}
	cout << (l - 1) + (r - 1) - 1;
	return 0;
}

二分法游戏

#include <iostream>

#include <ctime>
#include <cstdlib>
#include <windows.h>
using namespace std;

void sout(string str, int tim)
{
	for (char ch : str)
	{
		cout << ch;
		Sleep(tim);
	}
}

void cls()
{
	system("cls");
}

void game1()
{
	sout("程序会生成一个 1 到 100 的随机数字,你有 10 次机会猜这个数字", 25);
	Sleep(700);
	cls();
	
	int n = rand() % 100 + 1;
	int tim = 10;
	while (tim--)
	{
		sout("请输入你猜的数字:", 25);
		int mid;
		cin >> mid;
		cls();
		if (n == mid)
		{
			sout("你猜对了!使用次数: " + to_string(10 - tim + 1), 25);
			return ;
		}
		else if (n > mid)
		{
			sout("小了", 25);
		}
		else
		{
			sout("大了", 25);
		}
		Sleep(300);
		cls();
	}
	sout("机会用完,你输了!", 25);
}

void game2()
{
	sout("请你在心里想一个 1 到 100 的数字,这个程序会在 7 次之内猜出你想的数字", 25);
	Sleep(700);
	cls();
	sout("在每次猜出一个数字后,你要比较你想的数字和这个数字,\n如果大了就输入一个正数,小了就输入一个负数,对了就输入0", 25);
	Sleep(2000);
	cls();
	
	int l = 1, r = 100, ans = 0;
	while (l <= r)
	{
		int mid = l + (r - l) / 2;
		sout("猜的数字是:" + to_string(mid) + "\n", 25);
		Sleep(500);
		sout("请比较:", 25);
		int input;
		cin >> input;
		if (input == 0)
		{
			ans = mid;
			break;
		}
		else if (input < 0)
		{
			l = mid + 1;
		}
		else
		{
			r = mid - 1;
		}
		cls();
	}
	
	cls(); 
	sout("猜到了!你想的数字是: " + to_string(ans), 25);
}

int main()
{
	srand(time(0));
	
	sout("这是猜数字游戏", 25);
	Sleep(300);
	cls();
	
	while (1)
	{
		sout("这里有两种游戏模式:\n1. 你来猜测数字; \n2. 你来想数字 \n如果要退出游戏请输入 0 \n", 25);
		Sleep(1000);
		cls();
		sout("请输入:", 25); 
		int input;
		cin >> input;
		cls();
		while (input < 0 or input > 2)
		{
			sout("输入有误,请重新输入: ", 25);
			cin >> input;
			cls();
		}
		if (input == 0)
		{
			cls();
			sout("游戏结束!", 25);
			return 0;
		}
		else if (input == 1)
		{
			game1();
		}
		else
		{
			game2();
		}
		cls();
	}
	return 0;
}

(通俗一点就是猜数字游戏

人工能(可能没有智)

#include <iostream>
using namespace std;

int main()
{
	string str;
	for (int ti = 1; cin >> str; ++ti)
	{
		if (str.find("题") != string::npos && str.find("选") != string::npos && str.find("什么") != string::npos)
		{
			cout << "选C\n";
		}
		else
		{
			int n = str.size();
			for (int i = 0; i < n; ++i)
			{
				if (str[i] == '?')str.erase(str.begin() + i, str.begin() + i + 1);
			}
			n = str.size();
			for (int i = 0; i < n; i += 3)
			{
				if (str.substr(i, 3) == "吗")str.erase(i, 3);
			}
			n = str.size();
			for (int i = 0; i < n; i += 3)
			{
				if (str.substr(i, 3) == "?")str.erase(i, 3);
			}
			if (ti % 3 == 0)
			{
				n = str.size();
				for (int i = 0; i < n; i += 3)
				{
					if (str.substr(i, 3) == "不")str.erase(i, 3);
				}
			}
			n = str.size();
			for (int i = 0; i < n; i += 3)
			{
				if (str.substr(i, 3) == "我")
				{
					str.erase(i, 3);
					str.insert(i, "你");
				}
				else if (str.substr(i, 3) == "你")
				{
					str.erase(i, 3);
					str.insert(i, "我");
				}
			}
			if (ti % 3 != 0)
			{
				n = str.size();
				for (int i = 0; i < n; i += 3)
				{
					if (str.substr(i, 3) == "好" || str.substr(i, 3) == "是")
					{
						str.insert(i, "不");
						i += 3;
						//break;
					}
				}
			}
			cout << str << "\n";
		}
	}
	return 0;
}

按F5

#include <windows.h>
#include <iostream>
#include <string>
using namespace std;
void SimulateKeyPress(WORD keyCode, bool press, bool release) {
    INPUT input = {0};
    input.type = INPUT_KEYBOARD;
    input.ki.wVk = keyCode;
    
    if (!press) input.ki.dwFlags = KEYEVENTF_KEYUP;
    
    SendInput(1, &input, sizeof(INPUT));
    
    if (release) {
        input.ki.dwFlags = KEYEVENTF_KEYUP;
        SendInput(1, &input, sizeof(INPUT));
    }
}

void SimulateRefresh() {
    SimulateKeyPress(VK_F5, true, true);
}

int main() {
	int refreshCount;
    cin >> refreshCount;
    Sleep(5000);
    
    for (int i = 0; i < refreshCount; ++i) {
        SimulateRefresh();
    }
    return 0;
}

奇怪的功能

#include <iostream>
using namespace std;

void universe_goto()
{
	int a;
	cin >> a;
	if (a >= 10)
	{
		goto label;
	}
	cout << "a小于10\n";
	label:
		cout << "a是一个数字";
		
	cout << "\n";
}

void universe_enum()
{
	enum week
	{
		sunday,
		moday,
		tuesday,
		westeday,
		thursday,
		firday,
		starday
	};
	
	week today = firday;
	cout << today << " ";
	today = week(int(today + 1));
	cout << today;
	
	cout << "\n";
}

void universe_functor()
{
	int n;
	cin >> n;
	
	auto isp = [](int x) -> bool
	{
		if (x < 2)return 0;
		for (int i = 2; i * i <= x; ++i)
			if (x % i == 0)return 0;
		return 1;
	};
	
	cout << isp(n);
	
	cout << "\n";
}

//universe_print:
	// 基础 case
	void print()
	{
	    cout << "\n";
	}
	
	// 变参模板
	template<typename f, typename... s>
	void print(f a, s... b)
	{
	    cout << a << " ";
	    print(b...);
	}
//}

#if 0 
需要C++17
#include <tuple>
void universe_tuple()
{
	auto [name, age, job] = make_tuple("PPCQ", 666, "dog");
	print(name, age, job);
}
#endif

void universe_if()
{
	int a;
	cin >> a;
	#if (a > 10)
		cout << "a>10";
	#else
		cout << "a<=10";
	#endif
	cout << "\n";
}

int main()
{
	universe_if();
	return 0;
}

python-数学类绘图

import turtle as t
from math import*

class dot:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class line:
    def __init__(self, a1, a2):
        self.a1 = a1
        self.a2 = a2

    def lent(self):
        return sqrt(pow((a1.x - a2.x), 2) + pow((a1.y - a2.y), 2))

    def drawl(self):
        t.up()
        t.goto(self.a1.x, self.a1.y)
        t.down()
        t.goto(self.a2.x, self.a2.y)

class ttt:
    def __init__(self, A, B, C, a, b, c):
        self.A, self.B, self.C = A, B, C
        self.a, self.b, self.c = a, b, c

    def Clen(self):
        return self.a.lent() + self.b.elnt() + self.c.lent()

    def drawt(self):
        self.a.drawl()
        self.b.drawl()
        self.c.drawl()



x1, y1 = map(int, input(). split())
x2, y2 = map(int, input(). split())
x3, y3 = map(int, input(). split())

A = dot(x1, y1)
B = dot(x2, y2)
C = dot(x3, y3)
a = line(B, C)
b = line(C, A)
c = line(A, B)
tt = ttt(A, B, C, a, b, c)

t.pensize(4)
t.title("图形化编程")
t.color("#e03131")

tt.drawt()

t.done()

py获取题目Markdown

#!/usr/bin/env python3
"""
by jason
2025-07-26
copyright wanwusangzhi 2024-2025
"""
import requests, re, sys
from bs4 import BeautifulSoup
import html2text

# ========== 按需修改 ==========
BASE_URL = input("")       # 你的站点根域名
LOGIN_URL = f'{BASE_URL}/login' # login page
Problem_ID = input("")
HOME_URL = f'{BASE_URL}/p/{Problem_ID}'
USERNAME  = input("")
PASSWORD  = input("")
# ===============================

def main():
    s = requests.Session()
    s.headers.update({
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/120.0.0.0 Safari/537.36'
    })

    # 1. 拉登录页,取 csrf
    login_html = s.get(LOGIN_URL).text
    soup = BeautifulSoup(login_html, 'lxml')
    csrf = (soup.find('meta', attrs={'name': 'csrf-token'}) or
            soup.find('input', attrs={'name': re.compile(r'csrf|_csrf')}))
    if csrf:
        csrf = csrf.get('content') or csrf['value']
    else:
        csrf = ''          # 站点没开 csrf 验证

    # 2. 提交账号密码
    resp = s.post(LOGIN_URL, data={
        'uname': USERNAME,
        'password': PASSWORD,
        '_csrf': csrf
    }, allow_redirects=False)

    if resp.status_code != 302:
        raise RuntimeError('登录失败,请检查账号密码或抓包核对字段名')

    # 3. 登录成功后拿首页
    home_html = s.get(HOME_URL).text
    soup = BeautifulSoup(home_html, 'html.parser')
    for katex_span in soup.find_all('span', class_='katex'):
        annotation = katex_span.find('annotation')
        if annotation:
            katex_span.replace_with(f"${annotation.text}$")  # 可选:加 $ 变成 LaTeX 公式
        # 查找class="problem-content"的div
    problem_content = soup.find('div', class_='problem-content')
    html=problem_content
    print(html)
    # 创建 html2text 处理器
    h = html2text.HTML2Text()
    h.ignore_links = False  # 不忽略链接
    h.bypass_tables = False  # 不忽略表格
    h.ignore_images = False  # 不忽略图片
    h.body_width = 0  # 不自动换行
    		# 转换 HTML 为 Markdown
    markdown = h.handle(str(html))
    print(markdown)		
    with open("p.md","w",encoding='utf-8') as f:
        f.write(markdown)

if __name__ == '__main__':
    main()

CSS - 每天都大吉

.lg-punch-result {
    /* 不隐藏整个元素,只隐藏原始内容 */
    font-size: 0 !important;
    color: transparent !important;
    background: none !important;
    border: none !important;
    /* 但保持元素可见以便显示伪元素 */
    width: auto !important;
    height: auto !important;
    overflow: visible !important;
    display: block !important; /* 确保是块级元素 */
}

.lg-punch-result::after {
    content: "§ 大吉 §" !important;
    font-size: 60px !important;
    color: #e74c3c !important;
    display: block !important;
    /* 确保伪元素独立显示 */
    position: relative !important;
    z-index: 1000 !important;
}

div.am-u-sm-6:not(.lg-fg-red) {
    /* 不隐藏整个元素,只隐藏原始内容 */
    font-size: 0 !important;
    color: transparent !important;
    background: none !important;
    border: none !important;
    /* 但保持元素可见以便显示伪元素 */
    width: auto !important;
    height: auto !important;
    overflow: visible !important;
    display: block !important; /* 确保是块级元素 */
}

div.am-u-sm-6:not(.lg-fg-red)::after {
    content: "万事皆宜" !important;
    font-size: 16px !important;
     font-weight: bold !important;
    color: #000 !important;
    left: 45px !important;
    display: block !important;
    /* 确保伪元素独立显示 */
    position: relative !important;
    z-index: 1000 !important;
}

div.am-u-sm-6:not(.lg-fg-red) span.lg-small{
    display: none !important;
}