0

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

1 回答 1

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 ...
}
于 2013-04-27T03:06:43.610 回答