随机位图将数字转换为资源ID

时间:2013-04-27 02:47:55

标签: c++ visual-studio-2012 mfc

我正在尝试同时显示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
}

1 个答案:

答案 0 :(得分:2)

一种方法是使用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 ...
}