我正在尝试同时显示2个随机骰子。我知道我需要将模具编号转换为资源ID,但如何?这是我到目前为止的代码...

有什么好的编码方式?

    void CMFCApplication5Dlg::OnBnClickedButton1()
{

    // randomize random number generator using current time
   srand( (unsigned)time( NULL ) );

    // pick random die values
    int die1 = 1 + rand() % 6; // first die roll
    int die2 = 1 + rand() % 6; // second die roll


    pPCAvatar = (CStatic *) GetDlgItem(PC_AVATAR);
    pIDCPicture = (CStatic *) GetDlgItem(IDC_PICTURE2);

    //image for the avatar
    CString Image1;
    CString Image2;
    CString Image3;
    CString Image4;
    CString Image5;
    CString Image6;

    //initialize entity from the constructor
    Image1 = "pcture1.bmp";  // die face # 1
    Image2 = "pcture2.bmp";  // die face # 2
    Image3 = "pcture3.bmp";  // die face # 3
    Image4 = "pcture4.bmp";  // die face # 4
    Image5 = "pcture5.bmp";  // die face # 5
    Image6 = "pcture6.bmp";  // die face # 6




    // TODO: Add your control notification handler code here
}

最佳答案

一种方法是使用switch/case语句。

CString dieImage;

switch(dieValue)
{
case 0:
    dieImage = "filename1";
    break;

case 1:
    dieImage = "filename2";
    break;

// Rest of case statements

}


另一种方法是使用数组。

const CString dieImages[6] =
{
    "filename1",
    "filename2",
    "filename3",
    "filename4",
    "filename5",
    "filename6"
};

const CString& dieImage = dieImages[dieValue];


如果要使用多个值,可以将其放入函数并将数组设为静态成员变量

const CString& GetDieImage(int dieValue) const
{
    return dieImages[dieValue];
}


只是这样称呼它

const CString& dieImage1 = GetDieImage(dieValue1);
const CString& dieImage2 = GetDieImage(dieValue2);


要使用数组来管理图像名称,您可以将代码更改为如下所示。

void CMFCApplication5Dlg::OnBnClickedButton1()
{
    static const CString dieImages[6] =
    {
        "filename1",
        "filename2",
        "filename3",
        "filename4",
        "filename5",
        "filename6"
    };

    // pick random die values
    const int die1 = 1 + rand() % 6; // first die roll
    const int die2 = 1 + rand() % 6; // second die roll

    const CString die1image = dieImages[die1];
    const CString die2image = dieImages[die2];


    // ... rest of your code goes here ...
}

关于c++ - 随机位图将数字转换为资源ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16247799/

10-16 19:34