密码猜谜游戏

Password guess game

本文关键字:游戏 密码      更新时间:2023-10-16

感谢您帮助我一直在尝试进行密码猜测匹配的人,但我遇到了一些问题。问题是例如我的随机密码生成是 1624,然后当输入时问我输入猜测密码时,我输入 1325。因此,输出为:OXOX 。O 表示正确,X 表示不正确

但是,如何使用if语句指定思维。目前,我将生成密码和猜测密码的每个位置都存储在数组中。

这是我的想法:

if ( x[0] == y[0] && x[1] == y[1] && x[2] == y[2] && x[3] == y[3] ){
                cout << " OOOO" << endl; 
  } 

*****校正:**

如果使用 x[i] == y[i] 如果我去 i = 1 怎么办? 如何仍然比较位置 0,1,2,3 ?我需要单独匹配每个角色!现在,如果我 = 0,我只会比较 0,其余的将被忽略!我的意思是:

生成密码:1234

整数 i = 0;

x = 0;猜测输入:1845输出:OXXX

整数 i = 1;

x = 1;猜测输入:1200输出:OOXX

整数 i = 2;

x = 2;猜测输入:0230输出 X00X

这是我的代码现在的样子

void randomClass () {
        std::generate_n(std::back_inserter(s), 10,
                        []() { static char c = '0'; return c++; });
        // s is now "0123456789"
        std::mt19937 g(std::random_device{}());
        // if 0 can't be the first digit
        std::uniform_int_distribution<size_t> dist(1, 9);
        std::swap(s[0], s[dist(g)]);
        // shuffle the remaining range
        std::shuffle(s.begin() + 1, s.end(), g); // non-deprecated version
        // convert only first four
        x = std::stoul(s.substr(0, 4));
        std::cout<<x << std::endl;
        //Store array
        y[0] = x/1000;
        y[1] = x/100%10;
        y[2] = x /10%10;
        y[3] =  x %10;


        }
    void guess (string b) {
        int x[4];
        for ( int i =0; i < 4; i++) {
        cout << "Make a guess:" << endl;
        getline(cin,b);
        int u = atoi(b.c_str());
        x[0] = u/1000;
        x[1] = u/100%10;
        x[2] = u /10%10;
        x[3] = u %10;


        }
    }
};

而不是您的所有组合...

if ( x[0] == y[0] && x[1] == y[1] && x[2] == y[2] && x[3] == y[3] ){
    cout << " OOOO" << endl; 
}

。一次只需处理一个字符...

for (int i = 0; i < 4; ++i)
    cout << (x[i] == y[i] ? 'O' : 'X');
cout << 'n';

将数字保留为字符串。然后可以使用数组索引访问该数字。

比较guess[2]比除法然后使用模提取数字更容易。

希望对您有所帮助

#include <iostream>
#include <math.h>
int main()
{
    //  get input from user
    std::string input;
    std::cin>>input;
    //  set password
    std::string password = "1234";
    //  find size of lowest element string
    int size = fmin(input.size(),password.size());
    //  loop through all elements
    for(int i=0;i<size;i++)
    {
        //  if current element of input is equal to current element of password, print 'x', else print '0'
        std::cout<<(input[i]==password[i]?"X":"0");
    }
}