Jump to content
  • Advertisement

Ntvu

Member
  • Content Count

    203
  • Joined

  • Last visited

Community Reputation

100 Neutral

About Ntvu

  • Rank
    Member
  1. I'm debating whether or not I should learn MATLAB. For one thing I'm not sure what I would use it for considering I focus most of my attention Web development (and occasionally a few desktop game and software). But from what I know I am going to be using it in college because I'm planning to be a computer or electrical engineering major. Do you think it would be a wise idea for me to self-teach myself MATLAB in preparation for university? Or should I just wait for a few years for the professors to teach me?
  2. Alright so the college application season is coming soon and I'll be applying to about 8 colleges, over half of which are technology-oriented in some way. The thing is though, I don't think my stats are good enough to get into them (some of them include CMU and RPI). From what I know as well as my counselor's advice, I'll only be able to get into my state university, which isn't really that great. Will that screw me over though? I want to major in computer engineering or computer science, maybe electrical engineering but will the state university be good enough? It's not in any top 10 list or whatever and I'm worried that if I do choose to major in engineering, when I graduate I will have bad employment opportunities because employers will see that i went to a crappy school, then think that I'm a bad choice or high risk and refuse to hire me. Is that really the case though, or am I just delusional? I really need a reality view into the college -> career process. I have close to no REAL real world experience and I'm interested in knowing how this all works together.
  3. I've been doing programming since I was in middle school and I'm going to be a senior this upcoming year of high school. I've built up a personal website over the years of some projects that I've done as well as some other things. The thing is though, I'm not exactly sure how to put my personal website into college admissions. I'm not quite sure how to get the admission officers to notice and put much weight on it, because I would really like to emphasize that. Basically to put it, it is definitely going to be the strongest of my ECs because programming has been my primary focus and the activity that I've put the most time into. Now about emphasizing it. Do I add it into the Common Application as an extracurricular activity? Or should I put it on an "extras" page? Or should I really emphasize it in my essay and do the above listed as well?
  4. I was thinking about something I recently thought about today. You know how those URL forwarding services like bit.ly or tinyurl work? Well, I was thinking of making one just like that, except it has a bit more functionality to it. The extra functionality allows for you to log the referer, IP address and user agent of the person who clicks on the link and then forwards him/her to the URL you specify. The other idea I had was also pretty similar to URL forwarding, except in this case, it does not forward you. Instead, when you click on the link, it just brings you to a blank page. I was thinking I could embed this in forum signatures via the 'img' tag, and then every time my signature is viewed, requests will be sent to my site and then IP addresses and user agents could be logged, along with referer, date, time, etc etc... But my question is, would this be considered illegal? And if it is, what specific laws would I be violating? And what could be the potential punishments of this?
  5. I'm interested in releasing source code (the entire source code, including images, database schemas, css, js, etc) for some of my PHP web applications. However, I need some advice on which license I should use and the pros and cons of each. All of my web applications are already running online, if that's important. Also I'm putting the downloads for the source on my personal website, so it's accessible to everyone. Which license should I use though? I know that there are many of them and I can't seem to choose one. However, my criteria for a license is that: 1) Even if I release the source code, I can still legally have my own web applications running online. 2) After releasing the source, I can still create future versions of my applications and not be legally oblidged to release the source. 3) I don't want companies to use my code for commercial purposes without my consent. 4) I don't care if people change/edit the source, setup the web application on another web server on another domain, etc. as long as I still receive credit. Sorry if I sound a bit stupid -- I'm not very experienced with this type of stuff. But really, which license should I use? I prefer a more permissive one than a restrictive one.
  6. Quote:Original post by superpig Here's a few thoughts to begin with. Why use a fixed array of 10 students with a count variable, instead of java.util.List<Student>? The assignment requires me to. Quote:Original post by superpig The navigation methods 'first' and 'last' are a bit ambiguous as to whether they actually change the model - I'd expect collection.first() and collection.last() to return the first and last elements in the collective respectively, and I wouldn't expect them to change any state (like which one is currently 'selected'). The names selectFirst, selectNext, selectPrev, selectLast would be better. Again, the assignment requires me to. Quote:Original post by superpig getHighScore() is confusingly named because I'd expect it to return the highest score, not the student with the highest score. Try calling it getHighestScoring() instead? I'd be inclined to separate the 'currently selected' functionality from the model into a separate 'cursor' class. Imagine two views trying to use the model at the same time - if the cursor is separated out, then they could each have a different 'selected' student with no problems. The model would probably need to fire a couple of events for students being added/removed so the cursors could make sure they don't become invalid. All of that was part of the original code from the textbook, none of it was written by me. The same goes for the array of only 10 students, the navigation methods, etc. The last source block I have (the third one) is the code that I wrote.
  7. public class TestScoresModel{ private Student[] students; // Array of students private int indexSelectedStudent; // Position of current student private int studentCount; // Current number of students public TestScoresModel(){ // Initialize the data indexSelectedStudent = -1; studentCount = 0; students = new Student[10]; } // Mutator methods for adding and replacing students public String add(Student s){ if (studentCount == students.length) return "SORRY: student list is full"; else{ students[studentCount] = s; indexSelectedStudent = studentCount; studentCount++; return null; } } public String replace(Student s){ if (indexSelectedStudent == -1) return "Must add a student first"; else{ students[indexSelectedStudent] = s; return null; } } // Navigation methods public Student first(){ Student s = null; if (studentCount == 0) indexSelectedStudent = -1; else{ indexSelectedStudent = 0; s = students[indexSelectedStudent]; } return s; } public Student previous(){ Student s = null; if (studentCount == 0) indexSelectedStudent = -1; else{ indexSelectedStudent = Math.max (0, indexSelectedStudent - 1); s = students[indexSelectedStudent]; } return s; } public Student next(){ Student s = null; if (studentCount == 0) indexSelectedStudent = -1; else{ indexSelectedStudent = Math.min (studentCount - 1, indexSelectedStudent + 1); s = students[indexSelectedStudent]; } return s; } public Student last(){ Student s = null; if (studentCount == 0) indexSelectedStudent = -1; else{ indexSelectedStudent = studentCount - 1; s = students[indexSelectedStudent]; } return s; } // Accessors to observe data public Student currentStudent(){ if (indexSelectedStudent == -1) return null; else return students[indexSelectedStudent]; } public int size(){ return studentCount; } public int currentPosition(){ return indexSelectedStudent; } public int getClassAverage(){ if (studentCount == 0) return 0; int sum = 0; for (int i = 0; i < studentCount; i++) sum += students.getAverage(); return sum / studentCount; } public Student getHighScore(){ if (studentCount == 0) return null; else{ Student s = students[0]; for (int i = 1; i < studentCount; i++) if (s.getHighScore() < students.getHighScore()) s = students; return s; } } public String toString(){ String result = ""; for (int i = 0; i < studentCount; i++) result = result + students + "\n"; return result; } } import java.util.Scanner; public class TestScoresView{ private TestScoresModel model; public TestScoresView(TestScoresModel m){ model = m; run(); } // Menu-driven command loop private void run(){ while (true){ System.out.println("start of run method"); System.out.println("Number of students: " + model.size()); System.out.println("Index of current student: " + model.currentPosition()); displayMenu(); int command = getCommand("Enter a number [1-11]: ", 1, 11); if (command == 11) break; runCommand(command); } } private void displayMenu(){ System.out.println("MAIN MENU"); System.out.println(" 1. Display the current student"); System.out.println(" 2. Display the class average"); System.out.println(" 3. Display the student with the highest grade"); // missing code System.out.println("11. Quit the program"); } // Prompts the user for a command number and runs until // the user enters a valid command number // Parameters: prompt is the string to display // low is the smallest command number // high is the largest command number // Returns: a valid command number private int getCommand(String prompt, int low, int high){ // errors checking Scanner reader = new Scanner(System.in); int command = low - 1; while (command < low || command > high){ System.out.print(prompt); command = reader.nextInt(); if (command < low || command > high) System.out.println("Error: command must be between " + low + " and " + high); } return command; } // Selects a command to run based on a command number, // runs the command, and asks the user to continue by // pressing the Enter key private void runCommand(int command){ if (command == 1) displayStudent(); else if (command == 2) System.out.println("Average score = " + model.getClassAverage()); //missing code } private void displayStudent(){ Student s = model.currentStudent(); if (s == null) System.out.println("No student is currently available"); else System.out.println(s); } private void displayHighScore(){ Student s = model.getHighScore(); if (s == null) //missing code else //missing code } private void addStudent(){ Student s = new Student(); Scanner reader = new Scanner(System.in); System.out.print("Enter the name: "); s.setName(reader.nextLine()); for (int i = 1; i <= s.getNumberOfTests(); i++){ //missing code } String message = s.validateData(); if (message != null) System.out.println(message); else{ message = model.add(s); if (message != null) System.out.println(message); else System.out.println("Student added"); } } private void editStudent(){ Student s = model.currentStudent(); if (s == null) System.out.println("No student is currently available"); else{ // Work on a temporary copy Student temp = new Student(s); String menu = "EDIT MENU\n" + "1. Change the name\n" + "2. Change a score\n" + "3. View the student\n" + "4. Quit this menu\n"; Scanner reader = new Scanner(System.in); int command = 1; while (command != 4){ System.out.print(menu); command = getCommand("Enter a number [1-4]: ", 1, 4); if (command == 1){ //lots of missing code }else{ // Check for valid data before writing to database String message = temp.validateData(); if (message != null) System.out.println(message); else model.replace(temp); } } } } } Do you think it is good? Bad? And why? After reading through it I decided to improve on it because some parts of it looked like they could be better designed. This is my completed code for the view file, you can also see that I basically rewrote the whole thing. /* * Test Scores View */ import java.util.Scanner; public class TestScoresView { private TestScoresModel model; private Scanner scanner; public TestScoresView(TestScoresModel newModel) { model = newModel; scanner = new Scanner(System.in); run(); } private void run() { int command = 0; while (command != 11) { System.out.println("Number of students: " + model.size()); System.out.println("Current student index: " + model.currentPosition()); System.out.println(); displayMenu(); command = getCommand("Enter a number [1-11]: ", 1, 11); runCommand(command); } } private void displayMenu() { String[] menuOptions = { "Display current student", "Display class average", "Display student with highest grade", "Display all students", "Edit current student", "Add new student", "Go to first student", "Go to last student", "Go to next student", "Go to previous student", "Quit the program" }; for (int c = 0; c < menuOptions.length; c++) System.out.println((c + 1) + ": " + menuOptions[c]); System.out.println(); } private int getCommand(String prompt, int min, int max) { // Keep prompting for input until valid input is received int command = min - 1; while (command < min || command > max) { try { System.out.print(prompt); command = Integer.parseInt(scanner.nextLine()); } catch (Exception exception) { command = min - 1; continue; } } return command; } private void runCommand(int command) { switch (command) { case 1: System.out.println((model.size() > 0) ? model.currentStudent() : "There are no students."); break; case 2: System.out.println("The class average is " + model.getClassAverage()); break; case 3: Student highScoreStudent = model.getHighScore(); System.out.println((highScoreStudent != null) ? "The student " + highScoreStudent.getName() + " got the highest score of " + highScoreStudent.getHighScore() : "There are no students yet."); break; case 4: System.out.println((model.size() > 0) ? model : "There are no students."); break; case 5: editStudent(); break; case 6: addStudent(); break; case 7: System.out.println((model.size() > 0) ? model.first() : "There are no students."); break; case 8: System.out.println((model.size() > 0) ? model.last() : "There are no students."); break; case 9: System.out.println((model.size() > 0) ? model.next() : "There are no students."); break; case 10: System.out.println((model.size() > 0) ? model.previous() : "There are no students."); break; } // Wait for enter key to be pressed before continuing if (command >= 1 && command <= 10) { System.out.println("Press the enter key to continue."); scanner.nextLine(); } } private void addStudent() { Student newStudent = getStudentInput(); String errors = newStudent.validateData(); if (errors == null) { if (model.add(newStudent)) { System.out.println("Student has successfully been added."); } else { System.out.println("The list of students is full, so the student was not added."); } } else { System.out.println(errors); } } private void editStudent() { if (model.size() > 0) { Student updatedStudent = getStudentInput(); String errors = updatedStudent.validateData(); if (errors == null) { System.out.println("Student has successfully been edited."); model.replace(updatedStudent); } else { System.out.println(errors); } } else { System.out.println("There are no students to edit."); } } private Student getStudentInput() { String name = ""; int[] tests; int testCount = 0; while (name.length() == 0) { System.out.println("Enter the student's name: "); name = scanner.nextLine(); } while (testCount <= 0) { System.out.println("How many tests does this student have: "); try { testCount = Integer.parseInt(scanner.nextLine()); } catch (Exception exception) { testCount = 0; continue; } } tests = new int[testCount]; for (int c = 0; c < testCount; c++) { int score = -1; while (score < 0 || score > 100) { System.out.println("Enter score for test #" + (c + 1) + ": "); try { score = Integer.parseInt(scanner.nextLine()); } catch (Exception exception) { score = -1; continue; } } tests[c] = score; } return new Student(name, tests); } } What do you think of this code and how do you think I can improve it?
  8. Alright so here's what happened. Yesterday night I accidentally dropped my Logitech mouse on the floor while I was using the computer. I tried to use it again as usual but the right mouse button wasn't functioning. Everything else works fine though. I think that the right mouse button is jammed in or something because I can't even press down on it anymore. Also when I shake the mouse, I hear a little rattling sound coming from inside, so I guess some of the smaller components from inside came loose. I don't think I'll be able to fix the mouse (but please feel free to give me suggestions) however I need to be able to right-click again. Are there any settings that I can alter in the Control Panel that will assign right-clicks to a different mouse command?
  9. It seems to me that high school education regards computer science as basically programming. I looked over the course listings for my high school and also at AP Computer Science; all of them are about learning to program in Java. Yes, only Java, and nothing else. However I think there's something wrong with this. Isn't programming supposed to be more than just programming or the act of learning programming languages? When I think of computer science, I think about combining one's knowledge base in computers with his or her problem solving skills to solve intriguing, challenging problems. Unfortunately it seems like high school computer science education is not the same. I'm going into college two years from now. What can I expect to learn as a computer science major in college? I know that I'm going to programming, of course, but what else will I learn about? Networks? Database? Computer security? Software and hardware? Are computer science classes in college vastly different from those that you see in high school? How? What about computer engineering?
  10. I'm interested in creating network-based C# applications. I would like to create programs that can connect to websites and other services, send data if necessary, receive data, etc. I did some research and found out that there are two .NET Framework namespaces that deal with network programming: System.Net and System.Net.Sockets; Are those what I need to begin? If so, I already did some Google searches for some tutorials. However I can't be sure that they are up-to-date let alone accurate, because most of them were written years ago. Can someone recommend me a more current and reliable resource to learn C# network programming from? Also can you tell me about the capabilities of this? What are the limits? Am I restricted to only using these libraries or can I also use other network libraries like Twisted as an alternative solution?
  11. I've been learning about C# for about a month now and so far everything's going alright. I didn't find it too difficult to switch from PHP to C# besides a few adjustments I had to make. I'm able to comprehend most of C#'s features, except for two of them: delegates and events. I've read several articles and tutorials on them yet I feel that I don't understand them completely. I've tried using them before but I can't really think of a good time when I would need them. From what I know, a delegate in C# is basically a type-safe function pointer. You can initialize a delegate object with a method (?) and then you can call the delegate as if it were a method and it will call the function. I also read that in C# delegates are by reference and in C++ function pointers are by value, although I have no clue what this means. I'm not exactly sure how delegates would be of use. Why use a delegate instead of making a function accessible to another function/class in another scope? Why is it a good idea to pass delegates as arguments to functions? I know even less about events in C#. From what I read, they are based on a subscriber model where you can add a function to an event, something like this: myEvent += new Function And then once the event comes up then it will call the function and pass the arguments to it. Also I don't know what use I could make of events. What are some good situations to use them in and how do I use them properly? Can someone please explain this or point me to an article/tutorial that will provide me with a solid grasp on these features? Thanks.
  12. After almost two weeks of delving into C# and adjusting to coding styles and familiarizing myself with the language, I'm ready to begin learning about networking. I'm interested in learning about things like sockets, TCP/IP, wireless networks, ports, DNS, packets, etc. What I'm more interested in learning about is how to apply these concepts to create my own programs (windowed, in C#) that can connect over a network using a socket (or something similar) and send and receive data. I looked around and found a networking site which looks fairly reliable. The site is at http://learn-networking.com however I'm not sure whether I should completely trust the information or not. Can someone take a look at it and ascertain the reliability and accuracy of the information? Also what are some good resources for learning about network programming in C#? Thanks.
  13. Again, please point out anything you find that detracts from the quality of the code, the good points, the bad points, what I could improve on. Also it would be nice if you could rate the code out of 10 (1 = worst, 10 = best) and also give a light evaluation of my programming skills, such as my strengths and weaknesses, etc. ------ I'm also going to post an idea I had before. I'm not exactly sure whether it's a good idea to do it though. I was thinking about making a Battle class to handle battles (if I choose to do this I will rename the namespace to something else). Do you think this would be a good idea? I was thinking I could have methods inside class Battle such as: PreCycle - Handles things that occur before actions can be made (such as ailment effects like poison, stun, and other messages) MainCycle - Handles the actual battle. In this stage the player chooses an option, chooses a target if he's attacking and attacks the monster. Monster attacks back after he attacks. PostCycle - For things that happen after the player and all monsters have attacked. And of course all these methods will be private as they'll be handled by the main loop. My idea was something like this: // Battle.cs class Battle { Entity player = null; Entity[] monsters; Random random = new Random(); ... public void Start(Entity p, params[] Entity m) { player = p; monsters = new Entity[m.Length]; for (int c = 0; c < m.Length; c++) { monsters[c] = m; } } public bool Loop() { if (GameOver()) // GameOver is a private function return false; PreCycle(); MainCycle(); PostCycle(); return true; } } // Program.cs class Program { ... static void Main() { Entity player = ... Entity monster1 = ... Entity monster2 = ... Battle battle = new Battle(); battle.Start(player, monster1, monster2); while (battle.Loop()); Console.ReadLine(); } }
  14. First of all I'd like to thank those who gave me advice on how to improve my code in my previous thread. I took a lot of your suggestions and used them to improve my code. Now my code count is a little bit over 800 lines and I could use your help again. The code is below. Program.cs using System; using System.Text; using Game.Classes; namespace Game.Program { partial class Program { static Random random = new Random(); static void Main(string[] args) { // Entities for the battle Entity player = new Entity("Ntvu", 120, 6000, 6500, 550); Entity dog = new Entity("Dog", 120, 35000, 820, 3800); Entity cat = new Entity("Cat", 50, 200000, 500000, 250); // Game loop while (!GameOver(player, dog, cat)) { ActivateAilments(player, dog, cat); MessageStatus(player, dog, cat); MessageMenu(player, dog, cat); } // Display final message and quit if (player.Dead) Console.WriteLine("Unfortunately you have been slaughtered. But feel free to try again!"); else Console.WriteLine("Congratulations! You have defeated your enemies and won the game!"); Console.ReadLine(); } } } Utils.cs using System; using System.Text; using Game.Classes; namespace Game.Program { partial class Program { /* Separates text using two sets of newlines, adjust as necessary */ static void Break() { Console.Write("\n\n"); } /* Prompt the user to press the enter key before continuing */ static void Pause() { Console.WriteLine(); Console.WriteLine("Press enter to continue"); Console.ReadLine(); Break(); } /* Keeps a value between 0 and the maximum value for 32-bit integers */ public static int Clamp(int value) { return Clamp(value, 0, Int32.MaxValue); } /* Keeps a value between a minimum and a maximum */ public static int Clamp(int value, int min, int max) { if (value < min) { return min; } else if (value > max) { return max; } return value; } /* Takes the user's input in Int32 form and handles formatting errors transparently */ static int MenuInput() { // Some menu options could use 0 as an option, so we use -1 instead to prevent these kinds of conflicts int choice = -1; Console.Write("> "); // If the call to Int32.Parse() fails, then it will throw a FormatException exception // The catch statement will catch that exception and resume program execution transparently // without interrupting anything or displaying any errors, etc. try { choice = Int32.Parse(Console.ReadLine()); } catch (FormatException) { choice = -1; } return choice; } /* Creates a menu based on the arguments passed, takes the user's input, and returns it */ static int Menu(params string[] menuOptions) { int choice = 0; // Keep looping until we get valid input while (choice < 1 || choice > menuOptions.Length) { Break(); // Display all menu options in list form for (int menuIndex = 0; menuIndex < menuOptions.Length && menuOptions[menuIndex].Trim().Length > 0; menuIndex++) { Console.WriteLine("{0}: {1}", menuIndex + 1, menuOptions[menuIndex]); } choice = MenuInput(); } return choice; } /* Creates a target menu for selecting active monsters based on the information in the array of Entity objects passed */ static int TargetMenu(Entity[] targetList) { int choice = -1; while (choice < 0 || choice > targetList.Length) { Break(); Console.WriteLine("Select a target: \n"); // Go through all the targets and list their information for (int targetIndex = 0; targetIndex < targetList.Length; targetIndex++) { // Do not list dead targets if (targetList[targetIndex].Dead) continue; Console.WriteLine("{0}: {1} - {2}/{3}", targetIndex + 1, targetList[targetIndex].Name, targetList[targetIndex].Health, targetList[targetIndex].MaxHealth); } // Add in a cancel option (0) to exit from the target menu Console.WriteLine("0: Cancel"); // Take user input choice = MenuInput(); // If the cancel option was chosen, then return -1 to signal it if (choice == 0) { return -1; } // Make sure that the target is not dead if (choice >= 1 && choice <= targetList.Length) { if (targetList[choice - 1].Dead) { choice = -1; continue; } } } // The indexes were increased by one during display, but in reality they begin at 0 and not 1 return choice - 1; } } } Messages.cs using System; using System.Text; using Game.Classes; namespace Game.Program { partial class Program { /* Displays status (name, health, ailments, etc) for an entity or list of entities */ static void MessageStatus(params Entity[] entityList) { foreach (Entity entity in entityList) { // Do not list dead entities if (entity.Dead) continue; string ailments = ""; if (entity.Poisoned) { ailments += "Poisoned, "; } if (entity.Stunned) { ailments += "Stunned, "; } if (ailments.Length > 0) { ailments = ailments.Substring(0, ailments.Length - 2); } Console.WriteLine("{0} (Lvl {1}) [{2}] - {3}/{4}", entity.Name, entity.Level, ailments, entity.Health, entity.MaxHealth); } Break(); } /* Display message saying that a target has been attacked */ static void MessageAttack(Entity attacker, Entity target, int attacker_damage) { Console.WriteLine("{0} hit {1} for {2}", attacker.Name, target.Name, attacker_damage); } /* Display message saying that a target has been killed */ static void MessageDead(string name) { Console.WriteLine("{0} was killed.", name); } /* The main battle menu where the player selects an option and carries it forward */ static void MessageMenu(Entity player, params Entity[] monsters) { _BattleMenu: // Build menu and get the player's input (option) int choice = Menu("Attack", "Defend", "Skill", "Potions", "Run"); Break(); switch (choice) { case 1: { // If there's more than one monster then select a target first int target = monsters.Length > 1 ? TargetMenu(monsters) : 0; // If the cancel button was pressed (return value of -1) then cancel the choice if (target == -1) { goto _BattleMenu; } DoAttack(player, monsters[target]); break; } case 2: { // It doesn't matter which monster is targeted, either way the player can't damage anything DoDefense(player, monsters[0]); break; } case 3: // display skill list break; case 4: // display item list break; case 5: Environment.Exit(0); break; } Pause(); } } } Battle.cs using System; using System.Text; using Game.Classes; namespace Game.Program { partial class Program { /* Calculates the damage based on the attacker's attack, target's defense and random variables */ static int CalculateDamage(int attack, int defense) { // Damage = (attack * 2) + (extra damage of 0 to 1/3 the attack) - (defense) return Clamp(attack * 2 + random.Next(0, attack / 3) - defense); } /* Determines whether game is over or not, returns true if it is, otherwise false */ static bool GameOver(Entity player, params Entity[] monsters) { // If the player died then it's an immediate game over if (player.Dead) return true; int deadMonsters = 0; foreach (Entity monster in monsters) { if (monster.Dead) deadMonsters++; } // If all monsters are killed, then it's also game over if (deadMonsters == monsters.Length) { return true; } return false; } /* Checks for ailments and if activated, uses their effects */ static void ActivateAilments(params Entity[] entityList) { foreach (Entity entity in entityList) { int damage = 0; if (entity.Poisoned) { // Damage of poison = 1/10 of health damage = entity.Health / 10; entity.Damage(damage); Console.WriteLine("{0} took {1} damage from poison.", entity.Name, damage); } if (entity.Stunned) { // Damage of stun = 1/2 to 1/50 of health damage = entity.Health / random.Next(2, 50); entity.Damage(damage); Console.WriteLine("{0} took {1} damage from stun.", entity.Name, damage); } if (damage > 0) { // Pause to alert player that a target has been damaged Pause(); } } } /* Attack option from the menu - player attacks target and target attacks back */ static void DoAttack(Entity attacker, Entity target) { // Calculate attack damage int attackerAttack = CalculateDamage(attacker.Attack, target.Defense); int targetAttack = CalculateDamage(target.Attack, attacker.Defense); // Player attacks the monster and damages it target.Damage(attackerAttack); MessageAttack(attacker, target, attackerAttack); // The target could be dead, check to make sure. If it is then return to prevent it from attacking if (target.Dead) { MessageDead(target.Name); return; } // The monster attacks the player attacker.Damage(targetAttack); MessageAttack(target, attacker, targetAttack); } /* Defense option from the menu - player defends and target attacks */ static void DoDefense(Entity attacker, Entity target) { // Save a copy of the attack and defense before changing it temporarily int attack = attacker.Attack; int defense = attacker.Defense; // When defending, the defense is 5 times as high and attack is lowered to 0 to prevent player from doing damage attacker.Attack = 0; attacker.Defense *= 5; // Message Console.WriteLine("{0} temporarily increases defense to {1} and decreases attack to 0.", attacker.Name, attacker.Defense); // Start attack sequence DoAttack(attacker, target); // Restore original attack and defense attacker.Attack = attack; attacker.Defense = defense; } } } Item.cs using System; using System.Text; using Game.Program; namespace Game.Classes { /* * The basic item class. * All items must derive from this class and implement an override function for Use() */ abstract class Item { public const int MAX_AMOUNT = 9999; private string name; private string description; private int amount; private int cost; // Creates a new item with preset values public Item(string name, string description, int amount, int cost) { Name = name; Description = description; Amount = amount; Cost = cost; } // Uses public abstract void Use(Entity entity); /* -- Properties -- */ public string Name { get { return name; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentNullException("Value cannot be null in property Item.Name"); name = value; } } public string Description { get { return description; } set { description = value; } } public int Amount { get { return amount; } set { amount = Program.Program.Clamp(value, 0, MAX_AMOUNT); } } public int Cost { get { return cost; } set { cost = Program.Program.Clamp(value); } } /* -- Properties -- */ } } Weapon.cs using System; using System.Text; using Game.Program; namespace Game.Classes { class Weapon : Item { private int attack; public Weapon(string name, int cost, int attack) : base(name, name + " with attack rate of " + attack.ToString(), 1, cost) { Attack = attack; } public override void Use(Entity user) { // Not exactly sure what to do with this for now... } /* -- Properties -- */ public int Attack { get { return attack; } set { attack = Program.Program.Clamp(value); } } /* -- Properties -- */ } } Armor.cs using System; using System.Text; using Game.Program; namespace Game.Classes { class Armor : Item { private int defense; public Armor(string name, int cost, int defense) : base(name, name + " with defense rate of " + defense.ToString(), 1, cost) { Defense = defense; } public override void Use(Entity user) { // Not exactly sure what to do with this for now... } /* -- Properties -- */ public int Defense { get { return defense; } set { defense = Program.Program.Clamp(value); } } /* -- Properties -- */ } } Potion.cs using System; using System.Text; using Game.Program; namespace Game.Classes { class Potion : Item { private int healthRecover; private int manaRecover; public Potion(string name, int cost, int amount, int healthRecover, int manaRecover) : base(name, "Recovers " + healthRecover.ToString() + " HP and " + manaRecover.ToString() + " MP", amount, cost) { HealthRecover = healthRecover; ManaRecover = manaRecover; } // Call potion.Use( public override void Use(Entity user) { // Do not use if there is none left if (Amount == 0) return; user.Heal(HealthRecover); Amount--; Console.WriteLine("{0} drank the {1} and recovered {2} HP", user.Name, Name, HealthRecover); } /* -- Properties -- */ public int HealthRecover { get { return healthRecover; } set { healthRecover = Program.Program.Clamp(value); } } public int ManaRecover { get { return manaRecover; } set { manaRecover = Program.Program.Clamp(value); } } /* -- Properties -- */ } } Entity.cs using System; using System.Text; using Game.Program; namespace Game.Classes { /* * The entity class represents a character. * Eg: Players, monsters, etc. */ class Entity { public const int MAX_LEVELS = 120; private string name; private int level; private int health, maxHealth; private int mana, maxMana; private int attack, defense; private bool poisoned, stunned; private Weapon weapon = new Weapon("Brass Dagger", 50, 60); private Armor armor = new Armor("Brass Set", 150, 45); /* Creates an entity with preset values */ public Entity(string name, int level, int health, int attack, int defense) { Name = name; Level = level; MaxHealth = health; Health = health; Attack = attack; Defense = defense; } /* Increases health */ public void Heal(int heal) { Health += Program.Program.Clamp(heal, 0, Int32.MaxValue); } /* Decreases health */ public void Damage(int damage) { Health -= Program.Program.Clamp(damage, 0, Int32.MaxValue); } /* -- Properties -- */ public string Name { get { return name; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentNullException("Value cannot be null in property Entity.Name"); name = value; } } public int Level { get { return level; } set { level = Program.Program.Clamp(value, 1, MAX_LEVELS); } } public int Health { get { return health; } set { health = Program.Program.Clamp(value, 0, maxHealth); } } public int MaxHealth { get { return maxHealth; } set { maxHealth = Program.Program.Clamp(value); } } public int Mana { get { return mana; } set { mana = Program.Program.Clamp(value, 0, maxMana); } } public int MaxMana { get { return maxMana; } set { maxMana = Program.Program.Clamp(value); } } public int Attack { get { return attack + weapon.Attack; } set { attack = Program.Program.Clamp(value); } } public int Defense { get { return defense + armor.Defense; } set { defense = Program.Program.Clamp(value); } } public bool Poisoned { get { return poisoned; } set { poisoned = value; } } public bool Stunned { get { return stunned; } set { stunned = value; } } public bool Dead { get { return health <= 0; } } public Weapon Weapon { get { return weapon; } set { if (!(value is Weapon) || value == null) throw new Exception("Value is not valid in property Entity.Weapon"); weapon = value; } } public Armor Armor { get { return armor; } set { if (!(value is Armor) || value == null) throw new Exception("Value is not valid in property Entity.Armor"); armor = value; } } /* -- Properties -- */ } }
  15. *** Update to the project. I took some advice and changed things a little and also expanded on what I created yesterday. *** Program.cs using System; using System.Text; namespace Battle { partial class Program { static Random random = new Random(); static void Main(string[] args) { Entity player = new Entity("Ntvu", 120, 80000, 15020, 800); Entity monster = new Entity("Dog", 120, 150000, 3250, 1500); while (!GameOver(player, monster)) { ActivateAilments(player, monster); MessageStatus(player, monster); MessageMenu(player, monster); } if (player.Dead) Console.WriteLine("Unfortunately you have been slaughtered. But feel free to try again!"); else Console.WriteLine("Congratulations! You have defeated your enemies and won the game!"); Console.ReadLine(); } } } Battle.cs using System; using System.Text; namespace Battle { partial class Program { static int CalculateDamage(int attack, int defense) { // Damage = (attack * 2) + (extra damage of 0 to 1/3 the attack) - (defense) return Entity.Clamp(attack * 2 + random.Next(0, attack / 3) - defense, 0, Int32.MaxValue); } static bool GameOver(Entity player, params Entity[] monsters) { // If the player died then it's an immediate game over if (player.Dead) return true; int deadMonsters = 0; foreach (Entity monster in monsters) { if (monster.Dead) deadMonsters++; } // If all monsters are killed, then it's also game over if (deadMonsters == monsters.Length) { return true; } return false; } static void ActivateAilments(params Entity[] entityList) { foreach (Entity entity in entityList) { int damage = 0; if (entity.Poisoned) { // Damage of poison = 1/10 of health damage = entity.Health / 10; entity.Damage(damage); Console.WriteLine("{0} took {1} damage from poison.", entity.Name, damage); } if (entity.Stunned) { // Damage of stun = 1/2 to 1/50 of health damage = entity.Health / random.Next(2, 50); entity.Damage(damage); Console.WriteLine("{0} took {1} damage from stun.", entity.Name, damage); } if (damage > 0) { // Pause to alert player that a target has been damaged Pause(); } } } static void DoAttack(Entity attacker, Entity target) { int attackerAttack = CalculateDamage(attacker.Attack, target.Defense); int targetAttack = CalculateDamage(target.Attack, attacker.Defense); target.Damage(attackerAttack); MessageAttack(attacker, target, attackerAttack); // The target could be dead, check to make sure. If it is then stop the battle. if (target.Dead) { MessageDead(target.Name); return; } attacker.Damage(targetAttack); MessageAttack(target, attacker, targetAttack); } static void DoDefense(Entity attacker, Entity target) { int attack = attacker.Attack; int defense = attacker.Defense; attacker.Attack = 0; attacker.Defense *= 5; Console.WriteLine("{0} temporarily increases defense to {1} and decreases attack to 0.", attacker.Name, attacker.Defense); DoAttack(attacker, target); attacker.Attack = attack; attacker.Defense = defense; } } } Utils.cs using System; using System.Text; namespace Battle { partial class Program { static void Break() { Console.Write("\n\n"); } static void Pause() { Console.WriteLine(); Console.WriteLine("Press enter to continue"); Console.ReadLine(); Break(); } static int MenuInput() { int choice = 0; Console.Write("> "); try { choice = Int32.Parse(Console.ReadLine()); } catch { choice = 0; } return choice; } static int Menu(params string[] menuOptions) { int choice = 0; while (choice < 1 || choice > menuOptions.Length) { Break(); for (int menuIndex = 0; menuIndex < menuOptions.Length && menuOptions[menuIndex].Trim().Length > 0; menuIndex++) { Console.WriteLine("{0}: {1}", menuIndex + 1, menuOptions[menuIndex]); } choice = MenuInput(); } return choice; } static int TargetMenu(Entity[] targetList) { int choice = 0; while (choice < 1 || choice > targetList.Length) { Break(); foreach (Entity target in targetList) { if (target.Dead) continue; MessageStatus(target); } choice = MenuInput(); // Make sure that the target is not dead if (targetList[choice - 1].Dead) continue; } return choice; } } } Messages.cs using System; using System.Text; namespace Battle { partial class Program { static void MessageStatus(params Entity[] entityList) { foreach (Entity entity in entityList) { string ailments = ""; if (entity.Poisoned) { ailments += "Poisoned, "; } if (entity.Stunned) { ailments += "Stunned, "; } if (ailments.Length > 0) { ailments = ailments.Substring(0, ailments.Length - 2); } Console.WriteLine("{0} (Lvl {1}) [{2}] - {3}/{4}", entity.Name, entity.Level, ailments, entity.Health, entity.MaxHealth); } Break(); } static void MessageAttack(Entity attacker, Entity target, int attacker_damage) { Console.WriteLine("{0} hit {1} for {2}", attacker.Name, target.Name, attacker_damage); } static void MessageDead(string name) { Console.WriteLine("{0} was killed.", name); } static void MessageMenu(Entity player, params Entity[] monsters) { int choice = Menu("Attack", "Defend", "Skill", "Item", "Run"); Break(); switch (choice) { case 1: { int target = monsters.Length > 1 ? TargetMenu(monsters) : 0; DoAttack(player, monsters[target]); break; } case 2: { int target = monsters.Length > 1 ? TargetMenu(monsters) : 0; DoDefense(player, monsters[target]); break; } case 3: // display skill list break; case 4: // display item list break; case 5: Environment.Exit(0); break; } Pause(); } } } Entity.cs using System; using System.Text; namespace Battle { class Entity { private const int MAX_LEVELS = 120; private string name; private int level; private int health, maxHealth; private int mana, maxMana; private int attack, defense; private bool poisoned, stunned; public static int Clamp(int value, int min, int max) { if (value < min) { return min; } else if (value > max) { return max; } return value; } public Entity(string name, int level, int health, int attack, int defense) { Name = name; Level = level; MaxHealth = health; Health = health; Attack = attack; Defense = defense; } public void Heal(int heal) { Health += Clamp(heal, 0, Int32.MaxValue); } public void Damage(int damage) { Health -= Clamp(damage, 0, Int32.MaxValue); } public string Name { get { return name; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentNullException("Value cannot be null in property Entity.Name"); name = value; } } public int Level { get { return level; } set { level = Clamp(value, 1, MAX_LEVELS); } } public int Health { get { return health; } set { health = Clamp(value, 0, maxHealth); } } public int MaxHealth { get { return maxHealth; } set { maxHealth = Clamp(value, 0, Int32.MaxValue); } } public int Mana { get { return mana; } set { mana = Clamp(value, 0, maxMana); } } public int MaxMana { get { return maxMana; } set { maxMana = Clamp(value, 0, Int32.MaxValue); } } public int Attack { get { return attack; } set { attack = Clamp(value, 0, Int32.MaxValue); } } public int Defense { get { return defense; } set { defense = Clamp(value, 0, Int32.MaxValue); } } public bool Poisoned { get { return poisoned; } set { poisoned = value; } } public bool Stunned { get { return stunned; } set { stunned = value; } } public bool Dead { get { return health <= 0; } } } } I was thinking about making a Battle class to handle battles (if I choose to do this I will rename the namespace to something else). Do you think this would be a good idea? I was thinking I could have methods inside class Battle such as: PreCycle - Handles things that occur before actions can be made (such as ailment effects like poison, stun, and other messages) MainCycle - Handles the actual battle. In this stage the player chooses an option, chooses a target if he's attacking and attacks the monster. Monster attacks back after he attacks. PostCycle - For things that happen after the player and all monsters have attacked. And of course all these methods will be private as they'll be handled by the main loop. My idea was something like this: // Battle.cs class Battle { Entity player = null; Entity[] monsters; Random random = new Random(); ... public void Start(Entity p, params[] Entity m) { player = p; monsters = new Entity[m.Length]; for (int c = 0; c < m.Length; c++) { monsters[c] = m; } } public bool Loop() { if (GameOver()) // GameOver is a private function return false; PreCycle(); MainCycle(); PostCycle(); return true; } } // Program.cs class Program { ... static void Main() { Entity player = ... Entity monster1 = ... Entity monster2 = ... Battle battle = new Battle(); battle.Start(player, monster1, monster2); while (battle.Loop()); Console.ReadLine(); } }
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!