A8-Multi-Function Programs

Table of Contents


Objectives

  • Use function declarations (prototypes).
  • Code void functions.
  • Design a program using multiple functions as modules.
  • Develop functions as black boxes.
  • Add block comments to function declarations.

Academic Honesty

Read the Scholastic Honesty Policy and Assignment Integrity policies of the syllabus. Here are some clarifications for this particular assignment:

  • You are encouraged to work with one other student of this class following the rules of Pair Programming for Homework Assignments. If you choose to pair program, there is a bonus applied.
  • You may not give a copy of your code to your designated pair-programming partner if you did not work on the code together at the same computer.
  • You may not look at another student's code until you complete and submit this assignment, except for code you work on with your pair-programming partner.
  • You may get help from people other than your pair-programming partner if you get stuck, but only if they do not show or tell you the code to type. Instead, ask them to show you other examples that you then apply to the project.
  • Remember that the instructor performs similarity tests on programming project submissions, and copied or plagiarized code is usually very easy to detect.

Preparation

  1. Make sure you have completed the exercises from lesson 8.
  2. Complete the Review Exercises in CodeLab 8. These exercises will help prepare you for the problem-solving programs and should be completed first.
  3. Read lesson 8.1.4: Arrays as Function Parameters.

Project Specifications

Your solutions to these projects must only use techniques we have covered so far.

Programming Style

For all programs, remember to follow all the style rules we covered including the recent items:

  1. Avoid duplicating code (see textbook page 208)
  2. Function comment blocks (See: Function Comment Block)
  3. Function naming conventions (See: Function Names)
  4. Indentation in functions and placement of curly braces (See: Indentation)
  5. No magic numbers. (Hint: make arrays of numbers const)
  6. Indentation in while statements and placement of curly braces
  7. No tab characters in your code.

    You can remove tab characters by either setting up TextPad correctly (see here) or by running a program named astyle (see here).

  8. Meaningful variable names and consistent naming style (caps vs. underbars).
  9. Create the README.txt file following the instructions.

Image

Project 1: Function Worksheet Sequel

Functions are an important part of programming, allowing us to break up long sequences of code into shorter reusable parts. We then assemble the parts to create larger programs.

In this project we complete several functions. Each function is like a smaller program inside of a our larger program. Notice that we can focus on each function separately, allowing our full attention on each part of the problem.

Project Specifications
  1. Start by downloading the worksheet: funwork2.cpp.

    Keep the same filename and add to the existing code to complete the project. Leave the existing code unchanged, except for comments as instructed.

  2. Add your name and the date to the file comment block at the top of the file, replacing the words Your Name with your first and last name and Date Here with the current date.
  3. No user input is required for this project and do not add any.
  4. Write the required functions as described by the function signature and comment block.

    Do NOT change any of the function headers and do NOT make any changes to the main() function besides uncommenting code.

  5. Write the function definitions below main(), and their prototypes above main().
  6. Do not turn in code with cout in any function besides printArray() and the cout statements already coded in main().

    You may add cout to debug code but please remove it before turning in your code.

  7. Compile and run the code when finished with each function to verify correctness. Check the test results and make any alterations to your function definitions as necessary. Do NOT change any code in main() beyond removing comments to call the functions and do not change the function headers.

    When you first start you will see warnings when compiling. Remember that code with warnings compiles but the warning is giving you hints about problems with the code.

  8. Example Run: The outputs of the program must look exactly like the following for full credit, including the same order and format of the output.
    ***Testing alternateXO***
    Variable ch is set to an X.
    alternateXO1 must change ch to (O): O
    alternateXO2 must change ch to (X): X
    alternateXO3 must change ch to (O): O
    
    ***Testing insertEvery3***
    insertEvery3a must return (ab): ab
    insertEvery3b must return (abcxde): abcxde
    insertEvery3c must return (abcydefy): abcydefy
    insertEvery3d must return (abczdefzg): abczdefzg
    
    ***Testing isClump3***
    isClump3a must return (false): false
    isClump3b must return (false): false
    isClump3c must return (true): true
    isClump3d must return (true): true
    
    ***Testing printArray3***
    printArray3a must cout
    a b c
    actual output:
    a b c
    printArray3b must cout
    a b c
    d
    actual output:
    a b c
    d
    printArray3c must cout
    a b c
    d e f
    actual output:
    a b c
    d e f
    
    ***Testing swapXO***
    swapXO1 must show (aOcX): aOcX
    swapXO2 must show (ObOXX): ObOXX
    swapXO3 must show (OXOXOf): OXOXOf
    
    *** End of Tests ***
  9. When all of the tests pass, upload your completed source code file with the rest of the assignment as described in Deliverables.
Hints:
  • Remember that a warning is not a failure to compile but must be corrected before submitting the project.
  • For an example of printing the elements of an array, see lesson 8.1.4: Arrays as Function Parameters.

Image
Image source

Project 2: Tic-Tac-Toe Game

Tic-tac-toe (American English), noughts and crosses (British English) or Xs and Os, is a game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row wins the game [1]. If no player can win, the game is called a "Cat's game".

In this project we implement a two player version of the tic-tac-toe game as played on a computer in a terminal window. Playing against the computer is an extra credit option.

When starting a more complex project, it is important to first develop a plan. First play the game yourself and write down the steps in broad terms using pseudocode (see pseudocode in lesson 8.4.2). For example, here is a possible list of steps in pseudocode:
Make the game board
Repeat until game is over
    Choose player for turn
    View the board
    Make move
    Check for exit conditions: winner, cat, quit
Evaluate finished game

Then use stepwise refinement, from lesson 8.4.2, to break down any step that seems too difficult to implement directly.

Notice that this project has three required functions to use besides main(). If you do not easily see how to implement the function, then list the steps and apply stepwise refinement as needed.

Project Specifications
  1. Write a program that allows two users to play tic-tac-toe and that operates as shown below.

    In the examples below, the user entered the values shown in aqua italics (for emphasis) to produce the output. Your program does NOT print the characters in aqua italics, nor does the user input appear in aqua italics.

  2. Name the source code file tictactoe.cpp and include all your code in this single file.

    Be careful of the spelling, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.

  3. The program first displays a board exactly as shown and prompts user X for a move with the message exactly as shown.
    1 2 3
    4 5 6
    7 8 9
    Please enter your move using
    the number of the square or -1 to exit
    
    Player X's move: 1
    
  4. Players enter their move by entering the position number they wish to mark.

    In the above example, player X entered a 1 and an X appears at position 1 as shown below.

  5. After each move, the program displays the updated board and prompts the next player to move. In the following, notice the display of prior moves.
    X 2 3
    4 5 6
    7 8 9
    Please enter your move using
    the number of the square or -1 to exit
    
    Player O's move: 2
    
  6. Play continues alternating between the two players until one of them wins by placing three of their marks in a horizontal, vertical, or diagonal row.
    X O 3
    X O 6
    X 8 9
    Player X wins!
    

    Make sure to display the winning board and exit the program after displaying the winner.

  7. If all the possible moves have been made and there is no winner, display the message, Cat's game! and exit the program.
    X O X
    O O X
    X X O
    Cat's game!
    
  8. Whenever the user enters -1, the program exits immediately without displaying the board or a winner.
    Player X's move: -1
    Good bye!
    
  9. Catch and handle moves that are not integers or are less than 1 or greater than 9 (except for -1 to exit the game) and display the message, Invalid move: reason where reason is an explanation of the error as shown below:
    Player X's move: a
    Invalid move: enter numbers only
    Please enter your move using
    the number of the square or -1 to exit
    
    Player X's move: 10
    Invalid move: must enter position < 9
    Please enter your move using
    the number of the square or -1 to exit
    
    Player X's move: 0
    Invalid move: Must enter position > 1
    Please enter your move using
    the number of the square or -1 to exit
    
    Player X's move:
    
  10. Write code to prevent a player from making a move that is already played and display the message, Invalid move: position already taken:
    Player O's move: 1
    Invalid move: position already taken
    Please enter your move using
    the number of the square or -1 to exit
    
    Player O's move:
    
  11. Ask the user for a single integer for each move, and no other input, as shown in the examples above.
  12. After the game is over, exit the program without entering a -1.
  13. Create a char array of nine (9) elements to store the board positions and player moves. Initialize each element to the board position.
  14. You may use magic numbers for array indexes for this assignment. However, use meaningful const variable names for other magic numbers.
  15. Code functions with these exact headings, though you may add more functions if you like, and call each function at least once:
    /**
     * Displays the current game board.
     *
     * @param board The game board.
     * @param size The number of elements in the game board.
     */
    void displayBoard(const char board[], int size);
    
    /**
     * Prompts for a move and makes the move if valid.
     * Otherwise, posts an error message and asks the
     * user to enter a correct move.
     *
     * @param board The game board.
     * @param size The number of elements in the game board.
     * @param prompt Message to display to the user.
     * @param player Name of the player ('X' or  'O').
     * @return The play made or -1 if the player exits the game.
     */
    int move(char board[], int size, string prompt, char player);
    
    /**
     * Checks to see if the game has a winner.
     *
     * @param board The game board.
     * @return true if a winner was found, otherwise false.
     */
    bool checkWinner(const char board[]);
    

    For information on array parameters see lesson 8.1.4: Arrays as Function Parameters.

  16. Define the functions after main() and their declarations (prototypes) before main().

    Do not forget to add block comments before each function declaration (prototype).

  17. Submit the source code file tictactoe.cpp with the rest of the assignment as described in Deliverables.
Hints:
  • Use pseudocode to list the steps for each function. You may find the pseudocode in the introduction useful for planning the main() function.
  • The player's move is an index of the board array. For example, entering a 1 should place an 'X' or 'O' in the array storing the current board, either at index 0 or 1 depending on how you organize your board.
  • The prompt parameter in the move() function is the instructions for the player on what to enter. See the lesson 2.2.3: Input and Output section on Prompting Users.
  • As promised, I am allowing the use of exit(0) even though it is not necessary.
References and More Information
  1. Tic-tac-toe: Wikipedia article

Extra Credit and Extensions

The following are optional and worth extra credit points if the main program works well:

  1. Complete the programming project using pair programming. (2 points)
  2. Add an option that allows either player to enter a zero ('0') and have the computer generate the next valid move automatically. Implement the computer-generated move inside a function named autoMove() as shown below. Use this function header exactly with no changes. Add this function with its header to the same file as the rest of the program. (1-3 points depending on the "intelligence" of the moves)
    /**
        Computes the next valid move automatically. (Extra credit)
    
        @param board The game board.
        @param size The number of elements in the game board.
     */
    int autoMove(char board[], int size, char player);
    

Make certain that your README.txt file describes any extra credit attempted.

Tutorial Lab

In preparation for next weeks lessons, complete the following:

  1. Read the assigned reading in the textbook
  2. Complete the Tutorial Exercises in CodeLab 8 before the specified due date.

    Refer to the assigned reading for the next lesson to help you understand the problems. Also, you can use the online lecture notes for more information as the notes become available. You can look at solutions if you miss your first few attempts and are stuck by clicking the "Solution" tab.

Grading Criteria

The instructor will evaluate your assignment using the following criteria. Thus you should check your assignment against these criteria to maximize your score.

Each criteria represents a specific achievement of your assignment and has a scoring guide. The scoring guide explains the possible scores you can receive. Some scoring guides have a list of indicators. These indicators are a sign of meeting, or a symptom of not meeting, the specific criterion. Note that a single indicator may not always be reliable or appropriate in a given context. However, as a group, they show the condition of meeting the criterion.

For information on grading policies, including interpretation of scores, see the syllabus.

Lesson Exercises

  • 2: All lesson exercises attempted and turned in
  • 1: Some lesson exercises completed and turned in
  • 0: No lesson exercises completed or turned in

Function Worksheet

  • 5: All functions completed and program generates the correct output without error
  • 4: All functions completed but has a minor error
  • 3: Most functions completed or has some small errors
  • 2: At least half the functions completed or has some errors
  • 1: Few functions completed or has many errors
  • 0: Does not compile or wrong file turned in

Tictactoe Project

  • 10: Demonstrates mastery of the assignment
    • Applies concepts from the lessons appropriately
    • Meets all specifications (see above) with particularly elegant solutions
    • Runs to completion with no abnormal error conditions
    • Generates correct output given correct input
    • Behaves in a reasonable way in response to incorrect data
  • 8: Has all the functionality expected of the assignment
    • Demonstrates many techniques from the lesson
    • Attempts to meet all specifications (see above)
    • Implementation seems more complicated than necessary.
    • May have one minor error
  • 6: Has most of the functionality expected of the assignment
    • Demonstrates some techniques from the lesson
    • Attempts to meet all but one of the specifications (see above)
    • Implementation seems excessively complicated.
    • May have 2-3 minor errors
  • 4: Has some of the functionality expected of the assignment
    • Demonstrates some techniques from the lesson
    • Attempts to meet at least 1/2 of the specifications (see above)
    • Implementation seems excessively complicated.
    • May have more than 3 minor errors
    • AI not correctly trained
  • 2: Serious functional problems but shows some effort and understanding
    • Attempts to meet less than 1/2 of the of the specifications (see above)
    • Has a major error or many minor errors
    • Implementation seems very convoluted
    • Demonstrates few techniques from the lesson
  • 1: Does not compile or wrong file turned in
  • 0: Does not execute, not turned in or uses techniques not covered in course

Program Style

  • 3: Code is well-documented including:
    • Correct file name used
    • Name, date, and program description in file comment block
    • Follows specified format for file comment block
    • Has a function comment block for all function declarations following the specified format
    • Proper use of spaces around operators
    • No tab characters are present in the source code
    • As described in How To Document and Organize C++ Code
    • Correct file name used
  • 2: Code has a minor documentation error
  • 1: Code has some documentation errors
  • 0: No apparent attempt to follow documentation standards or write documentation comments

CodeLab Exercises

Number completed correctly / number exercises * 8 and rounded up to the nearest integer.

README.txt File

  • 2: README.txt file submitted following the instructions
  • 1: README.txt file submitted but some information was missing
  • 0: No README.txt file submitted

Total possible: 30, plus extra credit

Deliverables

Submit your assignment to Canvas, in the assignment folder A8-Multi-Function Programs, following the instructions for submitting homework. Include the following items for grading:

  1. README.txt file
  2. All the exercise files from Lesson 8
  3. funwork2.cpp
  4. tictactoe.cpp

You must submit all the files needed to complete your assignment. Your assignment must work as submitted. Remember to test and double check your files before submitting them. If you make a mistake, you can resubmit up to the deadline. If you resubmit, you must include all your assignment files in the last submission as Canvas hides prior submissions.

Last Updated: April 08 2019 @21:55:52