跳到正文

科技·工程

Steam Game——《Math Expression》

MistGrove_Tide约 22 分钟
原文
文章信息与版本

文章信息

发布
2026年9月26日
收录
2026年10月4日
更新
2026年10月27日
篇幅
约 22 分钟

版本

  1. v2当前
  2. v1

V1.0-Snapshot 1:

(编译器配置:-std=c++14,运行系统:Windows 7+)

C++
#include <iostream>
#ifdef _WIN32
#include <sstream>
#include <vector>
#include <algorithm>
#include <utility>
#include <cmath>
#include <ctime>
#include <cctype>
#include <cstring>
#include <stdexcept>
#include <stack>
#include <windows.h>
#include <sys/time.h>
#include <random>

using int_t = long long;

static std::mt19937_64 rng(std::random_device{}());
int_t random () {
	return std::uniform_int_distribution<int_t>(0, 1e18)(rng);
}
int_t random (int_t l, int_t r) {
	return std::uniform_int_distribution<int_t>(l, r)(rng);
}
static void skipSpaces(const std::string& s, size_t& pos) {
	while (pos < s.size() && std::isspace(static_cast<unsigned char>(s[pos]))) {
		++pos;
	}
}

static int_t powInt(int_t base, int_t exp) {
	if (exp < 0) throw std::runtime_error("negative exponent");
	
	int_t result = 1;
	int_t b = base;
	
	while (exp > 0) {
		if (exp & 1) result *= b;
		b *= b;
		exp >>= 1;
	}
	return result;
}

static int_t parseNumber(const std::string& s, size_t& pos) {
	skipSpaces(s, pos);
	if (pos >= s.size()) throw std::runtime_error("unexpected end");
	
	int_t sign = 1;
	if (s[pos] == '-') {
		sign = -1;
		++pos;
		skipSpaces(s, pos);
	} else if (s[pos] == '+') {
		++pos;
		skipSpaces(s, pos);
	}
	
	if (pos >= s.size() || !std::isdigit(static_cast<unsigned char>(s[pos]))) {
		throw std::runtime_error("expected number");
	}
	
	int_t value = 0;
	while (pos < s.size() && std::isdigit(static_cast<unsigned char>(s[pos]))) {
		value = value * 10 + (s[pos] - '0');
		++pos;
	}
	return sign * value;
}

static int_t parseExpr(const std::string& s, size_t& pos);

static int_t parseFactor(const std::string& s, size_t& pos) {
	skipSpaces(s, pos);
	if (pos >= s.size()) throw std::runtime_error("unexpected end");
	
	if (s[pos] == '(') {
		++pos;
		int_t value = parseExpr(s, pos);
		skipSpaces(s, pos);
		if (pos >= s.size() || s[pos] != ')') {
			throw std::runtime_error("missing ')'");
		}
		++pos;
		return value;
	}
	
	if (s[pos] == '-' || s[pos] == '+') {
		int_t sign = (s[pos] == '-') ? -1 : 1;
		++pos;
		skipSpaces(s, pos);
		if (pos < s.size() && s[pos] == '(') {
			++pos;
			int_t value = parseExpr(s, pos);
			skipSpaces(s, pos);
			if (pos >= s.size() || s[pos] != ')') {
				throw std::runtime_error("missing ')'");
			}
			++pos;
			return sign * value;
		}
		--pos;
		return parseNumber(s, pos);
	}
	
	return parseNumber(s, pos);
}

bool powerExceedsIntMax(int x, int y) {
	if (y < 0) return false;          
	if (x == 0) return false;         
	if (y == 0) return false;         
	if (x == 1) return false;         
	long long res = 1;
	long long base = x;
	
	for (int i = 0; i < y; i++) {
		if (res > (1LL << 20) / base) {
			return true;           
		}
		res *= base;
	}
	return false;
}

static int_t parsePower(const std::string& s, size_t& pos) {
	int_t base = parseFactor(s, pos);

	skipSpaces(s, pos);
	if (pos < s.size() && s[pos] == '^') {
		++pos;
		int_t exp = parsePower(s, pos); 
		return powInt(base, exp);
	}
	
	return base;
}

static int_t parseTerm(const std::string& s, size_t& pos) {
	int_t value = parsePower(s, pos);
	
	while (true) {
		skipSpaces(s, pos);
		if (pos >= s.size()) break;
		
		if (s[pos] == '*') {
			++pos;
			value *= parsePower(s, pos);
		} else if (s[pos] == '/') {
			++pos;
			int_t divisor = parsePower(s, pos);
			if (divisor == 0) throw std::runtime_error("division by zero");
			value /= divisor;
		} else {
			break;
		}
	}
	return value;
}

static int_t parseExpr(const std::string& s, size_t& pos) {
	int_t value = parseTerm(s, pos);
	
	while (true) {
		skipSpaces(s, pos);
		if (pos >= s.size()) break;
		
		if (s[pos] == '+') {
			++pos;
			value += parseTerm(s, pos);
		} else if (s[pos] == '-') {
			++pos;
			value -= parseTerm(s, pos);
		} else {
			break;
		}
	}
	return value;
}

int_t eval(std::string a) {
	size_t pos = 0;
	int_t result = parseExpr(a, pos);
	skipSpaces(a, pos);
	if (pos != a.size()) {
		throw std::runtime_error("unexpected trailing characters");
	}
	return result;
}

bool equal(std::string a, std::string b) {
	try {
		int_t va = eval(a);
		int_t vb = eval(b);
		return va == vb;
	} catch (...) {
		return false;
	}
}

std::string SpawnExpression(int n) {
	if (n < 5) n = 5;

	const char ops[] = {'+', '-', '*', '/', '^'};
	const int opCount = 5;

	auto randInt = [&](int l, int r) -> int {
		return std::uniform_int_distribution<int>(l, r)(rng);
	};

	auto randNumber = [&](int maxLen) -> std::string {
		if (maxLen <= 0) maxLen = 1;

		int len = std::uniform_int_distribution<int>(1, maxLen)(rng);
		if (len == 1) {
			return std::to_string(std::uniform_int_distribution<int>(0, 9)(rng));
		}

		std::string s;
		s += std::to_string(std::uniform_int_distribution<int>(1, 9)(rng));
		for (int i = 1; i < len; ++i) {
			s += std::to_string(std::uniform_int_distribution<int>(0, 9)(rng));
		}
		return s;
	};

	auto buildExpr = [&](int len) -> std::string {
		if (len <= 0) return "0";

		std::string s;
		s += randNumber(len);

		while (static_cast<int>(s.size()) < len) {
			int remain = len - static_cast<int>(s.size());
			if (remain <= 1) break;

			s += ops[randInt(0, opCount - 1)];

			int maxDigitLen = std::min(remain - 1, 3);
			if (maxDigitLen < 1) maxDigitLen = 1;

			s += randNumber(maxDigitLen);
		}

		if (static_cast<int>(s.size()) > len) {
			s.resize(len);
		}
		return s;
	};

	auto tryBuildRight = [&](int len, int_t target) -> std::string {
		if (len <= 0) return "";

		if (len == 1) {
			if (target >= 0 && target <= 9) {
				return std::to_string(static_cast<int>(target));
			}
			return "";
		}

		if (len == 3) {
			int a = randInt(1, 9);
			int b = randInt(1, 9);

			if (a + b == target) return std::to_string(a) + "+" + std::to_string(b);
			if (a - b == target) return std::to_string(a) + "-" + std::to_string(b);
			if (b != 0 && a % b == 0 && a / b == target) {
				return std::to_string(a) + "/" + std::to_string(b);
			}
			return "";
		}

		std::string s;
		s += randNumber(len);

		while (static_cast<int>(s.size()) < len) {
			int remain = len - static_cast<int>(s.size());
			if (remain <= 1) break;

			s += ops[randInt(0, opCount - 1)];

			int maxDigitLen = std::min(remain - 1, 3);
			if (maxDigitLen < 1) maxDigitLen = 1;

			s += randNumber(maxDigitLen);
		}

		if (static_cast<int>(s.size()) > len) {
			s.resize(len);
		}

		try {
			if (eval(s) == target) {
				return s;
			}
		} catch (...) {}

		return "";
	};

	for (int attempt = 0; attempt < 8000; ++attempt) {
		int eqPos = 2 + randInt(0, n - 4);
		int leftLen = eqPos;
		int rightLen = n - eqPos - 1;

		if (leftLen < 1) leftLen = 1;
		if (rightLen < 1) rightLen = 1;

		std::string left = buildExpr(leftLen);

		int_t value;
		try {
			value = eval(left);
		} catch (...) {
			continue;
		}

		if (value <= 0 || value > 999999) continue;

		std::string right = tryBuildRight(rightLen, value);
		if (right.empty()) continue;

		std::string expr = left + "=" + right;
		if (static_cast<int>(expr.size()) != n) continue;

		try {
			if (eval(left) == eval(right)) {
				return expr;
			}
		} catch (...) {
			continue;
		}
	}

	std::string fallback;
	fallback += '1';
	fallback += '=';
	while (static_cast<int>(fallback.size()) < n) {
		fallback += '1';
	}
	return fallback;
}

void EnableAnsiColor() {
	HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	DWORD mode = 0;
	GetConsoleMode(hOut, &mode);
	mode |= 0x0004;
	SetConsoleMode(hOut, mode);
}

void PrintColorText(std::string s, WORD color) {
	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	GetConsoleScreenBufferInfo(hConsole, &csbi);
	WORD oldAttr = csbi.wAttributes;
	SetConsoleTextAttribute(hConsole, color);
	std::cout << s;
	std::cout.flush();
	SetConsoleTextAttribute(hConsole, oldAttr);
}

int score = 0, depth = 0;

std::string get_good (int level) {
	if (level == 1) return "Not bad.";
	if (level == 2) return "Decent.";
	if (level == 3) return "Good.";
	if (level == 4) return "Great!";
	if (level == 5) return "Perfect!";
	if (level == 6) return "Amazing!";
	if (level == 7) return "Excellent!";
	if (level == 8) return "Unbelievable!";
	if (level == 9) return "Unrivaled!";
	if (level == 10) return "Transcendent!";
	return "Beyound x" + std::to_string(level - 9) + "!";
}

int main() {
	try {
		EnableAnsiColor();

		while (++depth) {
			std::cout << "===== Math Expression =====\n";
			std::cout << "Level: " << depth << " | Score: " << score << '\n';
			int charcnt = 4;
			while (charcnt < 5) charcnt = depth + 2 + random() % 3;
			std::cout << "Length of equation: " << charcnt << "\n";
			int maxTry = charcnt * random(150, 250) / 100.0;
			std::string ans = SpawnExpression(charcnt);
			std::cout << "Max trys: " << maxTry << "\n\n";
			int ff = -1;
			for (int turn = 1; turn <= maxTry; turn++) {
				std::cout << ">" << std::string (charcnt, '_');
				std::cout << "\033[" << charcnt << "D";
				std::string gue;
				std::cin >> gue;
				if (gue == "\\F12:[[GetAnswer") {
					std::cout << "\033[1A\033[1CThe answer is: ";
					PrintColorText(ans, FOREGROUND_GREEN);
					std::cout << '\n';
					continue;
				}
				if (gue.size() != ans.size()) {
					std::cout << "\033[1A\033[1C";
					for (size_t i = 1; i <= gue.size(); i++) PrintColorText(std::string(1, gue[i - 1]), BACKGROUND_RED);
					std::cerr << "\nLength mismatch!\n";
					turn--;
					continue;
				}

				size_t opeq_pos = gue.find ('=');
				if (opeq_pos == gue.npos ||
				    opeq_pos != gue.rfind ('=') ||
				    opeq_pos == 0ULL ||
				    opeq_pos == gue.size() - 1 ||
				    !equal(gue.substr(0, opeq_pos), gue.substr(opeq_pos + 1))) {
					std::cout << "\033[1A\033[1C";
					for (size_t i = 1; i <= gue.size(); i++) PrintColorText(std::string(1, gue[i - 1]), BACKGROUND_RED);
					std::cerr << "\nEquation doesn't hold!\n";
					turn--;
					continue;
				}

				std::cout << "\033[1A\033[1C";
				for (size_t k = 0; k < ans.size(); k++) {
					if (gue[k] == ans[k]) {
						PrintColorText(std::string(1, gue[k]), FOREGROUND_GREEN);
					} else if (ans.find(gue[k]) != std::string::npos) {
						PrintColorText(std::string(1, gue[k]), FOREGROUND_RED | FOREGROUND_GREEN);
					} else {
						PrintColorText(std::string(1, gue[k]), FOREGROUND_RED);
					}
				}
				std::cout << "\n";
				if (gue == ans) {
					ff = turn;
					break;
				}
			}

			if (ff != -1) {
				score += maxTry - ff + 1;
				std::cout << '\n' << get_good(maxTry / ff);
			} else {
				std::cout << "\nLose!\nAnswer: " << ans << '\n';
			}
			std::cout << "\nPress Enter to next level...";
			std::cin.get();
			std::cin.get();
			system("cls");
		}
	} catch (std::exception &e) {
		std::cerr << "\nException: " << e.what() << '\n';
	}
	return 0;
}
#else
int main() {
	std::cerr << "Oops!\nThis program must run in Windows.\nYour system is " <<
#if defined (_WIN32)
	             "Windows"
#elif defined(__APPLE__)
	             "Apple"
#elif defined(__ANDROID_)
	             "Android"
#elif defined(__linux__)
	             "Linux"
#elif defined(__unix__)
	             "Other unix"
#endif
	          << ".";
	return 1;
}
#endif
//此版本为测试版,Bug较多,欢迎评论区指出
//代码中部分内容由Qwen-3.7模型生成
原文