C++珠玑妙算

本文介绍了一个名为珠玑妙算的游戏制作过程,玩家需猜测系统生成的无重复随机数。游戏规则包括系统随机生成不同数字的数位,玩家每轮猜测后会得到数字和位置正确个数的提示。代码实现包括获取挑战位数、生成随机数、检查输入合法性等功能,并提供了完整的游戏运行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

最近一直想做珠玑妙算的小游戏,今天就给大家分享一下。

效果

1
2

系统制作

首先我们来做头文件,里面定义一个class game_system

public

public:
	void startGame() {
    	PrintRules();
   	 	RunGame();
	}

private

变量

string guess, ans; //答案和猜测
int digit; //挑战位数

PrintRules

这段代码简单粗暴,用来解释规则:
系统随机生成n位的随机数,没有任意位是相同的。然后你猜一个数,猜完系统会给你两个提示。
第一个数代表数字和位置都猜对的数字个数,第二个数代表只有数字猜对的数字个数。

void PrintRules() {
        printf("                              MASTERMIND\n");
        printf("The rules of this game is:\n  1. The computer will randomly create a number.");
        printf("And every number in this number is different.\n");
        printf("  2. You will guess the number in each round, and the computer will give you two hints.\n");
        printf("The first number output is the number of numbers and positions guessed correctly");
        printf(", and the second number output is the number of numbers guessed correctly only.GoodLuck!\n");
    }

GetDigit

这段代码作用是获得玩家希望挑战的数字位数(3到7之间),这个值难度比较适中。当然,你可以自行根据需要调整,注意最大值不要超过10。

void GetDigit() {
    printf("Please enter the digit of the number ");
    printf("that you want to challange in this round of 'MASTERMIND'(3 - 7):");
    for (;;) {
        cin >> digit;
        if (digit <= 7 && digit >= 3) break;
        else printf("\nWrong input, please enter again\n");
    }
    printf("\n");
}

randomNumber

这段代码用来创作没有重复数位且第一位不是0的随机数

void randomNumber() {
    string choice = "123456789";
    srand(time(nullptr));
    int r = rand() % choice.size(); //创建从0到8的随机数做选择的下标
    ans += choice[r]; //答案后面加上随机选择的字符
    choice.erase(r, 1); //删除已选择过的选项
    choice += '0'; // 最高为不是零,将'0'加入选项
    for (int i = 1; i < digit; ++i) {
        srand(time(nullptr));
        r = rand() % choice.size();
        ans += choice[r];
        choice.erase(r, 1);
    }
}

获得合法输入

checkInput
bool checkInput() {
    string comp;
    for (int i = 0; i < guess.size(); ++i) {
        if (count(comp.begin(), comp.end(), guess[i]) > 0) return false; //判断是否重复
        else comp += guess[i]; //否则将遍历到的字符存入已出现字符串里
    }
    if (guess.size() != digit) return false; //若字符串大小超过选择挑战位数,返回假
    return true; //若合法,返回真
}
getInput
void getInput() {
    for (;;) {
        cin >> guess;
        if (checkInput()) break; //不停输入直到合法
        else printf("Wrong input, please enter again:");
    }
}

RunGame

函数都写完了,现在我们写运行游戏的函数。

void RunGame() {
    GetDigit(); //获得挑战位数
    randomNumber(); //获得随机数
    for (;;) {
        int all = 0, half = 0; //创建变量:数位皆猜对个数,数猜对个数
        getInput();
        for (int i = 0; i < digit; ++i) {
            if (ans[i] == guess[i]) ++all; //若位置和数字都猜对则提示第一个数加1
            else {
                for (auto j : guess) {
                    if (ans[i] == j) { //如果数字猜对则提示第二个数加1
                        ++half;
                        break;
                    }
                }
            }
        }
        if (all == digit)  { //若全部数位猜对,游戏胜利
            printf("Correct!");
            break;
        }
        else printf("%d%c%d\n", all, ' ', half); //否则输出提示
    }
}

头文件

#ifndef ABACUSCALCULATION_H_INCLUDED
#define ABACUSCALCULATION_H_INCLUDED

#include <iostream>
#include <algorithm>
#include <ctime>
#include <vector>
#include <string>
using namespace std;

class game_system
{
public:
    void startGame() {
        PrintRules();
        RunGame();
    }
private:
    string guess, ans;
    int digit;
    void RunGame() {
        GetDigit();
        randomNumber();
        for (;;) {
            int all = 0, half = 0;
            getInput();
            for (int i = 0; i < digit; ++i) {
                if (ans[i] == guess[i]) ++all;
                else {
                    for (auto j : guess) {
                        if (ans[i] == j) {
                            ++half;
                            break;
                        }
                    }
                }
            }
            if (all == digit)  {
                printf("Correct!");
                break;
            }
            else printf("%d%c%d\n", all, ' ', half);
        }
    }
    void PrintRules() {
        printf("                              MASTERMIND\n");
        printf("The rules of this game is:\n  1. The computer will randomly create a number.");
        printf("And every number in this number is different.\n");
        printf("  2. You will guess the number in each round, and the computer will give you two hints.\n");
        printf("The first number output is the number of numbers and positions guessed correctly");
        printf(", and the second number output is the number of numbers guessed correctly only.GoodLuck!\n");
    }
    void GetDigit() {
        printf("Please enter the digit of the number ");
        printf("that you want to challange in this round of 'MASTERMIND'(3 ¡ª 7):");
        for (;;) {
            cin >> digit;
            if (digit <= 7 && digit >= 3) break;
            else printf("\nWrong input, please enter again\n");
        }
        printf('\n');
    }
    void randomNumber() {
        string choice = "123456789";
        srand(time(nullptr));
        int r = rand() % choice.size();
        ans += choice[r];
        choice.erase(r, 1);
        choice += '0';
        for (int i = 1; i < digit; ++i) {
            srand(time(nullptr));
            r = rand() % choice.size();
            ans += choice[r];
            choice.erase(r, 1);
        }
    }
    bool checkInput() {
        string comp = "";
        for (int i = 0; i < guess.size(); ++i) {
            if (count(comp.begin(), comp.end(), guess[i]) > 0) return false;
            else comp += guess[i];
        }
        return guess.size() == digit;
        return true;
    }
    void getInput() {
        for (;;) {
            cin >> guess;
            if (checkInput()) break;
            else printf("Wrong input, please enter again:");
        }
    }
};

#endif // ABACUSCALCULATION_H_INCLUDED

请将此文件存放于正确的路径:xxx\MinGW\lib\gcc\x86_64-w64-mingw32\8.1.0\include\c++
这个路径是Codeblocks::IDE的路径,如有其他需求请自行调整。
否则也可以随便放一个位置然后

#include <盘名:\\路径\AbacusCalculation.h>

main()

最后,创建新的C++源文件,代码如下:

#include <AbacusCalculation.h> // 路径名请自行调整

int main() {
    game_system game;
    game.startGame();
}

Github 源代码链接

github

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]: # A加1 answer[0] += 1 # 将guess和solution中对应位置的字符都替换为空 guess = guess.replace(_, "", 1) solution = solution.replace(_, "", 1) else: # 否则j加1 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、付费专栏及课程。

余额充值