好玩的珠玑妙算-加作弊带概率空间+日志存储240705mindMaster

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重新初始化置信空间,其他命令不能告诉您,请联系41313989@qq.com.\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重新初始化置信空间,其他命令不能告诉您,请联系41313989@qq.com.\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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python珠玑妙算是一道猜数字游戏,游戏规则如下:系统随机生成一个长度为4的字符串,字符串由RGBY四个字符组成,且字符可以重复。玩家需要在10次机会内猜出系统生成的字符串,每次猜测后系统会给出两个数字,分别表示猜对了几个字符且位置正确(称为A),以及猜对了几个字符但位置不正确(称为B)。玩家需要根据系统给出的A和B来推测系统生成的字符串。 以下是一个Python珠玑妙算的实现,其中引用和引用分别提供了两种不同的实现方式: ```python # 引入必要的库 import random from typing import List # 实现珠玑妙算游戏 class Solution: def masterMind(self, solution: str, guess: str) -> List[int]: # 初始化变量 j = 0 answer = [0, 0] # 遍历solution字符串 for _ in solution: # 如果当前字符与guess字符串中对应位置的字符相同 if _ == guess[j]: # A1 answer[0] += 1 # 将guess和solution中对应位置的字符都替换为空 guess = guess.replace(_, "", 1) solution = solution.replace(_, "", 1) else: # 否则j1 j += 1 # 遍历guess字符串 for _ in guess: # 如果当前字符不为空 if _ != "": # 计算guess和solution中当前字符的出现次数 count1 = guess.count(_) count2 = solution.count(_) # 如果guess中当前字符出现次数大于1,将guess中所有当前字符都替换为空 if count1 > 1: guess = list(filter(lambda x: x != _, guess)) # B上guess和solution中当前字符出现次数的最小值 answer[1] += min(count2, count1) # 返回结果 return answer # 生成随机字符串 def generate_random_string(): colors = ['R', 'G', 'B', 'Y'] return ''.join(random.choices(colors, k=4)) # 主函数 if __name__ == '__main__': # 初始化变量 solution = generate_random_string() guess = '' count = 0 # 循环10次 while count < 10: # 获取用户输入 guess = input('请输入你猜测的字符串(由RGBY四个字符组成,且字符可以重复):') # 判断用户输入是否合法 if len(guess) != 4 or not all(c in 'RGBY' for c in guess): print('输入不合法,请重新输入!') continue # 调用珠玑妙算函数 result = Solution().masterMind(solution, guess) # 输出结果 print('A:{}, B:{}'.format(result[0], result[1])) # 如果猜对了,退出循环 if result[0] == 4: print('恭喜你猜对了!') break # 否则次数1 count += 1 # 如果次数用完了,输出答案 if count == 10: print('很遗憾,你没有在规定次数内猜对,答案是:{}'.format(solution)) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值