Python代码
import random
import time
import datetime
NUM_DIGITS = 10
#NUM_NON_ZERO_DIGITS = 9
failFlag = 0
class Mastermind:
def __init__(self, code_length, max_attempts, secret01code, game_id):
# def __init__(self, code_length, max_attempts):
self.code_length = code_length
self.max_attempts = max_attempts
# self.secret_code = self.generate_secret_code()
self.secret_code= secret01code
self.guesses = []
self.possible_guesses = [[[[
True for _ in range(NUM_DIGITS)] for _ in range(NUM_DIGITS)]
for _ in range(NUM_DIGITS)] for _ in range(NUM_DIGITS)]
def get_current_time_as_file_name(self):
now = datetime.datetime.now()
return now.strftime("%y%m%d_%H%M-%S")
# def play(self):
def play(self, log_file):
print("欢迎来到珠玑妙算!")
print(f"尝试猜测{self.code_length}位秘密代码!")
print(f"您的猜测空间有 {self.count_possible_guesses()} 种可能性")
file_name = f"log_{self.get_current_time_as_file_name()}.txt"
print(f"fileName: {file_name}")
with open(file_name, 'a') as log_file:
NumCount=0;
for attempt in range(1, self.max_attempts + 1):
print(f"您的猜测空间还有: {self.count_possible_guesses()} 种可能性")
print("\n")
print("第:",attempt,"次猜解:",end='')
current_guess = self.get_guess()
self.guesses.append(current_guess)
correct_positions, correct_numbers = self.evaluate_guess(current_guess, self.secret_code)
if correct_positions == self.code_length:
print("恭喜你! 你猜中了秘密代码!!")
log_file.write(f"第 {attempt} 次尝试: {' '.join(map(str, current_guess))} {correct_positions} 个位置(&数字都)正确, {correct_numbers} 个数字正确但位置错误.\n")
break
if log_file:
log_file.write(f"第 {attempt} 次尝试: {' '.join(map(str, current_guess))} {correct_positions} 个位置(&数字都)正确, {correct_numbers} 个数字正确但位置错误.\n")
print(f"第 {attempt} 次尝试: {correct_positions} 个位置(&数字都)正确, {correct_numbers} 个数字正确].")
if correct_positions == self.code_length:
print(f"恭喜你! 你猜中了秘密代码!!密码是: {' '.join(map(str, self.secret_code))}")
log_file.write(f"你猜中了秘密代码!密码是: {' '.join(map(str, self.secret_code))}\n")
input_value = input("输入 'e' 或 'E' 退出游戏: ")
if input_value.lower() == 'e':
return
if input_value == 'r':
self.init_guess_array()
self.update_possible_guesses(current_guess, correct_positions, correct_numbers)
if self.count_possible_guesses() < 2:
NumCount+=1
print(f"可能的猜测空间已经缩小到2个或更少的可能性,您的猜测空间有 {self.count_possible_guesses()} 种可能性")
log_file.write(f"可能的猜测空间已经缩小到2个或更少的可能性,您的猜测空间有 {self.count_possible_guesses()} 种可能性\n")
#break
if (NumCount>1 and self.count_possible_guesses()<2):
print("很遗憾,你用尽了所有尝试次数. 秘密代码是: ", ' '.join(map(str, self.secret_code)))
break
def generate_secret_code(self):
return [random.randint(0, NUM_DIGITS - 1) for _ in range(self.code_length)]
def init_guess_array(self):
self.possible_guesses = [[[[
True for _ in range(NUM_DIGITS)] for _ in range(NUM_DIGITS)]
for _ in range(NUM_DIGITS)] for _ in range(NUM_DIGITS)]
def old_count_possible_guesses(self):
return sum(
1 for i1 in range(NUM_DIGITS)
for i2 in range(NUM_DIGITS)
for i3 in range(NUM_DIGITS)
for i4 in range(NUM_DIGITS)
if self.possible_guesses[i1][i2][i3][i4]
)
def count_possible_guesses(self,show=0):
numSum=0
for i1 in range(NUM_DIGITS):
for i2 in range(NUM_DIGITS):
for i3 in range(NUM_DIGITS):
for i4 in range(NUM_DIGITS):
if self.possible_guesses[i1][i2][i3][i4]:
numSum+=1
if 1==show:
print ('[',i1,i2,i3,i4,']',end='')
return numSum
def get_guess(self):
while True:
input_value = input(f"请输入你的猜测 ({self.code_length} 位数字): ")
if len(input_value) == self.code_length and input_value.isdigit():
return [int(char) for char in input_value]
else:
if input_value == 's' or input_value=='z':
self.count_possible_guesses(1)
print("无效输入,请重新输入。")
def evaluate_guess(self, guess, secret_code):
secret_code_copy = secret_code[:]
correct_positions = sum(1 for i in range(self.code_length) if guess[i] == secret_code[i])
for i in range(self.code_length):
if guess[i] == secret_code[i]:
secret_code_copy.remove(guess[i])
correct_numbers = 0
for i in range(self.code_length):
if guess[i] in secret_code_copy and guess[i] != secret_code[i]:
correct_numbers += 1
secret_code_copy.remove(guess[i])
return correct_positions, correct_numbers
def update_possible_guesses(self, guess, correct_positions, correct_numbers):
for i1 in range(NUM_DIGITS):
for i2 in range(NUM_DIGITS):
for i3 in range(NUM_DIGITS):
for i4 in range(NUM_DIGITS):
if not self.possible_guesses[i1][i2][i3][i4]:
continue
temp_guess = [i1, i2, i3, i4]
temp_correct_positions, temp_correct_numbers = self.evaluate_guess(temp_guess, guess)
if temp_correct_positions != correct_positions or temp_correct_numbers != correct_numbers:
self.possible_guesses[i1][i2][i3][i4] = False
def load_question_bank(file_name):
question_bank = []
with open(file_name, 'r') as file:
for line in file:
code, id_number = line.strip().split(':')
question_bank.append((code, int(id_number)))
return sorted(question_bank, key=lambda x: x[1])
if __name__ == "__main__":
# game = Mastermind(4, 9999)
# game.play()
now = datetime.datetime.now()
date_str = now.strftime("%y%m%d_%H%M")
filename = now.strftime("%y%m%dnew18-a.txt")
question_bank_file = filename #f"240707new1718game.txt"
question_bank_file= f"240707new18-a.txt"
log_file_name = f"240707new1718log.txt"
# Generate question bank
# generate_question_bank(question_bank_file)
# Load question bank
print(question_bank_file)
question_bank = load_question_bank(question_bank_file)
with open(log_file_name, 'a') as log_file:
for code, game_id in question_bank:
secret_code = [int(digit) for digit in code]
game = Mastermind(4, 9999, secret_code, game_id)
game.play(log_file)
Python代码:
import random
import time
import datetime
NUM_DIGITS = 10
#NUM_NON_ZERO_DIGITS = 9
failFlag = 0
class Mastermind:
def __init__(self, code_length, max_attempts):
self.code_length = code_length
self.max_attempts = max_attempts
self.secret_code = self.generate_secret_code()
self.guesses = []
self.possible_guesses = [[[[
True for _ in range(NUM_DIGITS)] for _ in range(NUM_DIGITS)]
for _ in range(NUM_DIGITS)] for _ in range(NUM_DIGITS)]
def get_current_time_as_file_name(self):
now = datetime.datetime.now()
return now.strftime("%y%m%d_%H%M-%S")
def play(self):
print("欢迎来到珠玑妙算!")
print(f"尝试猜测{self.code_length}位秘密代码!")
print(f"您的猜测空间有 {self.count_possible_guesses()} 种可能性")
file_name = f"log_{self.get_current_time_as_file_name()}.txt"
print(f"fileName: {file_name}")
with open(file_name, 'a') as log_file:
NumCount=0;
for attempt in range(1, self.max_attempts + 1):
print(f"您的猜测空间还有: {self.count_possible_guesses()} 种可能性")
print("\n")
current_guess = self.get_guess()
self.guesses.append(current_guess)
correct_positions, correct_numbers = self.evaluate_guess(current_guess, self.secret_code)
if correct_positions == self.code_length:
print("恭喜你! 你猜中了秘密代码!!")
log_file.write(f"第 {attempt} 次尝试: {' '.join(map(str, current_guess))} {correct_positions} 个位置(&数字都)正确, {correct_numbers} 个数字正确但位置错误.\n")
break
if log_file:
log_file.write(f"第 {attempt} 次尝试: {' '.join(map(str, current_guess))} {correct_positions} 个位置(&数字都)正确, {correct_numbers} 个数字正确但位置错误.\n")
print(f"第 {attempt} 次尝试: {correct_positions} 个位置(&数字都)正确, {correct_numbers} 个数字正确].")
if correct_positions == self.code_length:
print(f"恭喜你! 你猜中了秘密代码!!密码是: {' '.join(map(str, self.secret_code))}")
log_file.write(f"你猜中了秘密代码!密码是: {' '.join(map(str, self.secret_code))}\n")
input_value = input("输入 'e' 或 'E' 退出游戏: ")
if input_value.lower() == 'e':
return
if input_value == 'r':
self.init_guess_array()
self.update_possible_guesses(current_guess, correct_positions, correct_numbers)
if self.count_possible_guesses() < 2:
NumCount+=1
print(f"可能的猜测空间已经缩小到2个或更少的可能性,您的猜测空间有 {self.count_possible_guesses()} 种可能性")
log_file.write(f"可能的猜测空间已经缩小到2个或更少的可能性,您的猜测空间有 {self.count_possible_guesses()} 种可能性\n")
#break
if (NumCount>1 and self.count_possible_guesses()<2):
print("很遗憾,你用尽了所有尝试次数. 秘密代码是: ", ' '.join(map(str, self.secret_code)))
break
def generate_secret_code(self):
return [random.randint(0, NUM_DIGITS - 1) for _ in range(self.code_length)]
def init_guess_array(self):
self.possible_guesses = [[[[
True for _ in range(NUM_DIGITS)] for _ in range(NUM_DIGITS)]
for _ in range(NUM_DIGITS)] for _ in range(NUM_DIGITS)]
def old_count_possible_guesses(self):
return sum(
1 for i1 in range(NUM_DIGITS)
for i2 in range(NUM_DIGITS)
for i3 in range(NUM_DIGITS)
for i4 in range(NUM_DIGITS)
if self.possible_guesses[i1][i2][i3][i4]
)
def count_possible_guesses(self,show=0):
numSum=0
for i1 in range(NUM_DIGITS):
for i2 in range(NUM_DIGITS):
for i3 in range(NUM_DIGITS):
for i4 in range(NUM_DIGITS):
if self.possible_guesses[i1][i2][i3][i4]:
numSum+=1
if 1==show:
print ('[',i1,i2,i3,i4,']',end='')
return numSum
def get_guess(self):
while True:
input_value = input(f"请输入你的猜测 ({self.code_length} 位数字): ")
if len(input_value) == self.code_length and input_value.isdigit():
return [int(char) for char in input_value]
else:
if input_value == 's' or input_value=='z':
self.count_possible_guesses(1)
print("无效输入,请重新输入。")
def evaluate_guess(self, guess, secret_code):
secret_code_copy = secret_code[:]
correct_positions = sum(1 for i in range(self.code_length) if guess[i] == secret_code[i])
for i in range(self.code_length):
if guess[i] == secret_code[i]:
secret_code_copy.remove(guess[i])
correct_numbers = 0
for i in range(self.code_length):
if guess[i] in secret_code_copy and guess[i] != secret_code[i]:
correct_numbers += 1
secret_code_copy.remove(guess[i])
return correct_positions, correct_numbers
def update_possible_guesses(self, guess, correct_positions, correct_numbers):
for i1 in range(NUM_DIGITS):
for i2 in range(NUM_DIGITS):
for i3 in range(NUM_DIGITS):
for i4 in range(NUM_DIGITS):
if not self.possible_guesses[i1][i2][i3][i4]:
continue
temp_guess = [i1, i2, i3, i4]
temp_correct_positions, temp_correct_numbers = self.evaluate_guess(temp_guess, guess)
if temp_correct_positions != correct_positions or temp_correct_numbers != correct_numbers:
self.possible_guesses[i1][i2][i3][i4] = False
if __name__ == "__main__":
game = Mastermind(4, 9999)
game.play()
C++:
一、new240707A:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream> // 用于输入和输出
#include <vector> // 用于动态数组(向量)的使用
#include <cstdlib> // 用于随机数生成
#include <ctime> // 用于设置随机数种子
#include <tuple> // 用于 std::tie
#include <string> // 用于字符串
#include <ctime> // 用于时间
#include <fstream> // 用于文件操作
#define Num10 10 // 0~9
#define Num09 9 // 1~9
int failFlag = false;
// 定义Mastermind游戏的类
class Mastermind {
public:
Mastermind(int codeLength, int maxAttempts)
: codeLength(codeLength), maxAttempts(maxAttempts) {
srand(static_cast<unsigned int>(time(0))); // 设置随机数种子
generateSecretCode(); // 生成秘密代码
initGuessArray(); // 初始化猜测数组
}
std::string getCurrentTimeAsFileName() {
// 获取当前时间
std::time_t now = std::time(nullptr);
// 将时间转换为本地时间
std::tm* now_tm = std::localtime(&now);
// 格式化时间为字符串
char buffer[60];// 100];
std::strftime(buffer, sizeof(buffer), "%y%m%d_%H%M-%S", now_tm);
return std::string(buffer);
}
void play() {
std::cout << "欢迎来到珠玑妙算!\n";
std::cout << "尝试猜测" << codeLength << "位秘密代码!\n";
std::cout << "您的猜测空间有 " << countPossibleGuesses() << " 种可能性\n";
//
std::string dateTime = getCurrentTimeAsFileName() + ".txt";
std::string fileName = "log" + dateTime;
std::cout << "fileName:" << fileName << std::endl;
std::ofstream logFile(fileName, std::ios::app);
//
int CountSuccess = 0;
int successFlag = 0;
for (int attempt = 1; attempt <= maxAttempts; ++attempt) {//for1100
// std::cout << "您的猜测空间还有: " << countPossibleGuesses() << " 种可能性\n";
printf("\n");
std::vector<int> currentGuess = getGuess(); // 获取用户的猜测
guesses.push_back(currentGuess); // 存储每次用户的猜测
int correctPositions, correctNumbers;
std::tie(correctPositions, correctNumbers) = evaluateGuess(currentGuess, secretCode); // 评估用户的猜测
{//代码块110
if (correctPositions == codeLength) { // 如果猜中所有位置1
std::cout << "恭喜你! 你猜中了秘密代码!!\n";
// //return;
}// 如果猜中所有位置1
}//代码块110
if (logFile.is_open()) {//if1100
logFile << "第 " << attempt << " 次尝试: ";
logFile << currentGuess[0] << currentGuess[1] << currentGuess[2] << currentGuess[3] << " ";
logFile << correctPositions << " 个位置(&数字都)正确, ";
logFile << correctNumbers << " 个数字正确但位置错误.\n";
}//if1100
else {
std::cout << "文件打开失败74line" << std::endl;
}
std::cout << "第 " << attempt << " 次尝试: ";
std::cout << correctPositions << " 个位置(&数字都)正确, ";
std::cout << correctNumbers << " 个数字正确].";
if (correctPositions == codeLength) // 如果猜中所有位置22
{ // 如果猜中所有位置22
std::cout << "恭喜你! 你猜中了秘密代码!!密码是:" << secretCode[0] << secretCode[1] << secretCode[2] << secretCode[3] << "\n";
logFile<< "你猜中了秘密代码!密码是:" << secretCode[0] << secretCode[1] << secretCode[2]<< secretCode[3] << "\n";
//输入 "e" 或 "E" 退出游戏
std::cout << "输入 'e' 或 'E' 退出游戏: ";
std::string input; // 用于存储用户输入的字符串
std::cin >> input; // 读取用户输入的字符串
if (input == "e" || input == "E") {
logFile.close();
return;
}//if
//
if ("r" == input) {
//初始化 置信空间
initGuessArray(); // 初始化猜测数组
}
//
} // 如果猜中所有位置22
updatePossibleGuesses(currentGuess, correctPositions, correctNumbers); // 更新可能的猜测
if (countPossibleGuesses() < 2) {
std::cout << "可能的猜测空间已经缩小到2个或更少的可能性,您的猜测空间有 " << countPossibleGuesses() << " 种可能性\n";
++CountSuccess; //最后一次猜测机会
logFile << "可能的猜测空间已经缩小到2个或更少的可能性,您的猜测空间有 " << countPossibleGuesses() << " 种可能性\n";
logFile.flush();
if(CountSuccess > 1) { //只一种可能性的时候, 猜不中,游戏失败
std::cout << "可能的猜测空间已经缩小到2个或更少的可能性,您的猜测空间有 " << countPossibleGuesses() << " 种可能性\n";
failFlag = true;
}//if(CountSuccess == 1)
if (true == failFlag) { printf("游戏失败,本来只有一种可能了,您没猜到!最后的一次机会您没抓住\n"); }
std::cout<< "可能的猜测空间已经缩小到2个或更少的可能性,您的猜测空间有 " << countPossibleGuesses() << " 种可能性\n";
//break;
}//if
logFile << "可能的猜测: " << countPossibleGuesses() << " 种可能性\n";
logFile.flush();
}//for1100
logFile.close();
std::cout << "很遗憾,你用尽了所有尝试次数. 秘密代码是: ";
for (int num : secretCode) std::cout << num << " ";
std::cout << "\n";
}
private:
int codeLength; // 秘密代码的长度
int maxAttempts; // 最大尝试次数
std::vector<int> secretCode; // 秘密代码的向量
std::vector<std::vector<int>> guesses; // 所有用户的猜测
bool possibleGuesses[Num10][Num10][Num10][Num10]; // 提供猜测集合的全体
// 生成秘密代码
void generateSecretCode() {
for (int i = 0; i < codeLength; ++i) {
// secretCode.push_back(1 + rand() % Num09);// 9); // 生成1-9之间的随机数
secretCode.push_back( rand() % Num10);// 10); // 生成1-9之间的随机数
}
}
// 初始化猜测数组
void initGuessArray() {
for (int i1 = 0; i1 < Num10; ++i1) {
for (int i2 = 0; i2 < Num10; ++i2) {
for (int i3 = 0; i3 < Num10; ++i3) {
for (int i4 = 0; i4 < Num10; ++i4) {
possibleGuesses[i1][i2][i3][i4] = true; // 初始化猜测数组
}
}
}
}
}
// 统计可能的猜测数量
int countPossibleGuesses() const {
int possibleCount = 0;
for (int i1 = 0; i1 < Num10; ++i1) {
for (int i2 = 0; i2 < Num10; ++i2) {
for (int i3 = 0; i3 < Num10; ++i3) {
for (int i4 = 0; i4 < Num10; ++i4) {
if (possibleGuesses[i1][i2][i3][i4]) {
++possibleCount;
}
}
}
}
}
return possibleCount;
}
// 显示可能的猜测数 们
int showPossibleGuesses() const {
int possibleCount = 0;
for (int i1 = 0; i1 < Num10; ++i1) {
for (int i2 = 0; i2 < Num10; ++i2) {
for (int i3 = 0; i3 < Num10; ++i3) {
for (int i4 = 0; i4 < Num10; ++i4) {
if (possibleGuesses[i1][i2][i3][i4]) {
printf("[%d%d%d%d] ", i1, i2, i3, i4);
}//if
}//fori4
}//fori3
}//fori2
}//fori1
return possibleCount;
}//countPossibleGuesses
// 获取用户的猜测
std::vector<int> getGuess() {
std::vector<int> guess010(codeLength); // 初始化与密码(代码)长度相同的向量
std::string input; // 用于存储用户输入的字符串
std::cout << "请输入你的猜测 (" << codeLength << " 位数字): ";
std::cin >> input; // 读取用户输入的字符串
//先 检查 是否是 数字
for (int i = 0; i < codeLength; ++i) {
if (input[i] < '0' || input[i] > '9') {
std::cout << "您只能输入数字如“1234”,或在下面输入隐含命令……如E:退出,R重新初始化置信空间,其他命令不能告诉您,请联系[email protected].\n";
//
std::string inpu0t02; // 用于存储用户输入的字符串
std::cin >> inpu0t02; // 读取用户输入的字符串
//
if("c"== inpu0t02 || inpu0t02 == "c") {
std::cout << "您的猜测空间有 " << countPossibleGuesses() << " 种可能性\n";
}//if_c
if("z" == inpu0t02 || inpu0t02 == "z") {
showPossibleGuesses();
}//if
//
if (inpu0t02 == "e" || inpu0t02 == "E") {
return { 0,0,0,0 };
}//if
//
if ("r" == inpu0t02) {
//初始化 置信空间
initGuessArray(); // 初始化猜测数组
std::cout << "初始化 置信空间\n";
}
//
//
return getGuess(); // 递归调用以重新获取输入
}
}//for
// 检查输入字符串的长度是否等于代码长度
// 将字符串转换为整数并存储在向量中
for (int i = 0; i < codeLength; ++i) {
guess010[i] = input[i] - '0'; // 将字符转换为对应的整数
}
return guess010;
}
// 评估用户的猜测
std::pair<int, int> evaluateGuess(const std::vector<int>& guess, const std::vector<int>& secretCode) const {
int correctPosition = 0; // 位置正确的个数
int correctNumber = 0; // 数字正确但位置错误的个数
std::vector<int> codeCopy = secretCode; // 复制秘密代码用于评估
// 首先检查位置和数字都正确的
for (int i = 0; i < codeLength; ++i) {
if (guess[i] == codeCopy[i]) {
++correctPosition;
codeCopy[i] = -1; // 标记已匹配的数字
}
}
// 然后检查数字正确但位置不正确的
for (int i = 0; i < codeLength; ++i) {
for (int j = 0; j < codeLength; ++j) {
if (guess[i] == codeCopy[j] && guess[i] != secretCode[i]) {
++correctNumber;
codeCopy[j] = -1; // 标记已匹配的数字
break;
}
}
}
return { correctPosition, correctNumber };
}//evaluateGuess
// 概率空间probability space与 评估用户猜测 的比较
std::pair<int, int> probabilyE01valuateGuess(const std::vector<int>& probabily01space, const std::vector<int>& GuesSecrtCode) const {
int correctPosition = 0; // 位置正确的个数
int correctNumber = 0; // 数字正确但位置错误的个数
std::vector<int> codeCopy = GuesSecrtCode; // 复制秘密代码用于评估
// 首先检查位置和数字都正确的
for (int i = 0; i < codeLength; ++i) {
if (probabily01space[i] == codeCopy[i]) {
++correctPosition;
codeCopy[i] = -1; // 标记已匹配的数字
}
}
// 然后检查数字正确但位置不正确的
for (int i = 0; i < codeLength; ++i) {
for (int j = 0; j < codeLength; ++j) {
if (probabily01space[i] == codeCopy[j] && probabily01space[i] != GuesSecrtCode[i]) {
++correctNumber;
codeCopy[j] = -1; // 标记已匹配的数字
break;
}
}
}
return { correctPosition, correctNumber };
}//probabilyE01valuateGuess
//evaluateGuess
// 更新可能的猜测
void updatePossibleGuesses(const std::vector<int>& gues01Code02, int correctPositions, int correctNumbers) {
std::vector<int> tempGuesCode(codeLength);
for (int i1 = 0; i1 < Num10; ++i1) {
for (int i2 = 0; i2 < Num10; ++i2) {
for (int i3 = 0; i3 < Num10; ++i3) {
for (int i4 = 0; i4 < Num10; ++i4) {
if (!possibleGuesses[i1][i2][i3][i4]) continue; // 跳过不可能的组合
tempGuesCode = { i1, i2, i3, i4 };
int tempCorrectPositions, tempCorrectNumbers;
// std::tie(tempCorrectPositions, tempCorrectNumbers) = evaluateGuess(tempGuess);
std::tie(tempCorrectPositions, tempCorrectNumbers) = probabilyE01valuateGuess(tempGuesCode, gues01Code02);
if (tempCorrectPositions != correctPositions || tempCorrectNumbers != correctNumbers) //对不上号的那些 概率分布 全部标记为false4eq
{
possibleGuesses[i1][i2][i3][i4] = false; // 标记不可能的组合
}//if
}//fori4
}//fori3
}//fori2
}//fori1
}//updatePossibleGuesses
};
int main() {
// std::string fileName = "log_" + getCurrentTimeAsFileName() + ".txt";
Mastermind game(4, 9999); //9999 初始化游戏,设置代码长度为4,最大尝试次数为99
game.play(); // 开始游戏
return 0;
}//main
二、
new240706A
#define _CRT_SECURE_NO_WARNINGS
#include <iostream> // 用于输入和输出
#include <vector> // 用于动态数组(向量)的使用
#include <cstdlib> // 用于随机数生成
#include <ctime> // 用于设置随机数种子
#include <tuple> // 用于 std::tie
#include <string> // 用于字符串
#include <ctime> // 用于时间
#include <fstream> // 用于文件操作
#define Num10 10 // 0~9
#define Num09 9 // 1~9
// 定义Mastermind游戏的类
class Mastermind {
public:
Mastermind(int codeLength, int maxAttempts)
: codeLength(codeLength), maxAttempts(maxAttempts) {
srand(static_cast<unsigned int>(time(0))); // 设置随机数种子
generateSecretCode(); // 生成秘密代码
initGuessArray(); // 初始化猜测数组
}
std::string getCurrentTimeAsFileName() {
// 获取当前时间
std::time_t now = std::time(nullptr);
// 将时间转换为本地时间
std::tm* now_tm = std::localtime(&now);
// 格式化时间为字符串
char buffer[60];// 100];
std::strftime(buffer, sizeof(buffer), "%y%m%d_%H%M-%S", now_tm);
return std::string(buffer);
}
void play() {
std::cout << "欢迎来到珠玑妙算!\n";
std::cout << "尝试猜测" << codeLength << "位秘密代码!\n";
std::cout << "您的猜测空间有 " << countPossibleGuesses() << " 种可能性\n";
//
std::string dateTime = getCurrentTimeAsFileName() + ".txt";
std::string fileName = "log" + dateTime;
std::cout << "fileName:" << fileName << std::endl;
std::ofstream logFile(fileName, std::ios::app);
//
for (int attempt = 1; attempt <= maxAttempts; ++attempt) {//for1100
std::cout << "您的猜测空间还有: " << countPossibleGuesses() << " 种可能性\n";
printf("\n");
std::vector<int> currentGuess = getGuess(); // 获取用户的猜测
guesses.push_back(currentGuess); // 存储每次用户的猜测
int correctPositions, correctNumbers;
std::tie(correctPositions, correctNumbers) = evaluateGuess(currentGuess, secretCode); // 评估用户的猜测
{//代码块110
if (correctPositions == codeLength) { // 如果猜中所有位置1
std::cout << "恭喜你! 你猜中了秘密代码!!\n";
// //return;
}// 如果猜中所有位置1
}//代码块110
if (logFile.is_open()) {//if1100
logFile << "第 " << attempt << " 次尝试: ";
logFile << currentGuess[0] << currentGuess[1] << currentGuess[2] << currentGuess[3] << " ";
logFile << correctPositions << " 个位置(&数字都)正确, ";
logFile << correctNumbers << " 个数字正确但位置错误.\n";
}//if1100
else {
std::cout << "文件打开失败74line" << std::endl;
}
std::cout << "第 " << attempt << " 次尝试: ";
std::cout << correctPositions << " 个位置(&数字都)正确, ";
std::cout << correctNumbers << " 个数字正确].";
if (correctPositions == codeLength) // 如果猜中所有位置22
{ // 如果猜中所有位置22
std::cout << "恭喜你! 你猜中了秘密代码!!密码是:" << secretCode[0] << secretCode[1] << secretCode[2] << secretCode[3] << "\n";
logFile<< "你猜中了秘密代码!密码是:" << secretCode[0] << secretCode[1] << secretCode[2]<< secretCode[3] << "\n";
//输入 "e" 或 "E" 退出游戏
std::cout << "输入 'e' 或 'E' 退出游戏: ";
std::string input; // 用于存储用户输入的字符串
std::cin >> input; // 读取用户输入的字符串
if (input == "e" || input == "E") {
logFile.close();
return;
}//if
//
if ("r" == input) {
//初始化 置信空间
initGuessArray(); // 初始化猜测数组
}
//
} // 如果猜中所有位置22
updatePossibleGuesses(currentGuess, correctPositions, correctNumbers); // 更新可能的猜测
logFile << "可能的猜测: " << countPossibleGuesses() << " 种可能性\n";
logFile.flush();
}//for1100
logFile.close();
std::cout << "很遗憾,你用尽了所有尝试次数. 秘密代码是: ";
for (int num : secretCode) std::cout << num << " ";
std::cout << "\n";
}
private:
int codeLength; // 秘密代码的长度
int maxAttempts; // 最大尝试次数
std::vector<int> secretCode; // 秘密代码的向量
std::vector<std::vector<int>> guesses; // 所有用户的猜测
bool possibleGuesses[Num10][Num10][Num10][Num10]; // 提供猜测集合的全体
// 生成秘密代码
void generateSecretCode() {
for (int i = 0; i < codeLength; ++i) {
// secretCode.push_back(1 + rand() % Num09);// 9); // 生成1-9之间的随机数
secretCode.push_back( rand() % Num10);// 10); // 生成1-9之间的随机数
}
}
// 初始化猜测数组
void initGuessArray() {
for (int i1 = 0; i1 < Num10; ++i1) {
for (int i2 = 0; i2 < Num10; ++i2) {
for (int i3 = 0; i3 < Num10; ++i3) {
for (int i4 = 0; i4 < Num10; ++i4) {
possibleGuesses[i1][i2][i3][i4] = true; // 初始化猜测数组
}
}
}
}
}
// 统计可能的猜测数量
int countPossibleGuesses() const {
int possibleCount = 0;
for (int i1 = 0; i1 < Num10; ++i1) {
for (int i2 = 0; i2 < Num10; ++i2) {
for (int i3 = 0; i3 < Num10; ++i3) {
for (int i4 = 0; i4 < Num10; ++i4) {
if (possibleGuesses[i1][i2][i3][i4]) {
++possibleCount;
}
}
}
}
}
return possibleCount;
}
// 显示可能的猜测数 们
int showPossibleGuesses() const {
int possibleCount = 0;
for (int i1 = 0; i1 < Num10; ++i1) {
for (int i2 = 0; i2 < Num10; ++i2) {
for (int i3 = 0; i3 < Num10; ++i3) {
for (int i4 = 0; i4 < Num10; ++i4) {
if (possibleGuesses[i1][i2][i3][i4]) {
printf("[%d%d%d%d] ", i1, i2, i3, i4);
}//if
}//fori4
}//fori3
}//fori2
}//fori1
return possibleCount;
}//countPossibleGuesses
// 获取用户的猜测
std::vector<int> getGuess() {
std::vector<int> guess010(codeLength); // 初始化与密码(代码)长度相同的向量
std::string input; // 用于存储用户输入的字符串
std::cout << "请输入你的猜测 (" << codeLength << " 位数字): ";
std::cin >> input; // 读取用户输入的字符串
//先 检查 是否是 数字
for (int i = 0; i < codeLength; ++i) {
if (input[i] < '0' || input[i] > '9') {
std::cout << "您只能输入数字如“1234”,或在下面输入隐含命令……如E:退出,R重新初始化置信空间,其他命令不能告诉您,请联系[email protected].\n";
//
std::string inpu0t02; // 用于存储用户输入的字符串
std::cin >> inpu0t02; // 读取用户输入的字符串
//
if("c" == inpu0t02 || inpu0t02 == "z") {
showPossibleGuesses();
}//if
//
if (inpu0t02 == "e" || inpu0t02 == "E") {
return { 0,0,0,0 };
}//if
//
if ("r" == inpu0t02) {
//初始化 置信空间
initGuessArray(); // 初始化猜测数组
std::cout << "初始化 置信空间\n";
}
//
//
return getGuess(); // 递归调用以重新获取输入
}
}//for
// 检查输入字符串的长度是否等于代码长度
// 将字符串转换为整数并存储在向量中
for (int i = 0; i < codeLength; ++i) {
guess010[i] = input[i] - '0'; // 将字符转换为对应的整数
}
return guess010;
}
// 评估用户的猜测
std::pair<int, int> evaluateGuess(const std::vector<int>& guess, const std::vector<int>& secretCode) const {
int correctPosition = 0; // 位置正确的个数
int correctNumber = 0; // 数字正确但位置错误的个数
std::vector<int> codeCopy = secretCode; // 复制秘密代码用于评估
// 首先检查位置和数字都正确的
for (int i = 0; i < codeLength; ++i) {
if (guess[i] == codeCopy[i]) {
++correctPosition;
codeCopy[i] = -1; // 标记已匹配的数字
}
}
// 然后检查数字正确但位置不正确的
for (int i = 0; i < codeLength; ++i) {
for (int j = 0; j < codeLength; ++j) {
if (guess[i] == codeCopy[j] && guess[i] != secretCode[i]) {
++correctNumber;
codeCopy[j] = -1; // 标记已匹配的数字
break;
}
}
}
return { correctPosition, correctNumber };
}//evaluateGuess
// 概率空间probability space与 评估用户猜测 的比较
std::pair<int, int> probabilyE01valuateGuess(const std::vector<int>& probabily01space, const std::vector<int>& GuesSecrtCode) const {
int correctPosition = 0; // 位置正确的个数
int correctNumber = 0; // 数字正确但位置错误的个数
std::vector<int> codeCopy = GuesSecrtCode; // 复制秘密代码用于评估
// 首先检查位置和数字都正确的
for (int i = 0; i < codeLength; ++i) {
if (probabily01space[i] == codeCopy[i]) {
++correctPosition;
codeCopy[i] = -1; // 标记已匹配的数字
}
}
// 然后检查数字正确但位置不正确的
for (int i = 0; i < codeLength; ++i) {
for (int j = 0; j < codeLength; ++j) {
if (probabily01space[i] == codeCopy[j] && probabily01space[i] != GuesSecrtCode[i]) {
++correctNumber;
codeCopy[j] = -1; // 标记已匹配的数字
break;
}
}
}
return { correctPosition, correctNumber };
}//probabilyE01valuateGuess
//evaluateGuess
// 更新可能的猜测
void updatePossibleGuesses(const std::vector<int>& gues01Code02, int correctPositions, int correctNumbers) {
std::vector<int> tempGuesCode(codeLength);
for (int i1 = 0; i1 < Num10; ++i1) {
for (int i2 = 0; i2 < Num10; ++i2) {
for (int i3 = 0; i3 < Num10; ++i3) {
for (int i4 = 0; i4 < Num10; ++i4) {
if (!possibleGuesses[i1][i2][i3][i4]) continue; // 跳过不可能的组合
tempGuesCode = { i1, i2, i3, i4 };
int tempCorrectPositions, tempCorrectNumbers;
// std::tie(tempCorrectPositions, tempCorrectNumbers) = evaluateGuess(tempGuess);
std::tie(tempCorrectPositions, tempCorrectNumbers) = probabilyE01valuateGuess(tempGuesCode, gues01Code02);
if (tempCorrectPositions != correctPositions || tempCorrectNumbers != correctNumbers) //对不上号的那些 概率分布 全部标记为false4eq
{
possibleGuesses[i1][i2][i3][i4] = false; // 标记不可能的组合
}//if
}//fori4
}//fori3
}//fori2
}//fori1
}//updatePossibleGuesses
};
int main() {
// std::string fileName = "log_" + getCurrentTimeAsFileName() + ".txt";
Mastermind game(4, 9999); //9999 初始化游戏,设置代码长度为4,最大尝试次数为99
game.play(); // 开始游戏
return 0;
}//main
new240705A
#define _CRT_SECURE_NO_WARNINGS
#include <iostream> // 用于输入和输出
#include <vector> // 用于动态数组(向量)的使用
#include <cstdlib> // 用于随机数生成
#include <ctime> // 用于设置随机数种子
#include <tuple> // 用于 std::tie
#include <string> // 用于字符串
#include <ctime> // 用于时间
#include <fstream> // 用于文件操作
#define Num10 10 // 0~9
#define Num09 9 // 1~9
// 定义Mastermind游戏的类
class Mastermind {
public:
Mastermind(int codeLength, int maxAttempts)
: codeLength(codeLength), maxAttempts(maxAttempts) {
srand(static_cast<unsigned int>(time(0))); // 设置随机数种子
generateSecretCode(); // 生成秘密代码
initGuessArray(); // 初始化猜测数组
}
std::string getCurrentTimeAsFileName() {
// 获取当前时间
std::time_t now = std::time(nullptr);
// 将时间转换为本地时间
std::tm* now_tm = std::localtime(&now);
// 格式化时间为字符串
char buffer[60];// 100];
std::strftime(buffer, sizeof(buffer), "%y%m%d_%H%M-%S", now_tm);
return std::string(buffer);
}
void play() {
std::cout << "欢迎来到珠玑妙算!\n";
std::cout << "尝试猜测" << codeLength << "位秘密代码!\n";
std::cout << "您的猜测空间有 " << countPossibleGuesses() << " 种可能性\n";
//
std::string dateTime = getCurrentTimeAsFileName() + ".txt";
std::string fileName = "log" + dateTime;
std::cout << "fileName:" << fileName << std::endl;
std::ofstream logFile(fileName, std::ios::app);
//
for (int attempt = 1; attempt <= maxAttempts; ++attempt) {//for1100
std::cout << "您的猜测空间还有: " << countPossibleGuesses() << " 种可能性\n";
std::vector<int> currentGuess = getGuess(); // 获取用户的猜测
guesses.push_back(currentGuess); // 存储每次用户的猜测
int correctPositions, correctNumbers;
std::tie(correctPositions, correctNumbers) = evaluateGuess(currentGuess, secretCode); // 评估用户的猜测
{//代码块110
if (correctPositions == codeLength) { // 如果猜中所有位置1
std::cout << "恭喜你! 你猜中了秘密代码!!\n";
// //return;
}// 如果猜中所有位置1
}//代码块110
if (logFile.is_open()) {//if1100
logFile << "第 " << attempt << " 次尝试: ";
logFile << currentGuess[0] << currentGuess[1] << currentGuess[2] << currentGuess[3] << " ";
logFile << correctPositions << " 个位置(&数字都)正确, ";
logFile << correctNumbers << " 个数字正确但位置错误.\n";
}//if1100
else {
std::cout << "文件打开失败74line" << std::endl;
}
std::cout << "第 " << attempt << " 次尝试: ";
std::cout << correctPositions << " 个位置(&数字都)正确, ";
std::cout << correctNumbers << " 个数字正确但位置错误.\n";
if (correctPositions == codeLength) // 如果猜中所有位置22
{ // 如果猜中所有位置22
std::cout << "恭喜你! 你猜中了秘密代码!!密码是:" << secretCode[0] << secretCode[1] << secretCode[2] << secretCode[3] << "\n";
logFile<< "你猜中了秘密代码!密码是:" << secretCode[0] << secretCode[1] << secretCode[2]<< secretCode[3] << "\n";
//输入 "e" 或 "E" 退出游戏
std::cout << "输入 'e' 或 'E' 退出游戏: ";
std::string input; // 用于存储用户输入的字符串
std::cin >> input; // 读取用户输入的字符串
if (input == "e" || input == "E") {
logFile.close();
return;
}//if
//
if ("r" == input) {
//初始化 置信空间
initGuessArray(); // 初始化猜测数组
}
//
} // 如果猜中所有位置22
updatePossibleGuesses(currentGuess, correctPositions, correctNumbers); // 更新可能的猜测
logFile << "可能的猜测: ";
logFile << "可能的猜测: " << countPossibleGuesses() << " 种可能性\n";
logFile.flush();
}//for1100
logFile.close();
std::cout << "很遗憾,你用尽了所有尝试次数. 秘密代码是: ";
for (int num : secretCode) std::cout << num << " ";
std::cout << "\n";
}
private:
int codeLength; // 秘密代码的长度
int maxAttempts; // 最大尝试次数
std::vector<int> secretCode; // 秘密代码的向量
std::vector<std::vector<int>> guesses; // 所有用户的猜测
bool possibleGuesses[Num10][Num10][Num10][Num10]; // 提供猜测集合的全体
// 生成秘密代码
void generateSecretCode() {
for (int i = 0; i < codeLength; ++i) {
secretCode.push_back(1 + rand() % Num09);// 9); // 生成1-9之间的随机数
}
}
// 初始化猜测数组
void initGuessArray() {
for (int i1 = 1; i1 < Num10; ++i1) {
for (int i2 = 1; i2 < Num10; ++i2) {
for (int i3 = 1; i3 < Num10; ++i3) {
for (int i4 = 1; i4 < Num10; ++i4) {
possibleGuesses[i1][i2][i3][i4] = true; // 初始化猜测数组
}
}
}
}
}
// 统计可能的猜测数量
int countPossibleGuesses() const {
int possibleCount = 0;
for (int i1 = 1; i1 < Num10; ++i1) {
for (int i2 = 1; i2 < Num10; ++i2) {
for (int i3 = 1; i3 < Num10; ++i3) {
for (int i4 = 1; i4 < Num10; ++i4) {
if (possibleGuesses[i1][i2][i3][i4]) {
++possibleCount;
}
}
}
}
}
return possibleCount;
}
// 获取用户的猜测
std::vector<int> getGuess() {
std::vector<int> guess010(codeLength); // 初始化与密码(代码)长度相同的向量
std::string input; // 用于存储用户输入的字符串
std::cout << "请输入你的猜测 (" << codeLength << " 位数字): ";
std::cin >> input; // 读取用户输入的字符串
//先 检查 是否是 数字
for (int i = 0; i < codeLength; ++i) {
if (input[i] < '0' || input[i] > '9') {
//std::cout << "输入无效. 请只输入数字.\n";
//
std::string inpu0t01; // 用于存储用户输入的字符串
std::cin >> inpu0t01; // 读取用户输入的字符串
if (inpu0t01 == "e" || inpu0t01 == "E") {
return { 0,0,0,0 };
}//if
//
if ("r" == inpu0t01) {
//初始化 置信空间
initGuessArray(); // 初始化猜测数组
std::cout << "初始化 置信空间\n";
}
//
//
return getGuess(); // 递归调用以重新获取输入
}
}//for
// 检查输入字符串的长度是否等于代码长度
// 将字符串转换为整数并存储在向量中
for (int i = 0; i < codeLength; ++i) {
guess010[i] = input[i] - '0'; // 将字符转换为对应的整数
}
return guess010;
}
// 评估用户的猜测
std::pair<int, int> evaluateGuess(const std::vector<int>& guess, const std::vector<int>& secretCode) const {
int correctPosition = 0; // 位置正确的个数
int correctNumber = 0; // 数字正确但位置错误的个数
std::vector<int> codeCopy = secretCode; // 复制秘密代码用于评估
// 首先检查位置和数字都正确的
for (int i = 0; i < codeLength; ++i) {
if (guess[i] == codeCopy[i]) {
++correctPosition;
codeCopy[i] = -1; // 标记已匹配的数字
}
}
// 然后检查数字正确但位置不正确的
for (int i = 0; i < codeLength; ++i) {
for (int j = 0; j < codeLength; ++j) {
if (guess[i] == codeCopy[j] && guess[i] != secretCode[i]) {
++correctNumber;
codeCopy[j] = -1; // 标记已匹配的数字
break;
}
}
}
return { correctPosition, correctNumber };
}//evaluateGuess
// 概率空间probability space与 评估用户猜测 的比较
std::pair<int, int> probabilyE01valuateGuess(const std::vector<int>& probabily01space, const std::vector<int>& GuesSecrtCode) const {
int correctPosition = 0; // 位置正确的个数
int correctNumber = 0; // 数字正确但位置错误的个数
std::vector<int> codeCopy = GuesSecrtCode; // 复制秘密代码用于评估
// 首先检查位置和数字都正确的
for (int i = 0; i < codeLength; ++i) {
if (probabily01space[i] == codeCopy[i]) {
++correctPosition;
codeCopy[i] = -1; // 标记已匹配的数字
}
}
// 然后检查数字正确但位置不正确的
for (int i = 0; i < codeLength; ++i) {
for (int j = 0; j < codeLength; ++j) {
if (probabily01space[i] == codeCopy[j] && probabily01space[i] != GuesSecrtCode[i]) {
++correctNumber;
codeCopy[j] = -1; // 标记已匹配的数字
break;
}
}
}
return { correctPosition, correctNumber };
}//probabilyE01valuateGuess
//evaluateGuess
// 更新可能的猜测
void updatePossibleGuesses(const std::vector<int>& gues01Code02, int correctPositions, int correctNumbers) {
std::vector<int> tempGuesCode(codeLength);
for (int i1 = 1; i1 < Num10; ++i1) {
for (int i2 = 1; i2 < Num10; ++i2) {
for (int i3 = 1; i3 < Num10; ++i3) {
for (int i4 = 1; i4 < Num10; ++i4) {
if (!possibleGuesses[i1][i2][i3][i4]) continue; // 跳过不可能的组合
tempGuesCode = { i1, i2, i3, i4 };
int tempCorrectPositions, tempCorrectNumbers;
// std::tie(tempCorrectPositions, tempCorrectNumbers) = evaluateGuess(tempGuess);
std::tie(tempCorrectPositions, tempCorrectNumbers) = probabilyE01valuateGuess(tempGuesCode, gues01Code02);
if (tempCorrectPositions != correctPositions || tempCorrectNumbers != correctNumbers) {
possibleGuesses[i1][i2][i3][i4] = false; // 标记不可能的组合
}
}
}
}
}
}
};
int main() {
// std::string fileName = "log_" + getCurrentTimeAsFileName() + ".txt";
Mastermind game(4, 9999); //9999 初始化游戏,设置代码长度为4,最大尝试次数为99
game.play(); // 开始游戏
return 0;
}
三、old240701
文章评论