Monday, 4 March 2013

Activity 8: Random number generator


Activity 8: Random number generator
Use a new function, rand() to generate a random number. You will also need to use
srand() to provide an initial seed value so that rand() does not always start at the same
place. We will tie srand() to the current time (in seconds past midnight) so that it has a
different seed value each time it is used.
·  Design an ActiveX control button (called Dice) to generate a random number between 1
and 6. Use the MFC ActiveX ControlWizard and base it on the BUTTON class in Step 2.
·  In ClassWizard-> ActiveX events tab-> Add Event, select Click as external name and
OK. In ClassWizard-> Automation tab-> Add method, add a method called Random
giving it the return type short. In ClassWizard-> Message Maps connect CDiceCtrl to
WM_LBUTTONDOWN to create the OnLButtonDown() event-handler.
·  Open DiceCtl.cpp and add the following lines of code.
CDiceCtrl::CDiceCtrl()
{
InitializeIIDs(&IID_DDice, &IID_DDiceEvents);
// TODO: Initialize your control's instance data here.
// This line is to change the button’s caption.
SetText("Roll the dice!");
}
.
.
void CDiceCtrl::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
FireClick();
COleControl::OnLButtonDown(nFlags, point);
}
short CDiceCtrl::Random()
{
// TODO: Add your dispatch handler code here
int i;
/* Seed the random-number generator with current time so
that the numbers will be different every time */
srand( (unsigned)time( NULL ) );
i = rand()% 6 + 1;
return i;
}

·  Start a new dialog based application (RollTheDice) and add the new Dice Control (in
Projects, Add to projects, Components and Controls). Place on the dialog box along with
an edit box to display the result each time the Dice is clicked.
·  Using ClassWizard->Member Variables, add m_text (as an int) to IDC_EDIT1 and
m_button (of the CDice class) to IDC_DICECTRL1. Change to Message Maps tab and
connect IDC_DICECTRL1 to the Click event to create the event-handler
OnClickDicectrl1().
·  Add the bold code to RollTheDiceDlg.cpp.
void CRollTheDiceDlg::OnClickDicectrl1()
{
// TODO: Add your control notification handler code here
/*Use char() to typecast integer returned by Random() so that it
can be assigned to the CString variable m_text. */
m_text = char (m_button.Random());
UpdateData(false);
}
·  Build the program, debug any errors and run it.

No comments:

Post a Comment