Colorado State University Logo | CS 163/4: Java Programming (CS 1) Colorado State University Logo | CS 163/4: Java Programming (CS 1)
CS 163/4: Java Programming (CS 1)
Computer Science

Practical One - Knight Fight

Introduction

Welcome to your first practical. Practical assignments are longer assignments, and you have roughly two weeks to complete the assignment during a 16 week session (1 week for 8 week class sessions). Looking in canvas you will find all practicals have three parts. One part is in zybooks that involves coding. For the coding section, you will be working with provided code, and they will get harder are you progress. You will also see a quiz on about the code. This quiz helps you practice tracing unfamiliar code, a needed skill in industry. Lastly, you will have a reflection to fill out. All three make up your practical assignment grade.

Knight Fight
Student, you have been hired by Round Table Games. They are a startup company that believes text based games are going to make a comeback. However, the programmer they hired to prototype their latest game Knight Fight, quit mid-development, and you have been hired to pickup the slack. Once completed, you will have a very, very basic game to play.

What you will learn

  • System.out.print/println
  • String concatenation
  • String.format
  • if/else statements

Provided Code

You will find by clicking the drop down arrow next the name of the file in Zybooks, that this program has a lot of files. Most programs have as much code divided out between files as is reasonable, and this is no exception. In all the files, you will find extensive comments to help guide you on what each method does or is supposed to do, in the cases for methods you implement yourself.

Here is a quick summary of the files and what they do:

  • RtMain (Read only)
    Main launcher of the program. The only unique thing about this file is that if you pass in debug as a program argument, it will run tests and not the game.
  • RtMonster (Read only)
    The monster represents a creature with armor, power, damage, a name. It is read only, but provides a valuable blueprint for RtKnight.
  • RtCombatEngine (Read only)
    Handles combat calculations between monsters and knights.
  • RtController (Read only)
    Also common in development is having a ‘driver’ file that interacts with the view and the data. This is the main controller.
  • RtBarrak (Read only)
    Manages multiple knights, but the ‘active’ knight on the quest and knights not currently active.
  • RtTests
    Various tests that are only run when the commandline argument is debug. Great spot to add your own tests.
  • RtKnight
    A knight represents the character in the game. It is an information class that has health, armor, power, name, and helps track damage.
  • RtTarotDeck
    Knights can pull tarot style fortune cards. However, the tarot deck displays the knightly virtues instead of the traditional tarot.
  • RtView
    It is common for the part that interact with clients to be pulled into their own file or “view”. This file handles all input and output for the program.
  • RtDiceRoller (Read only)
    A simple class that keeps random numbers similar to dice (1d6, 1d4, 1d20, etc).

You will find that while there are a lot of files, the code is relatively minimal. That is because we are following the divide-conquer-glue design paradigm, so we seek to have many small methods doing our work for us. You will also sometimes your first role on a job, is diving into the code base to learn the application. As such, the next part of this assignment is in canvas. If you haven’t already, you should go take the code tracing quiz for practical one!

Step 0

Now that you have taken the canvas quiz, you should make sure the current code you have compiles. Go down to the interactive terminal, and type run plus return. This will start running your game, which admittedly, may not work as intended other than bringing up the initial prompt. You can type exit to end the game (and should).

Run Tests

The game is setup, so that if you run the program in “debug” mode, it will just run the tests defined in RtTests. This is common to do, and help you work on aspects of the game without having to launch the entire game every time. You should try running it in debug mode now by typing run debug in the interactive terminal in zybooks. The screenshot shows an example.

Step 1 - RtKnight Mutators and Accessors

In RtKnight, you will see a number of mutator methods and accessor methods - also called setters and getters. These methods all have a default value in them or nothing - which is incorrect. The reason for the default values is so the code could compile, and often call method “stubbing” or creating a method stub. Your first coding assignment is to complete the accessors and mutator methods. The names match with the variable, and feel free to look in RtMonster for similar examples. The mutator and accessor methods to complete are

  • getXp()
  • setXp(int xp)
  • getName()
  • setName(String name)
  • getMaxHealth() (notice, there is no setter version, that is intentional)
  • getPower()
  • setPower(int power)
  • getArmor()
  • setArmor(int armor)

Testing

It is recommended you run the program after every method (essentially every line of code)! You run it using run debug. As you do that, you will start seeing the test methods changing in value, and you can even add your own tests. While it may seem like a lot running after every method, it helps a lot if you forget something simple, like a semi-colon.

Step 2 - Writing Damage Modifiers

The damage modifiers for the RtKnight are a bit more specific. For this step, you are going to implement the bodies of the following:

  • getRemainingHealth()
    Going back to the canvas quiz, what two variables did you use to calculate getRemainingHealth? You took the maxHealth - the damage (which is stored as damage).
  • addDamage(int amount)
    addDamage it pretty straight forward, it takes the damage, adds the amount to the damage variable, and that is it.
  • reset()
    reset sets the damage to 0.

Testing

Remember to test after every method. You may also want to add your own tests into RtTests.

Step 3 - Writing getCard()

The getCard() method is the hardest method in the RtKnight class. What it does is build a String that represents the Knight. The format of the card is as follows:

+============================+
| [name]                     |
|                            |
| Health: [val1]  XP: [v3]   |
|  Power: [val2]  Armor: [v4]|
|                            |
+============================+

Based on the lines in order above:

  1. There are 28 = characters, and two + characters, making it 30 characters wide
  2. Given name starts in position 2, that means there are 27 characters for <name> (right-padded).
  3. Just spaces with the bars, no special padding.
  4. Notice that health and power line up with the : and a space after. This is fixed.
  5. Health and power are 6 right-padded.
  6. XP has one space after the : and then is 7 right-padded
  7. Armor has one space after the : and is 4 right-padded
  8. Don’t forget to add your new line characters \n for standard Strings or %n if using String.format()
  
Examples: 

+============================+
| Pendragon                  |
|                            |
| Health: 100     XP: 0      |
|  Power: 100     Armor: 100 |
|                            |
+============================+

+============================+
| Morgana                    |
|                            |
| Health: 150     XP: 0      |
|  Power: 150     Armor: 50  |
|                            |
+============================+

As a reminder, to right-pad a String using String.format, the syntax uses the minus sign to say padding is to the right of the passed in String.

1
String value = String.format("%-20s%n", "Doctor"); // returns "Doctor              \n"  

Testing

You have tests setup in RtTests, but the only test one card. You may want to create additional cards, and print them out with various ranges of names. You don’t have to worry about the numbers being larger than the padding numbers we defined above.

We also recommend you spend one of your “submit for grading” options right now. Don’t burn through them! Maybe use 2 at the most, and come back later. Simply make sure your spacing is correct, as that is hard to tell just from looking at it. If it isn’t, you will want to go in and carefully count spaces. It is also common for people to use the ‘tab’ character instead of spaces, which is not the same (and very hard to see the difference).

We do not suggest doing more than two submits this moment. You will have more time to fix later, but at least you know there is an issue now.

Running the game

Once you have done that, you actually have a mostly finished game. You should go ahead and run the game. At the prompt, type ls to list the knights. You can then select a knight and see their card, and even set it to active. You could also pit the knight in combat against a monster - but the dice roles will not show up (part of the TODO). You will also notice the Knight’s Fortunes are not working, and that is your next step.

No System.out.printlns?
You will notice that none of the classes have Systems.out.print/println except for RtTests and RtView. This is intentional, and common practice. Methods rarely print directly! Instead, they pass messages of information to other methods and user interfacing (UI/UX) happens in a specific layer of your program. In this case, RtView. It could be in the future, we change RtView to interact with a webpage, making the game a web-based game. UI/UX design is an emphasis of Human-Centered Computing, where as full-stack development is more Software Engineering and focuses on figuring the entire design.

Step 4 - Moving onto RtTarotDeck

The RtTarotDeck class takes in numbers, returns a simple String representing the card. As with most tarot decks, there are four suits (the foundation for modern playing cards). The four suits are:

  • Cups
  • Wands
  • Coins
  • Swords

If you look at getTarotCard(int, int), you will see some statements that direct which method is called and which suit is requested. Basically, 1-4 matches the suits in order above, and then anything else requests a major arcana card - which are specially named virtues, discussed below.

Here is a reminder on if/else statements, and an example of if-else if-else from w3schools.

You will want to review that now, before moving on to coding.

Step 5 - RtTarotDeck: minorArcana(String deck, int card)

For the minorArcana(String deck, int value), you deck name is provided, and based on the value that is passed in as a parameter. The range of values is as follows:

  • <= 2 - Ace
  • 3,4 - Two
  • 5,6 - Three
  • 7,8 - Four
  • 9,10 - Five
  • 11,12 - Six
  • 13,14 - Seven
  • 15,16 - Eight
  • 17,18 - Nine
  • 19,20 - Ten
  • 21,22 - Page
  • 23,24,25,26 - Knight
  • 27,28 - Queen
  • 29,30 - King
  • `>= 30 is a blank card, as there is no default case

While you could do this with thirty different == comparisons, we found it much easier to to use ``<=`. For example:

1
2
3
4
5
if(value <= 2) {
  cardName = "Ace";
} else if(value <= 4) {  
  cardName = "Two";
}//and so on

Testing

To test this method, run your program in debug mode - run debug. The first four tests line up with this method, but you may want to add your own testing odd ranges (putting a 0 in for example).

Suggestion
You should test after every couple if statements! While they won’t all work right away, it is much easier to trace errors like missing curly brackets if you are only looking at a couple lines of code.

Step 6 - RtTarotDeck: majorArcana(int value)

The major arcana in a tarot deck are “named” cards. In our case, we did not use the traditional names, but instead a modern variation of Knightly Virtues often referenced in documents of Chivalry.

While the cards don’t do much in the game at this time, it is the vision of Round Table Games to have these cards provide different types of benefits to the knight based on the random draw. This method will be series of if-elseif-else statements, similar to the last method. Repetition will help you solidify the syntax structure. The ranges are as follows:

  • 1, 2 - Prowess
  • 3 - Valor
  • 4 - Excellence
  • 5,6,7 - Justice
  • 8 - Temperance
  • 9 - Loyalty
  • 10 - Obedience
  • 11 - Faithfulness
  • 12 - Defense
  • 13 - Selflessness
  • 14 - Sacrifice
  • 15 - Courage
  • 16 - Integrity
  • 17 - Honesty
  • 18 - Faith
  • 19 - Perseverance
  • 20,21 - Wisdom
  • 22 - Humility
  • 23 - Morality
  • 24 - Largesse
  • 25 - Generosity
  • 26 - Kindness
  • 27 - Nobility
  • 28 - Charity
  • 29 - Franchise
  • 30 - Accountability

If a number is out of the range (less than 1, or greater and 30), than the card is “King”, as for arthurian legends the king is so rare, it isn’t even in range for the fortune. Because of the inclusive range, you will want to think through your logic on the first if statement.

Testing

To test this method, run your program in debug mode - run debug. The last three RtTarotDeck tests line up with this method, but you may want to add your own testing odd ranges (putting a 0 in for example).

Suggestion
You should test/run after every couple if statements! While they won’t all work right away, it is much easier to trace errors like missing curly brackets if you are only looking at a couple lines of code.

At this point, you should be able to run the game, and select random fortune cards. Try that now by just typing in run without the debug argument!

Step 7 - Moving onto RtView

Take a moment to look through your View file. You will notice this is the only file that references System.in and the only file (outside of tests) that uses System.out.println. In fact the method, that uses System.out.print is the display(String str) method.

Let’s take a look at the exitGame

1
2
3
4
public void exitGame() {
   display("Thank you for playing!\n");
   scanner.close();// leave here
}

Even in this method, in order to call the System.out.print, we call the display method passing in the String. You will want to keep that in mind, for the next method.

User Interface Design
The RtView class is the heart of your user interface, along ith the RtController acting as an interface to the rest of the program. We will explore this MVC design more in the future (take CS 312!), but for now, go here to learn about user interfaces.

Step 8 - RtView: displayRoll(String name, int roll)

The displayRoll method takes two parameters. The name of the person (knight or monster) rolling, and their dice roll - which is between 1 and 6 for now. What we would like to display is a typical looking six sided dice side with dots. Most notably, if 1 is passed into the roll parameter, then the method will display to the console:

+---------+ 
|         |
|    *    |
|         |
+---------+

However, remember divide-conquer-glue. It would be a pain to write all that in a single method, so we have what displayRoll() really does is have an if-else-if-else statement that checks the roll, calls the corresponding method, and prints out the results. For example:

1
2
3
if(roll == 1) {
  display(diceOne());
}else ...

Take a moment to think about line 2 above, and what diceOne() must be returning if display requires a String to work. Draw it out on paper if you need to visual the method calls.

You will implement all the if/else statements with 1 calling diceOne(), 2 calling diceTwo() and so on until 6 calling diceSix(). For this assignment, you can assume the range is between 1-6.

Testing

Go ahead and run in debug mode again (run debug). It should print out both diceOne and diceTwo if you did it properly. It will also be printing out the other device, but right now, those methods return null, so it will print null in place of the dice.

Step 9 - RtView: Dice Methods

For this next step, you will work on spacing on building Strings to return from each method (you will not print!). The dice all look like the following:

+---------+   +---------+   +---------+   +---------+   +---------+   +---------+
|         |   |    *    |   |    *    |   |  *   *  |   |  *   *  |   |  *   *  |
|    *    |   |         |   |    *    |   |         |   |    *    |   |  *   *  |
|         |   |    *    |   |    *    |   |  *   *  |   |  *   *  |   |  *   *  |
+---------+   +---------+   +---------+   +---------+   +---------+   +---------+

Following the idea that you are building Strings, implement diceThree(), diceFour(), diceFive(), and diceSix() to return the matching String. Don’t forget your \n characters. For reference, there are nine dashes - making the dice 11 wide by 5. This is a great spot to just use String concatenation (addition).

For advanced programmers, you could also build a couple helper methods, as there is a pattern in the lines | * * | and | * | can help you build any dice pattern. This will not affect your grade adding the additional methods, and it is not required. However, building the two additional methods will help your code be DRY, and maybe even help with debugging.

Testing

To test the different dice, run in debug mode again. We have a test for every dice. You should also run the game at this point, as most things will be working except for the splash screen.

Step 10 - RtView: splash()

You get to have fun with this method. Simply write a splash screen. You can use all the printing tools in your disposal.

Some examples of splash screens:

 ======== WELCOME ======
 =  Round Table Games  =
 =     Introduces      =
 =                     =
 =     Knight Fight    =
 = Quest for the Grail =
 =                     =
 =======================
 
 or fancier
 
 
 Knight Fight: Grail Quest
       _,.
     ,` -.)
    ( _/-\\-._
   /,|`--._,-^|            ,
   \_| |`-._/||          ,'|
     |  `-, / |         /  /
     |     || |        /  /
      `r-._||/   __   /  /
  __,-<_     )`-/  `./  /
 '  \   `---'   \   /  /
     |           |./  /
     /           //  /
 \_/' \         |/  /
  |    |   _,^-'/  /
  \    , ``  (\/  /_
   (  /   `-._/x/^`
    `Y-.____(__}
     |     {__)
           ()
        by
  Round Table Games          

ASCII art source.

All that we ask is that you copy and past your ASCII into your reflection for the assignment. The way you do that is select “pre-formatted” in the canvas formatting options, and then paste it in. We hope you have fun with the method, and take time to draw something fun. Btw, you have all been doing ascii art for years through emotes!

Turning in: Submit Code and Reflection

At this point, you should submit your code for grading in zybooks, and then click the orange button to submit to canvas. Naturally, you will have some parts you need to debug, but remember, if you aren’t struggling you aren’t learning. Also, if you have been testing after every step, your debug should be minimal. This is essential to being a successful programmer. This assignment is about precision, and learning basic syntax. If the orange submit to canvas button is grayed out, go into canvas, and click the link to the assignment from there. It should allow you to submit then.

After you have submitted your code to zybooks. You should complete the reflection. Please paste your ASCII art, we want to see it!

Computer Science Department

279 Computer Science Building
1100 Centre Avenue
Fort Collins, CO 80523
Phone: (970) 491-5792
Fax: (970) 491-2466

CS 163/4: Java Programming (CS 1)

Computer Programming in Java: Topics include variables, assignment, expressions, operators, booleans, conditionals, characters and strings, control loops, arrays, objects and classes, file input/output, interfaces, recursion, inheritance, and sorting.