C++珠玑妙算_最萌皮卡丘的博客-程序员宝宝

技术标签: 算法  C++  c++  小程序  

前言

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

效果

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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/peter_code/article/details/125415267

智能推荐

spring学习bug记录:不再支持目标选项 1.5。请使用 1.6 或更高版本_努力LT的博客-程序员宝宝

Q:[ERROR] COMPILATION ERROR : [INFO] ------------------------------------------------------------- [ERROR] 不再支持源选项 5。请使用 6 或更高版本。 [ERROR] 不再支持目标选项 1.5。请使用 1.6 或更高版本。A:pom.xml文件中增加maven编译的jdk版本...

Google笔试题整理(超全!)附部分答案_京程好2e6b9f_阳光岛主的博客-程序员宝宝

[笔试题] Google笔试题整理(超全!)附部分答案写出这样一个函数 ,输入一个 n, 输出从1到这个数字之间的出现的1的个数,比如f(13)等于6; f(9)等于1; 网上有很多这道题的解法,大多采用穷举法。这把这个算法题变成了程序设计,这道题,我认为是总结一个递推公式,然后用递推法实现,比较好。后来在网上考证了一下,这道题本来也是让总结一个数学函数即可,无需编程。既然写了,就贴出来,发表一下

Python enumerate() 函数_xiucai_cs的博客-程序员宝宝

enumerate()为python的内置函数,用于将可遍历的元祖,列表,或字符串进行序列化(每一个元素弄上标号)code:seq = ['one', 'two', 'three']for i, element in enumerate(seq): print(i, element)成果:错误分析:如果直接多写一个变量的话,则会显示too many values to unpac...

java 1.8 override_Java @override报错的解决方法_lyongsment的博客-程序员宝宝

今天在把eclipse工程拷贝到另一个电脑上的时候出现总是@override报错,提示是将@override移除就好了,但是项目中很多这个注解的存在,Java小白的我觉的就算不知道这个编制存在与不存在的区别,但是既然存在了,肯定有他的用处,而且项目中有好多地方存在@override,总不能全部移除吧。就查了一下,就此总结一下出错原因:开始以为是jar包引用的问题,尝试过更改jar包,没有用,才知道...

对输入的字符串进行处理:把单词中间有多个空格的调整为1个空格,同时将单词的首字母变为大写,后面的变为小写_Ning静致远的博客-程序员宝宝

1.对输入的字符串进行处理:把单词中间有多个空格的调整为1个空格,同时将单词的首字母变为大写,后面的变为小写package cn.syn.ex01;/** * 对输入的字符串进行处理:把单词中间有多个空格的调整为1个空格,同时将单词的首字母变为大写,后面的变为小写 * @author 温暖wk * */public class Demo05 { public static voi...

随便推点

pandas中Series和Dataframe的画图方法_我是小蚂蚁的博客-程序员宝宝

前言在pandas中,无论是series还是dataframe都内置了.plot()方法,可以结合plt.show()进行很方便的画图。Series.plot() 和 Dataframe.plot()参数data : Serieskind : str‘line’ : line plot (default)‘bar’ : vertical bar plot‘barh’ : horizo...

一句话理解到底怎么看神经网络的层数_神经网络有几层怎么看_爱学习滴好青年的博客-程序员宝宝

在计算神经网络的层数时,只计算具有计算能力的层,而输入层只是将数据进行输入,无计算过程,所以层数:隐藏层层数+1个输出层。

POJ1837 [DP水题]_软件丶Crazyxu的博客-程序员宝宝

DescriptionGigel has a strange &quot;balance&quot; and he wants to poise it. Actually, the device is different from any other ordinary balance. It orders two arms of negligible weight and each arm's length is 1...

PHP的SHA256WithRSA签名和验签_php sha256 with rsa签名_凯鑫BOSS的博客-程序员宝宝

//生成 sha256WithRSA 签名function getSign($content, $privateKey){ $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($privateKey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----"; $key = openssl_get_privatekey($privateKey

Qt三方库开发技术:QXlsx介绍、编译和使用_qxlsx 编译_长沙红胖子Qt的博客-程序员宝宝

若该文为原创文章,未经允许不得转载原博主博客地址:https://blog.csdn.net/qq21497936原博主博客导航:https://blog.csdn.net/qq21497936/article/details/102478062本文章博客地址:https://blog.csdn.net/qq21497936/article/details/108292147各位读者,知识无穷而人力有穷,要么改需求,要么找专业人士,要么自己研究红胖子(红模仿)的博文大全:开发技术集合(包含Qt实用

win10系统在安装后无法登录账户,或出现0x80190001错误_玖熙浩的博客-程序员宝宝

解决本文引用这位老哥的骚操作,原文链接:https://blog.csdn.net/qq_36393978/article/details/1074137911、在win10搜索框输入cmd,右键选择管理员身份运行;2、在弹出的命令框内输入:netsh int ip reset,回车;【会提示需要重启计算机,不用管,继续执行第三步】3、在命令框继续输入:netsh winsock reset,回车;重启计算机;重新启动之后看是否恢复正常,若还存在0x80190001这样的错误,请继续.