ENGG1110 Project
- IntroductionCandy Crush is a popular match-three puzzle game in the world, originally released in
2012 for Facebook and later adapted for mobile platforms.In the basic gameplay, the gameboard consists of a grid filled with various types ofcandies, each represented by different shapes and colors. The player’s goal is to creatematches of three or more identical candies by swapping adjacent one. When a match ismade, the matched candies are cleared from the gameboard, and new candies will falldown to fill the empty spaces. This sometimes leads to “chain reactions”, where newmatches are automatically created as the board refills.Figure 1. Sample Gameplay. Snapshots fromhttps://www.flickr.com/photos/alper/10330168576
In this project, you will develop a Candy Crush game using the C programminglanguage. The project is structured in two phases: Part I focuses on implementing thebasic version of the game, while Part II builds upon the first parENGG1110 r match-three puzzle game it by adding advancedfeatures and additional gameplay mechanics.You are required to complete the givensource code main.c without modifying anyexisting code (except otherwise specified) or introducing new libraries. Marks will bededucted from every modification.ENGG1110 Project2 of 26Program FlowPart I ENGG1110 Project3 of 26Part IIENGG1110 ProjectSuggested Project SchedulePart I (60%InitGameBoard(), printGameBoard()Week 11AskForSwap()- Input/Validation, swap()Week 12FindAndRemoveMatch(), isGameOver()Part II (40%)13/14File I/O, applyGravity, fillEmpty(),CascadeWeek 145 of 26Sample for Part IThe following shows several examples of inputs and the resulting candy clearings. Userinputs are indicated by bold, highlighted underlined text. The matches found by the are in red font.=====Detailed Program Design Flow – Part IIn this project, you are required to follow exactly the output format specified. Usingother outputformats will jeopardize your mark.This program willRead and initialize the game board from source
- Display the game board
- Allow the player to select a candy to swap
- The player can only swap two candies at a time
- The player will choose a candy by entering the coordinates (row, column)
- The player will also input a direction (U for Up, D for Down, L for Left, R forRight) to specify where to swap the selected candy.
- Find and remove matches
- After each swap, check for matches of three or more identical candies in
a row or column.
- If a match is found, display a message indicating the match’s location,
remove the matched candies, and update the game board.
- Check for a game-over condition
- Check if no further matches are possible on the gameboard.
- If the board has no possible moves left, display the message and end the.5.1.Header files, Functions, and Variable DeclarationsAt the beginning of the main.c file, we include two headers, <stdio.h> and
<stdlib.h>.No other header files or library are allowed in the project. We define several macros after the header line. Macros are identifiers defined by#define, which are replaced by their value before compilation. The first two are H and W.#define H 6 // height#define W 6 // widthH is the height of the game board, while W is its width. Therefore, our Candy Crush game
board is a 6x6 square. In our test cases, we do not have any test cases with varying boardsize. You may try it if you are interested.Each cell on the game board stores acandy, with different types of candies representedby numbers. To assist in converting these numbers into their correspondingcandyrepresentations, the following globalvariable is provided.char candies[] = {'*', '#', '@', '%'};ENGG1110 Project10 of 26
No other global variables are permitted. All variables you define must be declaredwithin functions and passed as parameters or return values as necessary. Violations of rule will result in a deduction of marks. Also, there are a number of helper functions declared in the project. You can add newfunctions to aid your work, but you CANNOT modify (function signatures – functionnames, return type, parameters), or delete the given functions. 5.2.Main FunctionThe main function is given to control the game flow.There are some local variables already declared for you. You can declare your own localvariables for your use.Usages board[H][W]Stores the candies on the game board.are the tasks in the loop.The loop should start by printing five equal signs (=====) as a separatorfor each round, as follows:=====New Round:
- , call printGameBoard() to display the current game board.| 0 | 1 | 2 | 3 | 4 | 5 |0| # | % | @ | * | # | * |1| @ | @ | * | # | # | % |
- Call askForSwap() to execute the swapping logic. If the askForSwap()returns zero (0), indicating the swapping is unsuccessful. In this case,pnt the following error message:Please try again.\nENGG1110 Project11 of 26Call isGameOver() to check if any moves are possible. If no valid movesremain, display a game over messageand exit the game loop. In this case,print the following error message:Game Over! No more possible moves.\nENGG1110 Project12 of 265.3.nitializing Game BoardThe main() function will first call the initGameBoard() 代写 ENGG1110 r match-three puzzle gamefunction, which initializes theboard[] array for the later gameplay. In Part I, the content of thearray should be readfrom another hard-coded arrays – board_samples[].5.4.Print Game BoardThe given printGameBoard() is useful throughout the program to show the currentgame board status to the user. You are required to implement this function and print thegame board on the screen based on the following format, where ␣represents a spacecharacter that should appear as an actual space in the program output.
, print a line of five equal signs (=====) as a separator. Then, display the game boardwith row and column numbers labeled. Each cell should be separated by bars to clearly distinguish rows and columns.=====␣|␣0␣|␣1␣|␣2␣|␣3␣|␣4␣|␣5␣|0|␣#␣|␣%␣|␣@␣|␣*␣|␣#␣|␣*␣| on the grid:Candies: Use the candies[] character array to convert the numericalalues stored in board[][] into the corresponding candy symbols.: Display the space character (' '), which is stored in
board[][] as ASCII 32 (space).It is crucial that your output format follows the example exactly, including the number
spaces and any other formatting details, as the program will be graded using anautograder. Any deviation in the format could result in a loss of marks.5.5.
Ask for input for swappingThe main function will call askForSwap() to handle the game action. The swappinglogic will be implemented inside this function. This function will return an integer toindicate whether the swapping is successful or not. (Details of return value)ENGG1110 Project13 of 26
5.5.1.User Input5.5.1.1. Coordinates
The function should first ask the users for input two integers for the coordinates first:Enter the coordinate (row, column) of the candy:\nAfter receiving the user input, assume the user will only input integers. Ensure that the coordinates are within thevalid game board range. If the coordinates input is out of bounds, output the followingerror message and return zero (0).Coordinates Out of Bound.\n5.5.1.2. Empty CellsThen, the function should check whether the selected cell is empty or not. If the cell is, output the following error message and return zero (0).Empty Cell Selected.\n5.5.1.3. Direction to SwapAfter the coordinates are valid, the game should ask for the direction: the direction to swap (U for Up, D for Down, L for Left, Rfor Right):\nYou can assume that the user will input one character only. This input should bevalidated toensure it is correct – i.e. Upper case and should be one of the fourpossibilities(U,D,L,R).If the direction is incorrect, output the following error messageand return zero (0). Direction Input.\n5.5.2.Valid Swapping Check attempting to move a candy, the program should validate that the move stayswithin the boundaries of the game board, For example, the candy at position (0, 0) beswapped to the left, as it is already at the left boundary of the boardIf the move is out of bounds, output the following error and return zero (0). Out of Bound.\nENGG1110 Project14 of 26In addition, the program should also check the Target cell (e.g. if swapping (1,3) to theleft, Target cell is (1,2)) is empty. In this case, output the following error message andreturn zero (0).Empty Cell Selected.\n
5.3.Execute Swap
f the input validations pass, the swap action is performed by calling the swap()function. You should implement the swap() to take the board, the starting coordinate,the target coordinate, and the direction as arguments. The function will then swap theselected candies in the specified direction. For example, if the direction is U (up),thecandy at (row,col) will be swapped with the candy directly above it at (row-1, col).Similarly, if the direction is L (Left), the candy at (row, col) will be swapped with theto the left (row,col-1). After the swap, you may use printGameBoard() toinspect the result, but remember to remove this call after completing your inspection.5.5.4.Find and Remove MatchesAfter the swapping, the findAndRemoveMatch() function is called to locate anymatches involving the candy at both the target position and the original position, as amatch may form in either direction. The function checks the neighboring cells aroundeach of these positions to detect any sequence of three or more identical candieshorizontally or vertically.To facilitate auto-grading and maintain consistency, you should check the matches infollowing order.Order of Checks: When checking for matches, start with the Target Position (where swap has just placed a new candy). After completing all the checks andremoval at the Target Position, move to the Start Position (the original cell where candy was swapped from) and perform the same operations.For example, swapping (1,2) downwards: Target Position is (2,2); and the Start Position is (1,2).Horizontal Matches: Starting for the given cell, if it is not empty (‘ ’), check tothe left (if any) to see if there are three or more consecutive identical same row. Then check the right direction (if any).Vertical Matches: From the given cell, if it is not empty (‘ ’), check upwards (ifany) to see if there are three or more consecutive identical candies in the samecolumn. Then check the bottom direction (if any).3| % | * | @ | # | * | @ |4| # | * | @ | % | % | @ |5| % | # | @ | * | % | % |
a match is found in the horizontal/vertical direction, output the correspondingmessage on the screen and indicate the row and column where the match occurred. Match at row <Row Index>!\ne.g. Horizontal Match found at row 1!Vertical Match found at col <Column Index>!\ne.g. Vertical Match found at column 1!After finding the match, the game should remove the matching candies from the gameboard. This is the intermediate status of the after the removal.
the candy you want to swap:5 1 Enter the direction to swap (U for Up, D for Down, L for Left, Rfor Right):R Vertical Match found at col 2!| 0 | 1 | 2 | 3 | 4 | 5 |
1| @ | @ | * | # | # | % |2| # | % | % | @ | % | * |3| % | * | | # | * | @ |4| # | * | | % | % | @ |5| % | # | | * | % | % |the swap yields no matches, you should restore the game board tothe previous status(before the swap), print the message “No Match Found”, and return zero (0). Here is th
In this function, you should return one (1) to the caller – i.e. AskForSwap() function. 5.6.Game Over Checking
As the game progresses, there will be eventually no more matches in the game board.you should implement isGameOver() to check the whole board to see if there is atleast one potential match or not.You can try swapping each candy with its right neighbour (if any) and its bottomneighbour (if any). After the swap, matches may be formed in any four directions (Up,Down, Left, Right). Therefore, you will implement a helper function isMatching() todo the checking. This function will do a simple checking to see if there is at least onematch-three that can be formed by the given cell in any of the directions. It shall returnone (1) if there is at least one match; If there is no match found, return zero (0).You may need to call it twice to check both the original position and swapped positionfor any potential matches.After each check, immediately undo the swap to restore the board to its original state.If a match is found during any swap, return one (1); If no matches are possible after allcheck, return zero (0). The main function will check this status andThe following input can be used to check the game over status:initialized to 0 and will be incrementedaseach candy is used during gameplay.6.2.Read board and stacks from filePreviously inPart I the game board and stacks are read from hard-coded arrays forasier debugging. Now let’s extend the function to file I/O and give us flexibility to
eplace the game board to a different initial status.The main() function will first call the initGameBoardFromFile() function, whichinitializes these arrays. The contents of the arrays should be read from a filenamed“board.txt”. Finally the function should return the number of candies in the stack,which will be stored in the numCandies variable in the main function.ENGG1110 Project19 of 26Below is an example of the expected format for “board.txt”:
- First Line: Contains two integers representing the game board dimensions – theumber of rows r and columns c.
- Next r Lines: A grid of r x c integers representing the initial game board. Eachinteger corresponds to a candy type.
- Following Line: Contains a single integer n, which corresponds to numCandies
and represents the total number of extra candies in the stacks[].
- Final Line: A list of n integers, each representing an extra candy that will be usedto fill the board when matches are removed.
Please ensure that the file is read correctly, and handle file operations properly. If anerror occurs (e.g., the file cannot be opened), output the following message andterminate the program with an exit code of -1.Failed to open board.txt!\nYou should implement the gravity algorithm in the applyGravity() function forimulating“gravity”. The main() function will call this function if the swapping isuccessful –i.e. the return value of askForSwap() is non-zero.n this function, implement the gravity feature to shift candies downwards into emptyspaces.Starting from the bottom of the each column, the function should upward to find emptyspaces (represented by ASCII 32 ‘ ’). When such empty space is detected, shift any ENGG1110 Project20 of 26candies above it down by one row . Repeat this processuntil each column has no emptyspace remaining below any candies.At the end of the applyGravity(), call printGameBoard() to output the game board.In this example, the candies at the top of column 2should fall down to fill the emptyspaces below. and the result should look like this:21 of 26After calling fillEmpty() in the main() function, you should see the following:Once the original candies have fallen to the bottom (highlighted in yellow above), anyremaining empty spaces are refilled sequentially using candies from the stacks[]array.The current variable in the parameter keeps track of the position in stacks[] from wherethe next candy should be drawn. Each time after the candies is drawn, current isncremented to point to next candies.Here is the example of how current variable works with the stacks[]. After thebeginning of the game, the current variable is set to zero (0) to indicate the candy drawn
next is the first item in the stack. current = 01 2 3 3 2 1 1 0After one candy is drawn for refill, the current variable is incremented to one (1) suchthat next candy drawn isthe second item in the stacks[].current = 11 2 3 3 2 1 1 0Inthe game, this is the array that helps you to convert the number to the candyrepresentation.char candies[] = {'*', '#', '@', '%'}With this array, you can observe that the empty cells are filled with “#”, “@” and “%”
from bottom to top, which is 1,2,3 in the stacks array respectively.process will continue until all the candies in the stack are exhausted. When filling
the candy, if the number of candies remaining in the stacks[] is less than the number ofempty spaces on the board, the game will be unable to fill all spaces. In this casethegame should display an error message and terminate the program with an exit code of-
- No more candies available.ENGG1110 Project22 of 26This check will naturally handle both cases: if stacks[] is exhausted during normal gameplay, or if stack[] is empty from the very beginning, as both conditions would trigger thesame error and exit the program at this point.If multiple columns contain empty spaces, fill these spaces in a bottom-to-top orderwithin each column, moving from the leftmost column to the rightmost column. Here isthe example of the case of filling in multiple column spaces. The number in red italicand brackets indicates the filling sequence.When the candies are refilled, new matches may form on the board. To mimic realgameplay, the game should continuously check for new matches as the board refills,repeating the process until the board is stable with no further matches.The mainfunction will call cascade() function right after the matching process. Withinthe function,you should call both the applyGravity() and fillEmpty() for thecascade process. As a result, any previous calls to these functions in the main functionshould be removed, as they are now called within cascade().In the cascade function, you are required to check if there are any matches for eachcell. For this, you will call findMatchAndRemove() function (developed in part I) to findall matches on each non-empty cell. You can make use of the return valueoffindMatchAndRemove() to determine whether a match is found.In the cascade function, repeat the process until no further matches can be found in theboard. In each checking round:
- Apply the gravity.
- Fill in all the empty cells on the board and get the updated value of current
- Print the Gameboard to show the current status
- Remove all matches found on the board. Starting from the top-left corner (0,0),check each cell for matches in the following order:
- Row by Row, Column by Column: For each cell, proceed across each rowfrom left to right, then move down to the next row.
- Check Directions: For each cell, check for matches in the order of Left,Right, Top, and BottomENGG1110 Project23 of 26Clear Matches: If a match is found, clear the matching candiesimmediately before proceeding to the next cell.If there is any removal, output the following at the end of checking:Cascade Matches found!\n
- After the cascade checking completes with no further matches, return theupdated value of current to the main() function.Repeat these steps until no matches are left, ensuring that all cascading actions arecompleted before returning to the main function.Below is the sample of a cascade matching, the matches found by the cascade functionare in red font.
Academic Honesty and Declaration Statement
Attention is drawn to University policy and regulations on honesty in academic work,and to the disciplinary guidelines and procedures applicable to breaches of such policyand regulations. Details may be found at
https://www.erg.cuhk.edu.hk/erg/AcademicHonesty .You are required to fill in the following declaration statement as the comment at thebeginning of the main.c source code with your information. Assignments without theproperly signed declaration will not be graded.Tools such as software similarity measurement, AI-tool fingerprint detection, etc., mightbe used to inspect all submissions.declare that the project here submitted is original
* except for source material explicitly acknowledged,
* and that the same or closely related material has not been
* previously submitted for another course.
* I also acknowledge that I am aware of University policy a nd
* regulations on honesty in academic work, and of the disciplinary* guidelines and procedures applicable to breaches of such* policy and regulations, as contained in the website.*/Grading Platform and SubmissionWe will grade your work in Gradescope autograder. Please note that while passing thetest cases is necessary, it is not sufficienon its own for full marks. Additional marks willbe allocated based on the completeness and adherence to all requirements specified inthe project documentation, including code organization, functionality, and adherenceto the design specifications.ENGG1110 Project26 of 26Please follow the steps below to submit your work by the deadline.
- Rename the modified main.c for part I to main_part1.c
- Rename the source code for part II to main_part2.c
- Submit your .c file to the Gradescope.Please only submit the source file (.c). You may submit many times before the due date,but the latest attempt will be graded.
- Late SubmissionThe late submission penalty is as follows:
- Within 3 days (72 hours): 10% per 24 hours
- 3-7 days: 50% penalty
- More than 7 days: 100% penalty (Your work will not be graded)
NOTE: Submitting the project is crucial in PASSING the co
标签:function,candies,puzzle,should,will,game,board,match From: https://www.cnblogs.com/comp9321/p/18543643