Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
CS112 Assignment 9 CS112 Assignment 9: Critters The goals of this assignment are to learn more about object-oriented programming (especially inheritance) and to learn how to program the actions of the characters in a programming game. For this assignment, you must work on your own! Pair programming is NOT allowed on this assignment! Due: 11:00 p.m., EDT, April 19, Thursday. Note: While the normal late policy dose apply to this assignment for the grade, we can not guarantee that any Bulldog handed in after 11:59PM on Saturday will be included in the tournament. News: You can now download example critters. Copy the class files into the same directory as CritterMain to run them. Note that the zip file contains some files that have identical names to the classes you are creating. Don't get them confused with each other We will be running two pretournaments before the actual contest. The first one will be Wednesday April 18th at 11:00 PM, the second one will be on Thursday April 19th at 11:00 PM. If you want to partake in the tournaments upload your Bulldog before the given time. We will post links to the result here. The result of the first practice tournament is now available. 15 Students participated. Congrats to Daniel Gordon on winning. Remember to watch your back, there is still a long time to the real tournament. The result of the second practice tournament is now available. 50 Students participated. Congrats to Celine Cuevas on winning. Remember to watch your back, there is still a long time to the real tournament. The result of the final tournament and the in class bracket is now available. Part 1. Understanding the Problem You are provided with several client program classes that implement a graphical simulated 2D world of animals. This world is called a critter world. Specifically, the world is divided into cells with integer coordinates. In our assignment, we define the world to be 60 cells wide and 50 cells tall. The upper-left cell has coordinates (0, 0); x increases to the right and y increases downward. You will write classes that define the behavior of some animals in the world. Animals move and behave in different ways. Your classes will define the unique behaviors for each animal. Movement. On each round of the simulation, the simulator asks each critter object which direction it wants to move. Each round a critter can move one square north, south, east, west, or stay at its current location ("center"). The world has a finite size, but it wraps around in all four directions (for example, moving east from the right edge brings you back to the left edge). Such wrapping is called torus topology, and is what you would expect if you lived on a torus shaped planet. This program may be a bit confusing at first, because you do not write its main method; your code is not in control of the overall execution. Instead, your objects are part of a larger system. You might want your critters to make several moves at once using a loop, but you can't. The only way a critter moves is to wait for the simulator to ask it for a single move and return that move. This experience can be frustrating, but it is an interesting application of object-oriented programming. Fighting/Mating. As the simulation runs, animals may collide by moving onto the same location. When two animals collide, if they are from different species, they fight. The winning animal survives and the losing animal is removed from the game. Each animal chooses one of Attack.ROAR, Attack.POUNCE, or Attack.SCRATCH. Each attack is strong against one other (e.g. roar beats scratch) and weak against another (roar loses to pounce). The following table summarizes the choices and which animal will win in each case. To remember which beats which, notice that the starting letters of " Roar, Pounce, Scratch" match those of "Rock, Paper, Scissors." If the animals make the same choice, the winner is chosen at random. Below is the score table:       Critter #2       Attack.ROAR Attack.POUNCE Attack.SCRATCH Critter#1 Attack.ROAR Random winner # 2 wins #1 wins   Attack.POUNCE #1 wins Random winner #2 wins   Attack.SCRATCH #2 wins #1 wins Random winner If two animals of the same species collide, they "mate" to produce a baby. Animals are vulnerable to attack while mating: any other animal that collides with them will defeat them. An animal can mate only once during its lifetime. Eating. The simulation world also contains food (represented by the period character, ".") for the animals to eat. There are pieces of food on the world initially, and new food slowly grows into the world over time. As an animal moves, it may encounter food, in which case the simulator will ask your animal whether it wants to eat it. Different kinds of animals have different eating behavior; some always eat, and others only eat under certain conditions. Every time one class of animals eats a few pieces of food, that animal will be put to "sleep" by the simulator for a small amount of time. While asleep, animals cannot move, and if they enter a fight with another animal, they will always lose. Scoring. The simulator keeps a score for each class of animal, shown on the right side of the screen. A class's score is based on how many animals of that class are alive, how much food they have eaten, and how many other animals they have killed. Provided Files. Download the following supporting files: Critter.java, CritterMain.java, and MiniMain.java (for testing purpose). Run CritterMain.java to start the simulation. Each class you write will extend a superclass named Critter. This is an example of inheritance, as discussed in Lecture 31 (pdf/1, pdf/4). Inheritance makes it easier for our code to talk to your critter classes, and it helps us be sure that all your animal classes will implement all the methods we need. But to do this assignment you don't need to understand much about inheritance. Your class headers should indicate the inheritance by writing extends Critter, like the following: public class Ant extends Critter { ... The Critter class contains the following methods, some/all of which you must write in each of your classes: public boolean eat() When your animal encounters food, our code calls this on it to ask whether it wants to eat (true) or not (false). public Attack fight(String opponent) When two animals move onto the same square of the grid, they fight. When they collide, our code calls this on each animal to ask it what kind of attack it wants to use in a fight with the given opponent. public Color getColor() Every time the board updates, our code calls this on your animal to ask it what color it wants to be drawn with. public Direction getMove() Every time the board updates, our code calls this on your animal to ask it which way it wants to move. public String toString() Every time the board updates, our code calls this on your animal to ask what letter it should be drawn as. Just by writing extends Critter as shown above, you receive a default version of these methods. The default behavior is to never eat, to always forfeit fights, to use the color black, to always stand still (a move of Direction.CENTER), and a toString of "?". If you don't want this default, rewrite (override) the methods in your class with your own behavior. For example, below is a critter class Stone. A Stone is displayed with the letter S, is gray in color, never moves or eats, and always roars in a fight. Your classes will look like this class, except with fields, a constructor, and more sophisticated code. Note that the Stone does not need an eat or getMove method; it uses the default behavior for those operations. import java.awt.*; // for Color public class Stone extends Critter { public Attack fight(String opponent) { return Attack.ROAR; } public Color getColor() { return Color.GRAY; } public String toString() { return "St"; } NOTE: You are not necessarily required to write extends Critter on every single animal class you write. If you find that two animal classes are very similar to each other, you should have one extend the other to reduce redundancy. Running the Simulator. When you press the Go button, it begins a series of turns. On each turn, the simulator does the following for each animal: move the animal once (calling its getMove method), in random order if the animal has moved onto an occupied square, fight! (call both animals' fight methods) if the animal has moved onto food, ask it if it wants to eat (call the animal's eat method) After moving all animals, the simulator redraws the screen, asking each animal for its toString and getColor values. It can be difficult to test and debug with so many animals. We suggest adjusting the initial settings to use a smaller world and fewer animals. There is also a Debug checkbox that, when checked, prints console output about the game behavior. Critter Classes. The following are the five animal classes to implement. Each has one constructor that accepts exactly the parameter(s) in the table. For random moves, each choice must be equally likely; use a Random object or the Math.random method. 1. Ant  constructor public Ant(boolean walkSouth) color red eating behavior always returns true fighting behavior always scratch movement if the Ant was constructed with a walkSouth value of true, then alternates between south and east in a zigzag (S, E, S, E, ...); otherwise, if the Ant was constructed with a walkSouth value of false, then alternates between north and east in a zigzag (N, E, N, E, ...) toString "%" (percent) 2. Bird  constructor public Bird() color blue eating behavior never eats (always returns false) fighting behavior roars if the opponent looks like an Ant ("%"); otherwise pounces movement a clockwise square: first goes north 3 times, then east 3 times, then south 3 times, then west 3 times, then repeat toString  "^" (caret) if the bird's last move was north or it has not moved; ">" (greater-than) if the bird's last move was east; "V" (uppercase letter v) if the bird's last move was south; "<" (less-than) if the bird's last move was west 3. Hippo  constructor public Hippo(int hunger) color gray if the hippo is still hungry (if eat would return true); otherwise white eating behavior returns true the first hunger times it is called, and false after that fighting behavior if this Hippo is hungry (if eat would return true), then scratches; else pounces movement moves 5 steps in a random direction (north, south, east, or west), then chooses a new random direction and repeats toString the number of pieces of food this Hippo still wants to eat, as a String The Hippo constructor accepts a parameter for the maximum number of food that Hippo will eat in its lifetime (the number of times it will return true from a call to eat). For example, a Hippo constructed with a parameter value of 8 will return true the first 8 times eat is called and false after that. Assume that the value passed is non-negative. The toString method for a Hippo returns the number of times that a call to eat would return true for that Hippo. For example, if a new Hippo(4) is constructed, initially its toString return "4". After eat has been called on it once, calls to toString return "3", and so on, until the Hippo is no longer hungry, after which all calls to toString return "0". You can convert a number to a string by concatenating it with an empty string. For example, "" + 7 makes "7". 4. Vulture  constructor public Vulture() color black eating behavior returns true if vulture is hungry. A vulture is initially hungry, and he remains hungry until he eats once. After eating once he will become non-hungry until he gets into a fight. After one or more fights, he will be hungry again. (see below) fighting behavior roars if the opponent looks like an Ant ("%"); otherwise pounces movement a clockwise square: first goes north 3 times, then east 3 times, then south 3 times, then west 3 times, then repeats toString "^" (caret) if the vulture's last move was north or has not moved; ">" (greater-than) if the vulture's last move was east; "V" (uppercase letter v) if the vulture's last move was south; "<" (less-than) if the vulture's last move was west A Vulture is a specific sub-category of bird with some changes. Think of the Vulture as having a "hunger" that is enabled when he is first born and also by fighting. Initially the Vulture is hungry (so eat would return true from a single call). Once the Vulture eats a single piece of food, he becomes non-hungry (so future calls to eat would return false). But if the Vulture gets into a fight or a series of fights (if fight is called on it one or more times), it becomes hungry again. When a Vulture is hungry, the next call to eat should return true. Eating once causes the Vulture to become "full" again so that future calls to eat will return false, until the Vulture's next fight or series of fights. 5. Bulldog ? constructor public Bulldog() (May not accept any parameter) all behavior you decide (see below) You will decide the behavior of your Bulldog class. Part of your grade will be based upon writing creative and non-trivial Bulldog behavior. The following are some guidelines and hints about how to write an interesting Bulldog. Your Bulldog's fighting behavior may want to utilize the opponent parameter to the fight method, which tells you what kind of critter you are fighting against (such as "%" if you are fighting against a Ant). Your Bulldog can return any text you like from toString (besides null) and any color from getColor. Each critter's getColor and toString are called on each simulation round, so you can have a Bulldog that displays differently over time. The toString text is also passed to other animals when they fight you. You may want to consider leveraging this to try to fool other animals. Unlike most other assignments in CPSC112, your Bulldog can use any advanced material you happen to know in Java. If your Bulldog uses additional classes you have written, contact your TFs or instructor to make sure it will be compatible with our system. Each critter class has some additional methods that it receives by inheritance from Critter. Your Bulldog may want to use these methods to guide its behavior. None of the methods below are needed for Ant, Bird, Hippo, or Vulture. public int getX(), public int getY() Returns your critter's current x and y coordinates. For example, to check whether your critter's x-coordinate is greater than 10, you would write code such as:       if (getX() > 10) { public int getWidth(), public int getHeight() Returns the width and height of the simulation grid. public String getNeighbor(Direction direction) Returns a String representing what is next to your critter in the given direction. " " means an empty square. For example, to check if your neighbor to the west is a "Q", you could write this in your getMove method:                if (getNeighbor(Direction.WEST).equals("Q")) { public void win(), public void lose(), public void sleep(), public void wakeup(), public void mate(), public void mateEnd(), public void reset() The simulator calls these methods on your critter to notify you when you have won/lost a fight, been put to sleep/ wake up, started/ended mating, or when the game world has reset, respectively. Style Guidelines. Since this assignment is largely about classes and objects, you should follow proper object-oriented programming style. You should encapsulate the data inside your objects, and you should not declare unnecessary data fields to store information that isn't vital to the state of the object. Please try to have your code express each critter's behavior elegantly. Another aspect of the style of this program is inheritance. Your critter classes should properly extend the Critter superclass as described. Inheritance can also be used to remove redundancy between classes that are similar, and you should make use of this concept in your classes as appropriate. In other words, if two of your critter classes A and B are very much alike, you should have B extend A rather than having both simply extend Critter. Some of the points for this assignment will be awarded on the basis of how much energy and creativity you put into defining an interesting Bulldog class. These points allow us to reward the students who spend time writing an interesting critter definition. Your Bulldog's behavior should not be trivial or closely match that of an existing animal shown in class. Follow past style guidelines about indentation, spacing, identifiers, and localizing variables. Place comments at the beginning of each class documenting that critter's behavior, and on any complex code. Your critters should not produce any console output. For reference, our Ant, Bird, Hippo, and Vulture together occupy just under 199 lines including blank lines and comments (117 "substantive" lines). The Bulldog is not graded on internal correctness at all. Its code does not need to be commented, can be redundant, and can use any advanced material you like, so long as it works properly and obeys the other constraints described previously. Part 2. Carrying Out the Actual Work Download the critter subdirectory to your computer. You can either download this critter.zip file (and then unzip it) or visit this http site. The critter directory contains CritterMain.java, Critter.java, MiniMain.java files, and this assignment's README.txt file. Development Strategy. The simulator runs even if you haven't completed all of the critters. The classes increase in difficulty from Ant to Bird to Hippo to Vulture. We suggest doing Ant first. Look at Stone.java and the examples in Lecture 31 to see the general structure. It will be impossible to implement each behavior if you don't have the right state in your object. As you start writing each class, spend some time thinking about what state will be needed to achieve the desired behavior. One thing in the past that students in CPSC112 have found particularly difficult to understand is the various constructors. In this assignment, some of the constructors accept parameters that guide the behavior of later methods of the animal. It is your job to store data from these parameters into fields of the animal as appropriate, so that it will "remember" the proper information and will be able to use it later when the animal's other methods are called by the simulator. Test your code incrementally. A critter class will compile even if you have not written all of the methods (the unwritten ones will use default behavior), so add one method, run the simulator to see that it works, then add another. Part 3. Frequently Asked Questions Q: How do I get started? A: Download the three provided files. Compile and run CritterMain.java to see if the basic simulator works. Then copy/paste the contents of Stone.java into a new file and save it as Ant.java. Then you can modify the code to try to implement that animal. Q: Why doesn't CritterMain list my critters after I created and compiled them? A: There seems to be a bug with CritterMain and Dr. Java on some computers. Try running the program from the system terminal or console instead of Dr. Java. Q: When I try to run my Stone or other animals, I get the following error. Why? Exception in thread "main" java.lang.NoSuchMethodError: main A: Don't run the animal classes. Run CritterMain. Q: Why can't I use a for loop for my critter's movement? Without a loop, how will I make the critter move multiple times in a given pattern? A: This is one of the toughest aspects of object-oriented programming: accepting that your object is no longer in control of the overall program. In Critters, the simulator asks each animal for a single move at a time. You can only return one move, so your critter object must keep track of what should be returned next time. By declaring the right set of fields in each object and giving them the appropriate values, your object can "remember" information that will tell it what to do in future moves. Q: I can pick a random direction once, but how do I move in the *same* random direction multiple times? A: Try picking a random direction and then having your object "remember" that direction. How do we make objects "remember" things?. Q: How do we use a value that's passed in to the constructor, in another method of that class? A: Make the object "remember" that value for use later. How do we make objects "remember" things?. Q: Why am I getting compiler errors about Point (or some random Java file)? A: You are probably saving all of your programs into the same directory that has a Point.java file. Put your Critters program files into their own directory. Q: My CritterMain chokes with lots of compiler errors. A: Make sure that you have copied over the entire file from the web site by right-clicking and choosing "Save As" instead of only copying and pasting part of the file. Q: I tried to change color/toString/fight/etc. and it compiles, but when I run I still get the default behavior! A: Check to make sure the method headers exactly match what is expected. Classes with methods such as getcolor (capitalized improperly) or getColor(String critter) (incorrect parameters) will compile but will be silently ignored; methods with incorrect headers will not properly override the methods from Critter.java. Q: How "creative" should my Bulldog be? A: The TFs will not pre-judge your Bulldog for you, but if you follow the guidelines on the assignment writeup and implement a new set of behavior that is distinct from all the other provided critters, you should be fine. Part 4. Critter Tournament On the last day of class (April 23rd, Monday), we will host a Critter tournament. In each battle, two students' Bulldog classes will be placed into the simulator along with the other standard animals. The student with the higher score in the right sidebar advances. A "battle" is defined as the following: We run CritterMain with a standard 60x50 world, using 25 of each kind of animal. The animals present are Ants, Birds, Hippos, Vultures, Stones, and two students' Bulldogs. We start the simulator and let it run until either one student's Bulldog are completely eliminated or until roughly 1000 moves have passed. At this point whichever student's Bulldog species has the more points wins the battle. Think of the tournament like one of the major pro sports. We will run a "regular season" in which every student's Bulldog species will play many battles against randomly chosen opponent Bulldog classes. We run a season of many games (at least 64 for each student), then we grab the top 16 students that have the best win/loss records. They advance to the "playoffs", which will take place live in lecture on the last day of class. The playoffs consists of a 16-Bulldog bracket similar to part of an NCAA basketball tournament bracket. Bulldog #1 battles #16, #2 battles #15, and so on. Winners advance and losers are eliminated. Eventually one Bulldog is the champion. No grade points will be based on tournament performance. For example, a Bulldog that sits completely still might fare well in the tournament, but it will not receive full grade points because it is too trivial. Q: How do I participate? A: You are automatically added if you submit your assignment. Q: How do the battles work? A: The tournament consists of a series of battles. In each battle, two students' Bulldog classes will be placed into the simulator along with the other standard animals: Ant, Bird, Hippo, Vulture, and Stone. We run CritterMain with a standard 60x50 world, using 25 of each kind of animal. Your classes are renamed to unique names for the tournament using your net id; so one might be called Bulldog_zs9. We let the battle run until either one student's Bulldogs are completely eliminated and/or until at least 1000 moves have passed. At this point, generally whichever student's Bulldog species has the more points wins the battle. If the battle is still being hotly contested after 1000 moves, we'll keep the simulator running until the scores and state are fairly stable and the clear winner has emerged. It's possible that one bulldog will be ahead in terms of points, but all of that species has been killed off (0 alive), and the other student still has Bulldogs alive and earning points. In such a case, the simulator will keep running to allow the living bulldogs to overtake the dead one, if this will happen in a reasonably short amount of time. At the instructor's discretion, if the victory is considered a "weak" victory, we may choose to change the match into best 2 out of 3. This is done by pressing the Reset button and starting the simulator again. A "weak" victory is one that meets one of the following conditions: The scores are very close. (within a few points) One bulldog species in the lead (higher point score) has been entirely killed off, and the other student has a significant number of bulldogs still alive, but it will take a long time for them to catch up. Q: Which students' Bulldogs are shown on the last day of class (Monday, April 23rd)? A: Unfortunately there isn't enough time in the lecture to show every Bulldog. We only have time to face off the top 16 in a bracket, NCAA basketball tournament style. In order to figure out which 16 to use for the in-class tournament, we run a "regular season" in which every student's Bulldog species will play many battles against randomly chosen opponent Bulldog classes. We run a season of many games (at least 64 for each student), then we grab the top 16 students that have the best win/loss records. They advance to the "playoffs", which will take place live in lecture on the last day of class. Bulldog #1 battles #16, #2 battles #15, and so on. Winners advance and losers are eliminated. Eventually one Bulldog is the champion. (The instructor reserves the right to remove a player from the bracket if that student is not present at lecture on the day of the tournament.) IMPORTANT NOTE: The simulator runs these 64+ battles for your Bulldog by essentially 'resetting' the class between each battle and adding 25 new bulldogs to the world. It's like if you were to push the 'Reset' button on the simulator user interface. Some students' Bulldogs crash when the Reset button is pressed, because they assume there will only be 25 bulldogs that are ever constructed during the entire run of the program, etc. This common problem sometimes prevents some of the very best Bulldogs from advancing in the tournament. Test your Bulldog with the Reset feature to make sure it doesn't crash! When the simular resets the game, it calls reset on each of your Bulldog critters. If your class uses any static/shared state, it can be hard to clean that up properly, so the simulator will also check for the following static method and call it on your Bulldog class if it is present (the header must match exactly): public static void resetAll() Q: Are there any things I am not allowed to do? A: A student's bulldog will be given a loss for the battle if it throws an exception. (Be careful with those array bounds and null values.) A bulldog will be removed from the tournament if it tries to "hack" or "cheat" at the game, such as by writing files on the instructor's computer, connecting to the internet or network, or directly accessing the game model to change its contents or force a certain game result. We run our tournament system with a security setting that blocks such access from most "hack" attempts and sets that student to be the loser of the match. Play fair! Q: What is at stake? What do I get if I win? A: No grade points will be based on tournament performance. For example, a Bulldog that sits completely still might fare well in the tournament, but it will not receive full grade points because it is too trivial. But we do plan to give out some prizes for a few of the top-ranked winners. Q: What about the Hunger-Game-style setup you mentioned in the lectures? A: After we complete the NCAA-style Critter Tournament on April 23rd, we will run a bonus round following the "Hunger-Game" style setup --- we will place the top-8 Bulldog finalists (from the above NCAA-style tournament) in a standard 60x60 world, using 25 of each kind of animal (that is, no more Ants, Birds, Hippos, Vultures, Stones, just 8 students' Bulldogs). We will run the simulator and let it run until all other 7 students' Bulldogs are completely eliminated --- whoever lives at last will win this bonus round. Note: your Bulldog code can tell whether you are in an NCAA-style tournament or in an "Hunger-Game" style setup by calling the getWidth and getHeight methods: the Hunger-Game style will only be played in a 60x60 board (or whenever the width of the board is equal to the height); the NCAA-style will be assumed on all other configurations (e.g., 50x60 board, or whenever the width of the board is not equal to the height). Part 5. Editing a README.txt File Using any plain text editor (e.g., Dr. Java, emacs, or notepad) to create a text file named README.txt. We provide a README.txt file that you must use as a template. Download this file and answer all questions in the space provided. Note: the template we provide for each assignment is different from each other. Once again, this README.txt file must be a plain text file; Microsoft Word .doc or .docx formats or Mac TextEdit .rtf formats are unacceptable. Part 6. Submitting Your Assignment All you need to submit electronically for Assignment 9 are the Ant.java, Bird.java, Hippo.java, Vulture.java, and Bulldog.java files and the README.txt file. To submit, just upload these files from the Assignment submission page (Navigation Tools/Assignments) on the Yale classes*v2 server. Clarification: In the Honor Pledge the word 'aid' shall be defined to mean any aid that has knowingly violated the rules defined in class. In no circumstances should 'aid' refer to discussions with TAs and the Instructor or sanctioned discussions on Piazza. If you are unable to sign the pledge for any reason, please post a private message on Piazza explaining why. Good luck and enjoy! Enrichment Finding more about the programming game. Interested in other Java-based programming game? check out Robowiki and Robocode Copyright © 1999–2012, the Critters assignment was designed by Stuart Reges and Marty Stepp, with ideas from Steve Gribble and Victoria Kirst. [Adapted and modified by Richard Yang and Zhong Shao for use in CPSC 112]