Name: Zhang, Qia ============================================================ hw4-koch < koch.in Enter the length of one side: Enter degree of snowflake (max = 5): Making a Koch snowflake of length 2.000000 and degree 3. Graphics in qiazhang.ps ============================================================ hw4-madlib < madlib.in Input file: /home/course/cs113/homework/grading/hw4/madlib.txt assignment: word: word: A TEST This is a test of HOMEWORK 4. The line above had one substitution. This one has none. And this line has two substitutions: BACON and EGGS. ============================================================ hw4-life life.bd1 rows = 4, cols = 5 simulate = 100, display = 8 time = 0 ..... ..o.. .oOo. ..o.. time = 1 ..... .ooo. .o:o. .ooo. time = 2 ..o.. .o.o. o.:.o .o.o. time = 3 ..o.. .ooo. oo:oo ..... time = 97 .ooo. o...o oo:oo ..... time = 98 .ooo. o...o oo:oo ..... time = 99 .ooo. o...o oo:oo ..... time = 100 .ooo. o...o oo:oo ..... ============================================================ hw4-life life.bd2 rows = 12, cols = 11 simulate = 9, display = 6 time = 0 ........... ........... ........... ........... ........... ........... ...ooOoo... ........... ........... ........... ........... ........... time = 1 ........... ........... ........... ........... ........... ....ooo.... ....oOo.... ....ooo.... ........... ........... ........... ........... time = 2 ........... ........... ........... ........... .....o..... ....o.o.... ...o.:.o... ....o.o.... .....o..... ........... ........... ........... time = 7 ........... ........... .....o..... .....o..... .....o..... ........... .ooo.:.ooo. ........... .....o..... .....o..... .....o..... ........... time = 8 ........... ........... ........... ....ooo.... ........... ..o.....o.. ..o..:..o.. ..o.....o.. ........... ....ooo.... ........... ........... time = 9 ........... ........... .....o..... .....o..... .....o..... ........... .ooo.:.ooo. ........... .....o..... .....o..... .....o..... ........... ============================================================ hw4-life life.bd3 rows = 4, cols = 7 simulate = 5, display = 5 time = 0 ....... .ooOoo. ....... ....... time = 1 ..ooo.. ..oOo.. ..ooo.. ....... time = 3 ....... .oo:oo. ..ooo.. ...o... time = 4 ....... .oo:oo. .o...o. ..ooo.. time = 5 ....... .oo:oo. .o...o. ..ooo.. SOURCE FILES ====== ===== /* File: hw4-koch.c * ===== ========== * Author: Carolyn Zhang * Class: CS113 * Assignment: No.4, file 1 * Due: Oct 16, 1997 * ------------------------------------------------------------ * * USAGE: hw4-koch * ====== * * OVERVIEW: * ========= * This program draws a koch fractal with length and degree as specified * by user. The degree must be an integer no greater than MAX_DEGREE. * The program is based on the turtle graphics package. * * Algorithm Notes: * ================ * Uses simple geometry to find the amount of degrees to turn: * | * | * / \ 150 * / | \ * / | \ * / 30|30 \ * / | \ * / | \ * / \ * / \ * / 60 \ * /___________________\ * \ * 120 \ * \ * * Known Bugs: None * =========== * * Enhancement: None * ============ * * Error Handling: * =============== * 1. User enters a non-integer number for degree: * Error message: Text displayed indicating why input is invalid. * Error action: Let user try again. * 2. User enters an integer for degree greater than MAX_DEGREE: * Error message: Text displayed indicating why input is invalid. * Error action: Use MAX_DEGREE instead. * 3. user enters an integer for degree less than 0: * Error message: Text displayed indicating why input is invalid. * Error action: Use 0 as degree. * * Other Comments: * =============== * If user enters a negative number for length, the fractal will * still be drawn, only upside down. * */ #include #include #include "turtle.h" #include "simpio.h" #include "genlib.h" /* constant: the maximum degree allowed to draw. */ #define MAX_DEGREE 5 /* Function prototypes */ /* * FUNCTION: GetParameters * USAGE: GetParameters(&length, °ree); * --------------------------------------- * This function prompt the user to enter the length of the fractal and * the degree of the fractal. */ void GetParameters(double *lengthPtr, int *degreePtr); /* * FUNCTION: StartKoch * USAGE: StartKoch(length); * ------------------------- * This function get the turtle into the starting position for drawing the * koch fractal which will be centered in graphics window. */ void StartKoch(double length); /* * FUNCTION: DrawKochSnowflake * USAGE: DrawKochSnowflake(length, degree); * ----------------------------------------- * This function draws the koch fractal snowflake with the specified length * and the degree in the graphics window. */ void DrawKochSnowflake(double length, int degree); /* * FUNCTION: DrawKochLine * USAGE: DrawKochLine(length, degree); * ------------------------------------------- * This recursive function draws the sides of the koch fractal. */ void DrawKochLine(double length, int degree); /* ------------------- main function ----------------------- */ int main(void) { double length; int degree; InitTurtle(); GetParameters(&length, & degree); /* Get inputs from user */ printf("\nMaking a Koch snowflake of length %f", length); printf(" and degree %d.\n",degree); /* * position and orient turtle to keep it roughly centered * move up 2/3 of length, then turn right 150 degrees so turtle is * ready to move down the right side of the "triangle" which forms basis * for the snowflake. * * /\ <- start here and go down right side first * / \ * / \ * /______\ */ StartKoch(length); DrawKochSnowflake(length,degree); return(0); } /* * FUNCTION: GetParameters * ----------------------- * This function gets user's input for the properties of the koch fractal, * and passes the inputs by reference to the main. */ void GetParameters(double *lengthPtr, int *degreePtr) { printf("\nEnter the length of one side: "); *lengthPtr = GetReal(); printf("\nEnter degree of snowflake (max = %i): ",MAX_DEGREE); *degreePtr = GetInteger(); if (*degreePtr > MAX_DEGREE) /* Error handling for large degrees */ { *degreePtr = MAX_DEGREE; printf("Your degree is too large. Using %d instead.",*degreePtr); } if (*degreePtr < 0) /* Error handling for small degrees */ { *degreePtr = 0; printf("Your degree is too small. Using %d instead.",*degreePtr); } } /* --- End GetParameters --- */ /* * FUNCTION: StartKoch * ------------------- * This function get the turtle into the starting position for drawing the * koch fractal which will be approximately centered: * * Position and orient turtle to keep it roughly centered * move up 2/3 of length, then turn right 150 degrees so turtle is * ready to move down the right side of the "triangle" which forms basis * for the snowflake. * * /\ <- start here and go down right side first * / \ * / \ * /______\ */ void StartKoch(double length) { double x, y; x = GetWindowWidth(); y = GetWindowHeight(); PlaceTurtle(x/2, y/2); MoveTurtle(length * 2.0 / 3.0); /* Center the turtle */ TurnRight(150); } /* --- End of StartKoch ---- */ /* * FUNCTION: DrawKochSnowflake * --------------------------- * This is a wrapper function which draws the three sides of the koch fractal * recursively. */ void DrawKochSnowflake(double length, int degree) { DrawKochLine(length, degree); /* The first side */ TurnRight(120); /* Turn to draw the second side */ DrawKochLine(length, degree); TurnRight(120); /* Turn to draw the third side */ DrawKochLine(length, degree); } /* ---- End of DrawKochSnowflake ---- */ /* * FUNCTION: DrawKochLine * ---------------------- * This function draws one side of the Koch fractal with specified length * and degree using recursive method: * Base Case: when the degree is 0, just draw a straight line. * Else: * 1. Break the problem in to four parts, each represent a koch line of * lower degree in the different directions. * 2. Draw the line recursively until easy case is reached. */ void DrawKochLine(double length, int degree) { if(degree == 0) /* Easy Case */ DrawTurtle(length); else /* Not Easy Case */ { DrawKochLine(length/3, degree-1); TurnLeft(60); DrawKochLine(length/3, degree-1); TurnRight(120); DrawKochLine(length/3, degree-1); TurnLeft(60); DrawKochLine(length/3, degree-1); } } /* ---- End DrawKochLine ----- */ /* --------------------- End of File: hw4-koch.c -------------------- */ /* * File: hw4-madlib.c * ===== ============ * Author: Carolyn Zhang * Class: CS113 * Assignment: ch3, prob10 * Due: Oct 16, 1997 * -------------------------------------------------------------------- * * USAGE: hw4-madlib * ====== * * OVERVIEW: * ========= * This program plays madlib with the user . * Input: the name of the file which contains the text for madlib. * Output: prompt the user for the words. * Output: print the text with the input words of user as substitutes. * * Algorithm Notes: None * ================ * * Known Bugs: None * =========== * * Enhancement: None * ============ * * Error Handling: * =============== * 1. User input a file which cannot be found: * Error message: Text displayed indicating file not found. * Error action: Ask if user wants to try again, and acts accordingly. * 2. If input file or output file cannot be open: * Error message: Text displayed indicating file cannot be opened. * Error action: quit the program. * 3. If temporary file cannot be removed: * Error message: Text displayed indicating file cannot be removed. * * Other Comments: None * =============== * */ #include #include "simpio.h" #include "genlib.h" #include "strlib.h" /* Function prototypes */ /* * FUNCTION: WriteTemp * USAGE: WriteTemp(infile, outfile); * ---------------------------------- * This function reads from the infile, replace the words in the placeholder * with the user inputs and write to the outfile. */ void WriteTemp(FILE *infile, FILE *outfile); /* * FUNCTION: PrintFile * USAGE: PrintFile(file); * ----------------------- * This function takes a file name and display the contents of the file to * the output console. */ void PrintFile(string file); /* ---------------------- main function ------------------------- */ int main() { int ans; string fileName, tempFile; FILE *infile, *outfile; while (TRUE) /* loop until either valid file name is */ { /* entered or user quits. */ printf("\nInput file: "); fileName = GetLine(); infile = fopen(fileName,"r"); printf("\n%s\n",fileName); if (infile!=NULL) /* break if file is valid */ break; printf("\nFile %s is not found, try again?(y/n)",fileName); ans = getc(stdin); /* Give user choice to try again */ fflush(stdin); if ( ans=='n' || ans=='N' ) { printf("Bye!\n"); fclose (infile); return (0); } } /* end while loop */ tempFile = tmpnam(NULL); /* Get a name for the temporary file */ outfile = fopen (tempFile, "w"); if (outfile == NULL) Error ("Can't open temporary file."); WriteTemp(infile, outfile); /*Edit text with user inputs, write to outfile*/ fclose (infile); fclose (outfile); PrintFile(tempFile); /* display final version of madlib poem */ if( remove(tempFile)!=0 ) /* delete the temporary file */ Error("Unable to remove temporary file. "); return (0); } /* --------------------- end of main ---------------------- */ /* * FUNCTION: WriteTemp * ------------------- * This function reads the content of infile and display the words in the * placeholders to get the user's inputs. The function then copy the * infile to the outfile with the user's inputs replacing the placeholders. */ void WriteTemp(FILE *infile, FILE *outfile) { int ch; while ( (ch=getc(infile)) != EOF ) /* reads until the end of file */ { if ( ch == '<' ) /* start placeholder */ { while ((ch=getc(infile))!= EOF ) { if (ch=='>') { printf(": "); while((ch=getc(stdin))!='\n') /* read user input */ putc(ch, outfile); break; /* end placeholder */ } putc(ch, stdout); /* display placeholder */ } /* end while loop */ } /* end if statement */ else putc(ch,outfile); /* copy to outfile */ } /* end while loop */ } /* ----------------- end WriteTemp -------------- */ /* * FUNCTION: PrintFile * ------------------- * This function takes a file name as the argument and displays the content * of the file to the output console. */ void PrintFile(string file) { FILE *infile; int ch; infile = fopen(file, "r"); if (infile == NULL) Error ("Can't open input file."); while ( (ch=getc(infile))!=EOF ) /* loop through each character */ putc(ch, stdout); fclose(infile); printf("\n\n"); } /* ---------------- end PrintFile ---------------- */ /* ------------------ End of File: hw4-madlib.c --------------------- */ /* * File: hw4-life.c * ====== =========== * Author: Carolyn Zhang * Class: CS113 * Assignment: No.4, Game of life * Due: Oct 16, 1997 * --------------------------------------------------------------- * * USAGE: hw4-life fileName * ====== * * OVERVIEW: * ========= * This program takes a file name as the input and simulates the * specified number of rounds and displays the specified number of * rounds. The original board is read from the input file. Each * generation is generated according to the basic rule of Life and * Death in Conway's World. * * Algorithm Notes: None * ================ * * Known Bugs: None * =========== * * Enhancement: None * ============ * * Error Handling: * =============== * User enter an invalid file name. * Error message: Display why input is invalid. * Error action: Quit. * * Other Comments: * =============== * Note that the game board here is finite in size and the amount of * cells alive is finite. Any cells off the boundary of the board is * considered dead. * */ #include #include "genlib.h" #include "simpio.h" #include "strlib.h" /* --- type declaration --- */ typedef char **boardArrayT; typedef struct { int rows, cols; boardArrayT array; } lifeBoardT; /* ------------------- Function prototypes ------------- */ /* * FUNCTION: ReadGameFile * ---------------------- * This function reads the data from the input file and creates the game * board. */ void ReadGameFile(string fileName, lifeBoardT *boardPtr, int *simulatePtr, int *displayPtr); /* * FUNCTION: SimulateGame * ---------------------- * This function updates and displays the life board according to the * specified number from the input file. */ void SimulateGame(lifeBoardT *boardPtr, int simulateNum, int displayNum); /* * FUNCTION: DisplayBoard * ---------------------- * This function prints the board to the screen along with its corresponding * time. */ void DisplayBoard(lifeBoardT *boardPtr, int time); /* * FUNCTION: UpdateBoard * --------------------- * This function generates the next generation based on the present board. * The birth and death of the cells follows the rules from Conway's game * of life. */ void UpdateBoard(lifeBoardT *boardPtr); /* * FUNCTION: CopyBoard * ------------------- * This function returns a copy of the board passed to it. */ lifeBoardT CopyBoard(lifeBoardT *boardPtr); /* * FUNCTION: AllocateArray * ----------------------- * This function allocate space in memory for the two demensional array. */ boardArrayT AllocateArray(int rows, int cols); /* * FUNCTION: NumNeighbors * ---------------------- * This function returns the number of cells alive surrounding the specified * position on the board. */ int NumNeighbors(lifeBoardT *boardPtr, int r, int c); /* * FUNCTION: IsAlive * ----------------- * This function returns true if the cell at the specified location on the * board is alive, returns false if the cell is dead. */ bool IsAlive(lifeBoardT *boardPtr, int r, int c); /* * FUNCTION: MakeAlive * ------------------- * This function make the specified cell on the board become alive. */ void MakeAlive(lifeBoardT *boardPtr, int r, int c); /* * FUNCTION: MakeDead * ------------------ * This function make the specified cell on the board become dead. */ void MakeDead(lifeBoardT *boardPtr, int r, int c); /* * FUNCTION: DestroyBoard * ---------------------- * This function free the memory of the board. */ void DestroyBoard(lifeBoardT *boardPtr); /* * FUNCTION: GetBoard * ------------------ * This function returns the character at the specified location on the * board. */ char GetBoard(lifeBoardT *boardPtr, int r, int c); /* * FUNCTION: SetBoard * ------------------ * This function assigns 'ch' to the specified location on the board. */ void SetBoard(lifeBoardT *boardPtr, int r, int c, char ch); /* -------------------- end Function prototypes --------- */ /* -------------------- main function ------------------- */ int main(int argc, string argv[]) { string fileName; int roundsToSimulate, roundsToDisplay; lifeBoardT board; /* if syntax is wrong, exit with error message */ if (argc != 2) {Error("Syntax: %s ", argv[0]);} fileName = CopyString(argv[1]); ReadGameFile(fileName, &board, &roundsToSimulate, &roundsToDisplay); SimulateGame(&board, roundsToSimulate, roundsToDisplay); return(0); } /* --------------- end main ------------------ */ /* * FUNCTION: ReadGameFile * ---------------------- * This function reads the information from the input file and copy the * data to the board. * Memory for the array has to be allocated first, the array is copied * character by character. * Care has to be taken for the space and newline characters. */ void ReadGameFile(string fileName, lifeBoardT *boardPtr, int *simulatePtr, int *displayPtr) { int r, c, /* loop variables */ ch; FILE *infile; infile = fopen (fileName, "r"); if (infile == NULL) Error ("Can't open game file."); fscanf(infile, "%d %d", &boardPtr->rows, &boardPtr->cols); fscanf(infile, "%d %d", simulatePtr, displayPtr); printf("rows = %d, cols = %d\n", boardPtr->rows, boardPtr->cols); printf("simulate = %d, display = %d\n", *simulatePtr, *displayPtr); boardPtr->array = AllocateArray(boardPtr->rows, boardPtr->cols); for (r=0; rrows; r++) { for (c=0; ccols; c++) { ch = getc(infile); if (ch=='\n' || ch==' ') /* readjust position if reading */ c=-1; /* space or newline character. */ else boardPtr->array[r][c] = ch; } } fclose(infile); } /* --------------- end ReadGameFile -------------- */ /* * FUNTION: SimulateGame * --------------------- * This function simulate the indicated number of rounds, and display * the beginning half of the rounds (rounded down) to be displayed, and * the other half for the end. */ void SimulateGame(lifeBoardT *boardPtr, int simulateNum, int displayNum) { int time=0, firstHalf, secondHalf; firstHalf = displayNum / 2; /* round down */ secondHalf = displayNum - firstHalf; while ( time < firstHalf ) /* Display half for beginning */ { DisplayBoard(boardPtr, time); UpdateBoard(boardPtr); time++; } while ( time <= simulateNum-secondHalf) /* Simulate game alone */ { UpdateBoard(boardPtr); time++; } while ( time < simulateNum ) /* Display half for end */ { DisplayBoard(boardPtr, time); UpdateBoard(boardPtr); time++; } DisplayBoard(boardPtr, time); } /* ------------- end SimulateGame ----------- */ /* * FUNCTION: DisplayBoard * ---------------------- * This function display the contents on the board to the screen, it also * prints the time corresponding to it. */ void DisplayBoard(lifeBoardT *boardPtr, int time) { int r, c; printf("\n\n\ntime = %d \n",time); for (r=0; rrows; r++) { for (c=0; ccols; c++) printf("%c", boardPtr->array[r][c]); printf("\n"); /* postion game board */ } } /* -------------- end DisplayBoard ----------- */ /* * FUNCTION: UpdateBoard * --------------------- * This function generates the next generation of the cells based on the * Life and Death rule in the Conway's world. * The function creates a copy of the board, and checks the living conditions * for each cell from the copy and change the board based on the conditions. * At the end, the copy of the board is destroyed to save memory. */ void UpdateBoard(lifeBoardT *boardPtr) { lifeBoardT oldBoard; int r, c; oldBoard = CopyBoard(boardPtr); /* create a copy of the board */ for (r=0; r3) /* Death condition */ MakeDead (boardPtr, r, c); } /* end for loop */ /* All other cells survive. */ DestroyBoard(&oldBoard); } /* --------------- end UpdateBoard ----------- */ /* * FUCNTION: CopyBoard * ------------------- * This function returns a copy of the board passed to it. * Memory has to be allocated for the array. Then copy the array character * by character. */ lifeBoardT CopyBoard(lifeBoardT *boardPtr) { lifeBoardT tempBoard; int r, c; tempBoard.rows = boardPtr->rows; tempBoard.cols = boardPtr->cols; tempBoard.array = AllocateArray(tempBoard.rows, tempBoard.cols); for (r=0; r= boardPtr->rows ) return (FALSE); if ( c<0 || c >= boardPtr->cols ) return (FALSE); if( GetBoard(boardPtr, r, c) == 'o' || GetBoard(boardPtr, r, c) == 'O') return(TRUE); else return (FALSE); } /* -------------- end IsAlive -------------------- */ /* * FUNCTION: MakeAlive * ------------------- * This function make the cell at the specified location alive. * The home base is treated as a special case. */ void MakeAlive(lifeBoardT *boardPtr, int r, int c) { if ( GetBoard(boardPtr, r, c) == ':' ) /* Home base */ SetBoard(boardPtr, r, c, 'O'); else SetBoard(boardPtr, r, c, 'o'); } /* --------------- end MakeAlive -------------------- */ /* * FUNCTION: MakeDead * ------------------ * This function make the cell at the specified location dead. * The home base is treated as a special case. */ void MakeDead(lifeBoardT *boardPtr, int r, int c) { if ( GetBoard(boardPtr, r, c) == 'O' ) /* Home base */ SetBoard(boardPtr, r, c, ':'); else SetBoard(boardPtr, r, c, '.'); } /* -------------- end MakeDead ------------------- */ /* * FUNCTION: DestroyBoard * ---------------------- * This function free the memory for the two demensional array. */ void DestroyBoard(lifeBoardT *boardPtr) { int r; for (r=0; rrows; r++) /* deallocate the char pointers */ free (boardPtr->array[r]); free( boardPtr->array ); /* deallocate ptr to char ptr */ } /* ------------- end DestroyBoard -------------------- */ /* * FUNCTION: GetBoard * ------------------ * This function returns the character at the specified position on * the board. */ char GetBoard(lifeBoardT *boardPtr, int r, int c) { char ch; ch = boardPtr->array[r][c]; return (ch); } /* ------------------- end GetBoard --------------- */ /* * FUNCTION: SetBoard * ------------------ * This function assigns character 'ch' to the specified position on * the board. */ void SetBoard(lifeBoardT *boardPtr, int r, int c, char ch) { boardPtr->array[r][c] = ch; } /* ------------------ end SetBoard ------------------ */ /* -------------------- END OF FILE: hw4-life.c ---------------------- */ -- END OF LOG FILE FOR qiazhang --