Knowledge of c programming principles

Assignment Help C/C++ Programming
Reference no: EM13810529

In this assignment, you are asked to implement a moderate size program to demonstrate early knowledge of C programming principles.

The concepts covered include:

· Data types and basic operators.
· Branching and looping programming constructs.
· Basic input and output functions.
· Strings.
· Functions.
· Pointers.
· Arrays.
· modularisation
· C Structs

We have decided this year to provide you what will be a fun assignment, a two player version of the game "Connect 4". Connect 4 is a rather simple game. Players take it in turns to place a token in a column on a board - the placed token drops down that column to the last available cell for it. Each player attempts to get four of their tokens in a row while blocking the opposing player for achieving the same objective.

The gameboard for this game will look as follows:

Before the game begins, the human player will be given the opportunity to enter their name. Each player will then be allocated a colour randomly - either red or white. The player allocated the white colour will go first and each player will be given the opportunity to drop a token onto the board until either player has 4 tokens in a row or there are no more possible moves.

Startup Code

Below we will outline the data structures we have provided to assist you in your solution to this assignment. Please note that these data structures form part of the startup code and cannot be modified. The startup code also includes function prototypes. You must use this startup code. You should feel free however to create additional variables, constants and functions to help you with your solution. In fact, it is impossible to get full marks without doing this.

We are providing you with some enumerations and structs which should be helpful in having more meaningful code that is easier to maintain. An enumeration is a series of integer values that are related together. For example, each cell of the board is defined by the following enumeration:

/**
* defines the possible contents of each cell of the board
**/
enum cell_contents
{
/** the cell does not contain a token **/
C_EMPTY,
/** the cell contains a red token **/
C_RED,
/** the cell contains a white token **/
C_WHITE
};

In other words, each cell that makes up the game board could be empty, it could be holding a red or white counter.

Another enumeration that we provide you with defines a "boolean" datatype. C (certainly ansi C) does not have a built-in boolean datatype (that is, a datatype for true and false), and because of that, if we are going to have a boolean type, we will have to define it ourselves. The header file "bool.h" contains the following definition:

typedef enum truefalse

{
FALSE, TRUE
} BOOLEAN;

This definition contains a "tag name" (truefalse) that is used to define the enumeration. This is then wrapped in a typedef statement. A typedef statement renames one type as another. Here, we rename the "enum truefalse" to be the type BOOLEAN, which we can then use whenever we need a true/false type value. One other thing to take notice of is how the counting of values occurs.

Remember that an enumeration is a set of related integer values and so we start counting at 0 so there is an implicit association of 0 with FALSE and 1 with TRUE which is a standard way to associate integers with truth values.

A struct on the other hand is a bundle of related data that can be passed around together. It is rather similar to an object in object-oriented programming languages such as Java. In this program there will be a single struct that you will be passing around, the player struct which looks like this:

struct player
{
/**
* the player's name
**/
char name[NAMELEN+1];
/**
* the color of the token for the player. Note: this is a
* typedef of enum cell_contents.
**/
color thiscolor;
/**
* how many counters does this player have on the board?
**/
unsigned counters;
/**
* what type of player is this? A human or a computer?
**/
enum playertype type;
};

So, we can see from the comments that color is a typedef (alias) for enum cell_contents as this is kind of what the contents of each cell is - a colour. The player struct also stores the name, number of counters played by the player and their type - whether they are a human or computer player.

There are some other data structures used in the assignment as well but we will discuss these as we come to each assignment requirement.

Further explanation of data structures will be available under each implementation requirement.

1. Main Menu

You are required to implement a main menu that manages the overall program. You should display the menu as follows:

Welcome to connect 4
--------------------
1. Play Game
2. Display High Scores
3. Quit
Please enter your choice:

Your menu input algorithm should reject any invalid data and should implement correct buffer handling. See the sections below on "buffer handling" and "input validation" for further information.

2. Data Structure Initialization

Various data structures used throughout your program need to be initialized to a known safe state. For example, you should initialize the two-dimensional game board to EMPTY, the name for each row of the scoreboard to the empty string, and so on. Leaving any data structure uninitialised means it is uncertain what the starting point for that element is and that is the source of many errors.

3. Player Setup

When a new game starts, you need to set up the structs to represent human and computer players. For the human player, you need to ask for their name and store it in the "name" element of the player structure, whereas the Computer player's name should simply be set to "Computer". You need to set the counters to an appropriate initial value. You will also need to randomly allocate a color to each player and set its type - whether it is a computer or a human player. Finally you need to set the player with white tokens as the current player as they always play first.

4. Play Game

This is the heart of the game.

Firstly, you need to initialise the game by calling functions written for requirement 3. The rest of this function is then managing the game loop.

Each player takes a turn to drop a token into a column on the game board. The task that needs to be performed will be different depending on whether this is a human or a computer player. Regardless of the player type, you will need to display the board as it was before the player makes their move.

If the current player is a computer player, we just need to select a column at random and drop a token into that column. If there is no room, try another column.

If the current player is a human player, your program will need to ask the user what column they wish to drop a token in. This input should be validated to check that it is numeric and within the range of allowed columns.

Once a valid move has been entered, your program should update the gameboard. It should then check if the game has been won lost or drawn by calling and the change the current player.

The game loop is implemented in the function:

struct player * play_game( struct player * human,
struct player * computer);

This function also checks if the game has been won, lost or drawn by calling test_for_winner(), and if the game is over, returns the winner to main or NULL if the game was a draw.

You should inform the user who won the game or if there was no winner before returning to the main menu.

5. Display Game Board

In this requirement you are required to display the game board. The game board should be displayed as shown on the first page of this assignment specification.

6. Player Turn

In this requirement, you need to handle the taking of a turn - either of a human or a computer player.

For the human player, you will need to allow the user to enter the column they wish to place a token in. You will need to validate what the user enters, then place a token correctly in that column so that it occupies the cell closest to the bottom of the board array for that column.

For the computer player, you will need to randomly generate a column number to place a token in and if that column is full, generate a different column number until a column number with some free space has been found.

For either player type, you need to increment the number of counters in the player struct after each successful turn. This is a count of how many tokens have been successfully played by that player in the current game.

The function prototype for the function to perform this task is:

enum input_result take_turn(struct player * current,
enum cell_contents board[][BOARDWIDTH]);

7. Swap Players

At the end of each turn, we need to change who the current player is as their turn has ended. We are going to do this by simply swapping the pointers for the current player and other player in the game.

The function prototype for this function is:
void swap_players(struct player ** first, struct player ** second);

Where first and second are both pointers to pointers to a struct player.

For example, if current points to the human player and other points to the computer player, at the end of this function, current will point to the computer player whereas other will point to the human player.

This will be called from play_game() with a call such as swap(&current, &other).

8. Test for Winner

In this requirement you are required to test what the game's current state is.

Possible game states are defined by the game_state enumeration:

enum game_state
{
G_NO_WINNER=-1,
G_DRAW,
G_RED,
G_WHITE
};

Most of these states should be self-explanatory but let's go through their meaning.

 

  • G_NO_WINNER: the game is still in progress and therefore there is no winner yet.

 

 

  • G_DRAW: neither player has won the game but there are no more spaces left for a player to make a move.

 

 

  • G_RED / G_WHITE: the player whose token is the specified colour has won the game.

 

Your task in this function is to iterate over the 2-dimensional array (the board) looking for four in a row in any direction - if you find this, return the appropriate value of either G_RED or G_WHITE.

Next, test for a draw. If none of these cases hold, return G_NO_WINNER.

9. Insert High Score

When the game ends, you need to return the appropriate game state back to main. You will then need to insert the winner's score sorted in order by the number of counters that they played in the game. You should only store the top ten scores and so when a new score is entered on a full scoreboard, the lowest score simply drops off the bottom of the board.

The function prototype for inserting a score is:

BOOLEAN add_to_scoreboard(scoreboard board, const score* lastscore);

Both scoreboard and score are typedefs (aliases) of other types.

Scoreboard is defined as:

typedef struct player scoreboard[SCOREBOARDSIZE];

and score is defined as:

typedef struct player score;

In other words, a scoreboard is an array of struct player of SCOREBOARDSIZE (10) and a score is another name of a player struct. This has been done so we can reuse the type and it simplifies the maintenance of the code.

10. Display High Scores

For this requirement, you will need to display the scores in the order they are scored in the scoreboard array. The display should look as follows:

Player |Score
---------------------------------------------
Barney |17
Magi |15
Red |10
Computer |8
Computer |7
Computer |6
Paul |4
Fred |4
Muaddib |4
Zafiqa |4

11. Return to Menu

This is a special requirement that has to do with proper buffer handling.

At any point in the running of this program, if the user presses the ctrl key and „d? together or they press enter on a new line, they should be returned to the main menu.

Students often ask about how to deal with the ctrl-d combination and what it means. A little bit of research online (ie, following a couple of links from a search engine) should help you solve this problem. We want you to show some resourcefulness with this one.

In order to simplify this process, we have provided you with an enumeration that can be used with your user input functions to capture whether an input request has succeeded or failed. The definition of this enumeration is:

enum input_result
{
SUCCESS,
FAILURE,
RTM=-1
};

So, when the input succeeds with a valid result, you can return SUCCESS, when it fails with an invalid result, you can return FAILURE, but if the user has fired a RTM event such as pressing enter of ctrl-d on a newline, you can return RTM.

12. Quit the Program

When the user selects quit from the main menu, your program should cleanly quit, without crashing.

13. General Requirements

Please pay attention to the "Functional Abstraction", "Buffer Handling", "Input Validation" and "Coding conventions/practices" sections of the "Assignment Specifications ­ General Requirements" document. These requirements are going to be weighted at 5, 5, 6 and 4 marks, respectively.

14: Demonstration

This demonstration will occur in the week beginning 10 August 2015. You will need to demonstrate the following, without, at this stage, requiring to implement validation.

Ability to compile/execute your program from scratch.

Requirements 1, 3, 5, and 6 implemented and running (1 mark each). That is, you will need to display the main menu, start a game, and implement the logic for computer and human players to be able to have a turn, including the display of the game board. Note that since we do not require implementation of the full game loop here. It is enough for each player to simply have one turn.

Reference no: EM13810529

Questions Cloud

Defining the business goals and objectives : Provide an overview of the organization that will be delivered to senior management, defining the business goals and objectives and the size, layout, and structure of the organization
Assignment on american political culture : American political culture
Either the sale of common stock or by a bond issue : Amarillo Parts is considering purchasing a small firm in the same line of business. The purchase would be financed by either the sale of common stock or by a bond issue. What is the degree of financial leverage for each plan at $7,000,000 of EBIT? Wh..
Ms project exercise-project management process : Develop a multilevel work breakdown structure (WBS) and create a detailed project schedule in MS Project for the project you identified.
Knowledge of c programming principles : Implement a moderate size program to demonstrate early knowledge of C programming principles - what will be a fun assignment, a two player version of the game "Connect 4". Connect 4 is a rather simple game.
What are the specific needs of the help desk : In addition to the other elements of the planned strategic IT operation there will be a need to develop and implement an IT Help Desk to better facilitate the support of Northwest Georgia Auto Parts' internal IT issues
Calculate the tax effect from the sale of the existing asset : Truth Dance Company, Inc., a manufacturer of dance and exercise apparel, is considering replacing an existing piece of equipment with a more sophisticated machine. Calculate the book value of the existing asset being replaced. Calculate the tax effec..
Write a review of your arts experience : Write a review of your arts experience that includes a defense of the arts. Include the following: Write a description of the elements of composition--line, color, shape, or movement, theme, rhythm, tone, and so forth that were incorporated into t..
About virtues and values : Virtues and Values

Reviews

Write a Review

C/C++ Programming Questions & Answers

  Determine the letter grade associated with the average

Create a loop structure to display and calculate the factorial of the larger number provided by the user - What if these were test scores? Calculate the average of the two numbers provided.

  Summarizing your predicted and actual output

Write a statement summarizing your predicted and actual output, and identify and explain any differences. For your conclusions, write at least one nontrivial paragraph that explains, in detail, either a significant problem you had and how you solv..

  Called cbankaccount

Create a base class, called CBankAccount, and two additional classes (each derived from CBankAccount), called CSavingsAccount and CCheckingAccount.

  Create a script that uses case logic

Display the command(s) used to do the following: display the cclontents of .bashrc file. Next, use the vi editor to edit that file and put in an alias so that you see a long file listing of a directory every time you type list.

  Function prototype

Math.Round is an example of a built-in function.

  To deal with deadlocks we can either use prevention or

to deal with deadlocks we can either use prevention or avoidance or detection followed by recovery. but which is a

  Program of a class date which displays the date

Write a C++ program of a Class Date which displays the date. Use the subsequent requirements:

  Create a constructor that initializes the data

After the user answers the question, just put the actual answer down below the one entered. You do not need to check if they were correct.

  Sort an array of elements using the quick sort algorithm

Sort an array of 10,000 elements using the quick sort algorithm as follows: sort the array using pivot as the middle element of the array

  Write in c++ another overloaded operator

Write in C++ another overloaded operator to go in the program that has Treasury. Overload the forward slash /  so that in the main program, you can declare sale to be of type Treasury, and commission to be of type Treasury, and commispctage to be of ..

  A list of toppings should be shown on the screen as a menu

Write a menu-driven C++ program that allows a user to select from the following items: Pizza, Cheeseburger, and Hot Dog. Pizza should be represented by the integer value 1. Cheeseburger should be represented by the integer value 2.

  Implement class bankacct for bank usq

Implement class BankAcct, for Bank of USQ, using bankacct.cpp and bankacct.h and Implement an application bankUSQ_app.cpp

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd