Title: AC21001 Lab 1
1AC21001 - Lab 1
2Rules of nim
- Two players
- Start with N counters
- First player takes 1, 2, or 3 counters
- Second player does the same
- Player who takes last counter loses
- Demo of program
3Requirements
- Text version of the game
- Ask human who goes first
- For each turn
- Print number of counters left
- If computers move, select number and make move
(random or strategy) - If humans move, ask how many counters to take
(check for errors) - Check if game over
- Ask for another game
- Keep track of scores
4Lab 1 design
- Use brainstorming (on your own or with a friend)
- List properties required
- Identify properties that can be implemented with
primitive data types - Sort them into classes
- Assign other properties to classes hierarchically
- Using your design
- Write C class definitions in header files
- Add a Test() function to each class
5Candidates for classes
- Everything in one class?
- Or....
- Class for one game of nim
- Another class for scores
- Or....
- Classes for computer and human players
- Another class for game itself
6Everything in one class
- Properties
- Counters left
- Games played
- Games won (by human)
- Actions
- Play first?
- Computer move
- Human move
- Adjust scores
- Print scores
- Game over?
- Play again?
7Relations
8Game scores classesGame class
- Actions
- Play first?
- Computer move
- Human move
9Game scores classesScores class
- Properties
- Games played
- Games won
- Actions
- Adjust scores
- Print scores
- Play again?
10Relations
11Computer/human/game classesComputer class
12Computer/human/game classesHuman class
13Computer/human/game classesGame class
- Properties
- Counters left
- Games played
- Games won
- Actions
- Play first?
- Adjust scores
- Print scores
- Game over?
- Play again?
14Class communication
- Game class must call functions in scores class
- How to do this?
- Communicate via main( ) function
15Communication
main()
Game class
Counters left
Play
Play first?
Computer move
Human move
Game over?
16Class communication in C
Declare a Game pointer
- void main()
-
- Game nimGame
- Scores nimScores
- int result
- nimGame new Game()
- nimScores new Scores()
- // Single play of game...
- result nimGame-gtPlay()
- nimScores-gtAdjustScores(result)
- nimScores-gtPrintScores()
17Class communication in C
Declare a Scores pointer
- void main()
-
- Game nimGame
- Scores nimScores
- int result
- nimGame new Game()
- nimScores new Scores()
- // Single play of game...
- result nimGame-gtPlay()
- nimScores-gtAdjustScores(result)
- nimScores-gtPrintScores()
18Class communication in C
Create Game and Scores objects
- void main()
-
- Game nimGame
- Scores nimScores
- int result
- nimGame new Game()
- nimScores new Scores()
- // Single play of game...
- result nimGame-gtPlay()
- nimScores-gtAdjustScores(result)
- nimScores-gtPrintScores()
19Class communication in C
Call Play() function of Game class to start the
game off
- void main()
-
- Game nimGame
- Scores nimScores
- int result
- nimGame new Game()
- nimScores new Scores()
- // Single play of game...
- result nimGame-gtPlay()
- nimScores-gtAdjustScores(result)
- nimScores-gtPrintScores()
20Class communication in C
Play() calls interior Game class functions to
play game
- void main()
-
- Game nimGame
- Scores nimScores
- int result
- nimGame new Game()
- nimScores new Scores()
- // Single play of game...
- result nimGame-gtPlay()
- nimScores-gtAdjustScores(result)
- nimScores-gtPrintScores()
21Class communication in C
When game ends, Play() returns humans score (1
win 0 lose)
- void main()
-
- Game nimGame
- Scores nimScores
- int result
- nimGame new Game()
- nimScores new Scores()
- // Single play of game...
- result nimGame-gtPlay()
- nimScores-gtAdjustScores(result)
- nimScores-gtPrintScores()
22Class communication in C
result is passed to AdjustScores() function of
Scores class
- void main()
-
- Game nimGame
- Scores nimScores
- int result
- nimGame new Game()
- nimScores new Scores()
- // Single play of game...
- result nimGame-gtPlay()
- nimScores-gtAdjustScores(result)
- nimScores-gtPrintScores()
23Class communication in C
PrintScores function of Scores class is called to
print scores on screen
- void main()
-
- Game nimGame
- Scores nimScores
- int result
- nimGame new Game()
- nimScores new Scores()
- // Single play of game...
- result nimGame-gtPlay()
- nimScores-gtAdjustScores(result)
- nimScores-gtPrintScores()
24Computer nim strategies
- Two options
- Play randomly
- Play to win
- Random play
- Use random number generator to choose number of
counters (1, 2, 3, or number left) - Winning strategy
- Try to work it out...
25Input/output in C
- To write to console, use cout
- cout ltlt variable ltlt string ltlt endl
- To read from console into a variable, use cin
- cin gtgt variable1 gtgt variable 2
26Input/output in C
- include ltiostreamgt
- using namespace std
- void main()
-
- int AVariable
- cout ltlt "Please enter a number" ltlt endl
- cin gtgt AVariable
- cout ltlt "The value of AVariable is " ltlt
- AVariable ltlt endl
Always include these 2 lines whenever using cout
or cin
27Input/output in C
- include ltiostreamgt
- using namespace std
- void main()
-
- int AVariable
- cout ltlt "Please enter a number" ltlt endl
- cin gtgt AVariable
- cout ltlt "The value of AVariable is " ltlt
- AVariable ltlt endl
Declare an int variable AVariable
28Input/output in C
- include ltiostreamgt
- using namespace std
- void main()
-
- int AVariable
- cout ltlt "Please enter a number" ltlt endl
- cin gtgt AVariable
- cout ltlt "The value of AVariable is " ltlt
- AVariable ltlt endl
Use cout to print a prompt requesting input
29Input/output in C
- include ltiostreamgt
- using namespace std
- void main()
-
- int AVariable
- cout ltlt "Please enter a number" ltlt endl
- cin gtgt AVariable
- cout ltlt "The value of AVariable is " ltlt
- AVariable ltlt endl
Use cin to read in a value from keyboard
30Input/output in C
- include ltiostreamgt
- using namespace std
- void main()
-
- int AVariable
- cout ltlt "Please enter a number" ltlt endl
- cin gtgt AVariable
- cout ltlt "The value of AVariable is " ltlt
- AVariable ltlt endl
Use cout again to print out the value
31Error checking in input
- Previous program has a problem
- If non-numeric value entered, goes into infinite
loop or loads garbage - Does not provide an error check for incorrect
input - Can solve this with following code
32Error-free cin
cin actually returns a bool flag indicating
whether data was read successfully
- include ltiostreamgt
- using namespace std
- void main()
-
- int AVariable
- cout ltlt "Please enter a number" ltlt endl
- while (!(cin gtgt AVariable))
-
- cin.clear()
- cin.ignore(80, '\n')
- cout ltlt "There was an error!" ltlt endl
-
- cout ltlt "You entered " ltlt AVariable ltlt endl
33Error-free cin
If cin returns 'false', entered data was not in
correct format
- include ltiostreamgt
- using namespace std
- void main()
-
- int AVariable
- cout ltlt "Please enter a number" ltlt endl
- while (!(cin gtgt AVariable))
-
- cin.clear()
- cin.ignore(80, '\n')
- cout ltlt "There was an error!" ltlt endl
-
- cout ltlt "You entered " ltlt AVariable ltlt endl
34Error-free cin
Clear input buffer, ignore up to 80 characters
(or until \n read) and print error message
- include ltiostreamgt
- using namespace std
- void main()
-
- int AVariable
- cout ltlt "Please enter a number" ltlt endl
- while (!(cin gtgt AVariable))
-
- cin.clear()
- cin.ignore(80, '\n')
- cout ltlt "There was an error!" ltlt endl
-
- cout ltlt "You entered " ltlt AVariable ltlt endl
35bool variables in C
- C has a built-in bool data type
- bool is a reserved word in C
- a bool variable may be either true or
false - true and false are also reserved words
36bool variables in C
- C has a built-in bool data type
- bool is a reserved word in C
- a bool variable may be either true or
false - true and false are also reserved words
- bool myBoolVar
- myBoolVar true
- myBoolVar false
- if (myBoolVar true) ...
- // or just
- if (myBoolVar) ...
37Random numbers in Visual C
Header files needed for random number initializati
on and use
- includeltstdlib.hgt
- includelttime.hgt
- includeltiostreamgt
- using namespace std
- int main()
-
- int i
-
- srand( (unsigned)time( NULL ) )
- for (i 0 i lt 10 i)
- cout ltlt rand() 100 1 ltlt endl
-
38Random numbers in Visual C
- includeltstdlib.hgt
- includelttime.hgt
- includeltiostreamgt
- using namespace std
- int main()
-
- int i
-
- srand( (unsigned)time( NULL ) )
- for (i 0 i lt 10 i)
- cout ltlt rand() 100 1 ltlt endl
Must seed the random number generator use the
current system time Note do this ONCE only in
your program put this statement in main()
39Random numbers in Visual C
- includeltstdlib.hgt
- includelttime.hgt
- includeltiostreamgt
- using namespace std
- int main()
-
- int i
-
- srand( (unsigned)time( NULL ) )
- for (i 0 i lt 10 i)
- cout ltlt rand() 100 1 ltlt endl
rand() is the library function that generates
random ints between 0 and RAND_MAX (maximum value
defined by compiler)
40Random numbers in Visual C
rand() 100 generates random ints between 0 and
99, so add 1 to get numbers between 1 and
100. Recall is the modulus operator returns
remainder when left operand divided by right
operand.
- includeltstdlib.hgt
- includelttime.hgt
- includeltiostreamgt
- using namespace std
- int main()
-
- int i
-
- srand( (unsigned)time( NULL ) )
- for (i 0 i lt 10 i)
- cout ltlt rand() 100 1 ltlt endl
41Clearing the console screen
- To clear the DOS console and position the cursor
at the top left - system("cls")
- Can use system() to run any DOS command
- e.g. system("notepad.exe")
- Use with caution! (e.g. system("del "))
42Lab hand-ins the program
- All labs to be handed in by email
- Code will be compiled and run during marking
- Make sure you hand in the right version
- Results emailed back to you
- Each lab marked out of 10
- 1 mark off for each day late
43Lab hand-ins the program
- Before emailing your code
- DELETE THE Debug DIRECTORY!!!
- Use WinZip to zip up all files in your lab
directory - DONT FORGET TO INCLUDE YOUR LAB REPORT (Word
file) - Email Zip file as attachment to
- growe_at_computing.dundee.ac.uk
44Using WinZip
- Start WinZip from Programs menu
- Click New button
- Enter name of new zip file
- e.g. Lab1.zip
- Ensure Add dialog is checked
- Click OK the Add dialog appears...
45Using WinZip
Open the top-leveldirectory for your lab.
46Using WinZip
Ensure the file name is given as .
47Using WinZip
Ensure that Include subfolders is
checked Ensure that Save extra folder info is
NOT checked.
48Using WinZip
Finally, click the Add with wildcards
button. Do NOT click the Add button!
49Lab hand-ins the report
- Write your report using Word
- Include
- Title of lab
- Purpose of lab (1 or 2 sentences refer back to
lab sheet for details) - Your class design, with brief description of how
you arrived at it - Use diagrams if you think it will be clearer
- Table showing test results for the program
- List of any bugs you couldnt fix
50Lab hand-ins testing
51OGRE
- If you've finished the lab, have a look at OGRE
- See AC2101 web site for instructions on how to
start OGRE - Run tutorials first, then try your own code or
examples from lectures
52Characters in a DOS window
- Visual C library functions for DOS window
display - Placing characters at specified locations
- Setting character colours
- Clearing the window
- Setting the DOS windows title bar
- See CharDisplay sample prog on AC2101 web site
53Characters in a DOS window
- Need to include ltwindows.hgt
- Must first get a handle for the console window
- Data type is HANDLE
- Obtain with GetStdHandle( STD_OUTPUT_HANDLE )
- Can now set text positions and colours
54The DOS console model
- Characters in DOS console stored in 2-dim array
of chars - Access a location by its x and y coords
- x starts at left margin with value 0
- increases to the right
- y starts at top margin with value 0
- increases downwards
55The COORD data structure
- Specify coordinates of a point using the COORD
data structure - COORD is a C struct
- Has 2 data fields X and Y (uppercase)
- E.g. to set a COORD to (12, 6)
- COORD testCoord
- testCoord.X 12
- testCoord.Y 6
56Writing some text to the console
char message50 strcpy(message, This is a
test) WriteConsoleOutputCharacter( hConsoleOut,
message, strlen(message), location,
charsWritten )
57Writing some text to the console
char message50 strcpy(message, This is a
test) WriteConsoleOutputCharacter( hConsoleOut,
message, strlen(message), location,
charsWritten )
Create a message to bedisplayed.
58Writing some text to the console
char message50 strcpy(message, This is a
test) WriteConsoleOutputCharacter( hConsoleOut,
message, strlen(message), location,
charsWritten )
Call library function to display text.
59Writing some text to the console
char message50 strcpy(message, This is a
test) WriteConsoleOutputCharacter( hConsoleOut,
message, strlen(message), location,
charsWritten )
Console HANDLE variable.
60Writing some text to the console
char message50 strcpy(message, This is a
test) WriteConsoleOutputCharacter( hConsoleOut,
message, strlen(message), location,
charsWritten )
Char array to be displayed.
61Writing some text to the console
char message50 strcpy(message, This is a
test) WriteConsoleOutputCharacter( hConsoleOut,
message, strlen(message), location,
charsWritten )
Number of chars to write.
62Writing some text to the console
char message50 strcpy(message, This is a
test) WriteConsoleOutputCharacter( hConsoleOut,
message, strlen(message), location,
charsWritten )
COORD variable giving location of first char in
array (e.g. (12, 6) )
63Writing some text to the console
char message50 strcpy(message, This is a
test) WriteConsoleOutputCharacter( hConsoleOut,
message, strlen(message), location,
charsWritten )
Pointer to int variable to receive number of
chars actually written.
64Writing some text to the console
char message50 strcpy(message, This is a
test) WriteConsoleOutputCharacter( hConsoleOut,
message, strlen(message), location,
charsWritten )
Result of function call
T
h
i
s
i
s
a
t
e
s
t
65Setting text colours
WORD colour50 // Initialize colour array to
integer colour codes (0 15) WriteConsoleOutputAt
tribute( hConsoleOut, colour, strlen(message),
location, charsWritten )
T
h
i
s
i
s
a
t
e
s
t
66CONSOLE_SCREEN_BUFFER_INFO
- Data structure providing info on format of DOS
console window - Obtain using
- GetConsoleScreenBufferInfo( )
- See on-line docs for info in struct
- See ClearScreen( ) function in CharDisplay for
example
67Random numbers in gnu C
Random number generator must be seeded
before being used for the first time.... Declare
a seed variable of type time_t
- includeltstdlib.hgt
- includelttime.hgt
- includeltlimits.hgt
- int main()
-
- int i
- time_t seed
- time(seed)
- srandom(seed)
- for (i 0 i lt 10 i)
- cout ltlt random() 100 1 ltlt endl
-
68Random numbers in gnu C
The system time( ) function returns the
current time from system clock, stores the
result in seed variable
- includeltstdlib.hgt
- includelttime.hgt
- includeltlimits.hgt
- int main()
-
- int i
- time_t seed
- time(seed)
- srandom(seed)
- for (i 0 i lt 10 i)
- cout ltlt random() 100 1 ltlt endl
-
69Random numbers in gnu C
System time is passed as seed value to srandom(
) function, which initializes the random
number generator DO THIS ONLY ONCE IN EACH
PROGRAM!
- includeltstdlib.hgt
- includelttime.hgt
- includeltlimits.hgt
- int main()
-
- int i
- time_t seed
- time(seed)
- srandom(seed)
- for (i 0 i lt 10 i)
- cout ltlt random() 100 1 ltlt endl
-
70Random numbers in gnu C
The random( ) function returns an integer in
the range 0 ... INT_MAX. Use remainder operator
to convert to smaller range random() 100
gives range 0 ... 99
- includeltstdlib.hgt
- includelttime.hgt
- includeltlimits.hgt
- int main()
-
- int i
- time_t seed
- time(seed)
- srandom(seed)
- for (i 0 i lt 10 i)
- cout ltlt random() 100 1 ltlt endl
-
71tarfiles
- tar Tape Archive
- Use tarfiles to archive your labs for mailing to
marker - Command
- tar cf lttarNamegt ltfiles to sendgt
- DO NOT OMIT tarName
- You will overwrite your source file if you do!!!
- INCLUDE makefile or Imakefile in tarfile