Java Video Tutorial 8

Java Video Tutorial 8I thought it would be fun to teach Java while I make a video game. This is a simple game, but it will teach a lot of the logic needed to make your own game.

This tutorial will teach you about arrays, class fields, class methods, how to set a default value for an array, and a ton of logic.

I hope you like it. If you missed the previous parts though you should check them out first here Java Video Tutorial.

I reference an article on how to install java libraries, in the video below. You can also find all of the code after the video.

If you like videos like this share it

LessonEight.java

import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;

// Basic class definition
// public means this class can be used by other classes
// Class names should begin with a capital letter
// A file can't contain two public classes. It can contain classes that are not public
// If you place class files in the same folder the java compiler will be able to find them

/* The Goal of this tutorial is to make a game like this
------------------------------
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||M||F||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|P||*||*||*||*||*||*||*||*||*|
|*||*||*||*||D||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
------------------------------
[9,9]

 */

public class LessonEight {
	
	public static void main(String[] args)
	{
		
		MonsterTwo.buildBattleBoard();
		
		char[][] tempBattleBoard = new char[10][10];
		
		// ObjectName[] ArrayName = new ObjectName[4];
		
		MonsterTwo[] Monsters = new MonsterTwo[4];
		
		// MonsterTwo(int health, int attack, int movement, String name)
		
		Monsters[0] = new MonsterTwo(1000, 20, 1, "Frank");
		Monsters[1] = new MonsterTwo(500, 40, 2, "Drac");
		Monsters[2] = new MonsterTwo(1000, 20, 1, "Paul");
		Monsters[3] = new MonsterTwo(1000, 20, 1, "George");
		
		MonsterTwo.redrawBoard();
		
	}
	
	
}

MonsterTwo.java

import java.util.Arrays;

// Basic class definition
// public means this class can be used by other classes
// Class names should begin with a capital letter
// A file can't contain two public classes. It can contain classes that are not public
// If you place class files in the same folder the java compiler will be able to find them

public class MonsterTwo{
	
	static char[][] battleBoard = new char[10][10];
	
	public static void buildBattleBoard(){
		
		for(char[] row : battleBoard)
		{
			
			Arrays.fill(row, '*');
			
		}
		
	}
	
	public static void redrawBoard()
	{
		
		int k = 1;
		while(k <= 30){ System.out.print('-'); k++; }
		System.out.println();
		
		for (int i = 0; i < battleBoard.length; i++)
		{
			
			for(int j = 0; j < battleBoard[i].length; j++)
			{
				
				System.out.print("|" + battleBoard[i][j] + "|");
				
			}
			System.out.println();
			
		}
		k = 1;
		while(k <= 30){ System.out.print('-'); k++; }
		System.out.println();
		
		
	}
	
	// Class Variables or Fields
	// You declare constants with final
	
	public final String TOMBSTONE = "Here Lies a Dead monster";
	
	// private fields are not visible outside of the class
	private int health = 500;
	private int attack = 20;
	private int movement = 2;
	
	private boolean alive = true;
	
	// public variables are visible outside of the class
	// You should have as few as possible public fields
	public String name = "Big Monster";
	public char nameChar1 = 'B';
	public int xPosition = 0;
	public int yPosition = 0;
	public static int numOfMonsters = 0;
	
	// Class Methods
	// Accessor Methods are used to get and set the values of private fields
	
	public int getAttack()
	{
		return attack;
	}
	
	public int getMovement()
	{
		return movement;
	}
	
	public int getHealth()
	{
		return health;
	}
	
	public boolean getAlive()
	{
		return alive;
	}
	
	// You can create multiple versions using the same method name
	// Now setHealth can except an attack that contains decimals
	// When overloading a method you can't just change the return type
	// Focus on creating methods that except different parameters
	
	public void setHealth(int decreaseHealth)
	{
		health = health - decreaseHealth;
		if (health < 0)
		{
			alive = false;
		}
	}
	
	public void setHealth(double decreaseHealth)
	{
		int intDecreaseHealth = (int) decreaseHealth;
		health = health - intDecreaseHealth;
		if (health < 0)
		{
			alive = false;
		}
	}
	
	/* The Constructor
	 * Code that is executed when an object is created from this class definition
	 * The method name is the same as the class
	 * The constructor is only executed once per object
	 * The constructor can't return a value
	 */
	
	public MonsterTwo(int health, int attack, int movement, String name)
	{
		this.health = health;
		this.attack = attack;
		this.movement = movement;
		this.name = name;
		/* If the attributes had the same names as the class health, attack, movement
		 * You could refer to the objects fields by proceeding them with this
		 * this.health = health;
		 * this.attack = attack;
		 * objectFieldName = attributeFieldName;
		 */
		
		int maxXBoardSpace = battleBoard.length - 1;
		int maxYBoardSpace = battleBoard[0].length - 1;
		
		int randNumX, randNumY;
		
		do {
			
			randNumX = (int) (Math.random() * maxXBoardSpace);
			randNumY = (int) (Math.random() * maxYBoardSpace);
			
		} while(battleBoard[randNumX][randNumY] != '*');
		
		this.xPosition = randNumX;
		this.yPosition = randNumY;
		
		this.nameChar1 = name.charAt(0);
		
		battleBoard[this.yPosition][this.xPosition] = this.nameChar1;
		
		numOfMonsters++;
		
	}
	
	// You can overload constructors like any other method
	// The following constructor is the one provided by default if you don't create any other constructors
	// Default Constructor
	
	public MonsterTwo()
	{
		numOfMonsters++;
	}
	
public static void main(String[] args)
{
	
	
}
	
}

46 Responses to “Java Video Tutorial 8”

  1. Sheron says:

    First of all thanks alot for the awesome tutorial, probably the best one and you have my support. i completed upto this tutorial. i done exactly all the steps and i am getting the same output as of 20:45 but all the “-” and “|*|” are in next lines so i am not getting the same pattern.
    Thanks
    Sheron

    • Sheron says:

      I figure it out what was the mistake… i put println in the following two places.
      System.out.print(“|” + battleBoard[i][j] + “|”);
      while(k <= 30){ System.out.print('-'); k++; }

      Thank you very much.. keep up your good work.

  2. MB says:

    Love the your tutorials! Is there a single file with the source code I could download?

    Thanks

    MB

  3. adhie says:

    I got an error that says :
    LessonEight.java:2: error: package org.apache.common.lang3 does not exist
    import org.apache.common.lang3.ArrayUtils;

    I use geany as my editor. Do I have to use eclipse or netbeans instead?

  4. maurice o connell says:

    sorry this might seem like a stupid question, but i was just wondering
    why do you do this
    int maxYBoardSpace = battleBoard[0].length – 1; // i’m talking about the[0], i don’t see it’s function

    for the x case you didn’t include it
    int maxXBoardSpace = battleBoard.length – 1;

  5. Dave says:

    Hi Derek, I copied and pasted your script into netbeans, removed all the line numbers and am left with 1 issue. At line 98

    return alive;

    from

    public int getAlive()
    {
    return alive;
    }

    The error being flagged up is required int found boolean

    I know private boolean alive = true; is declaring a boolean and do not quite understand how it is making an int out of alive as that is the boolean. Could you advise please. Thanks

  6. Pat says:

    1. In the LessonEight class I commented out the import org.apache.commons.lang3.ArrayUtils line because I don’t have it but the program runs fine without it. Have you actually used any of these utils yet? If so where? I’m not using an IDE just a text editor and a command line Window.

    2. If one does use such a set of utils will the compiled program run in a standard environment ( without the apche stuff)?

    3. Why does MonsterTwo class have a main function?

    I like your videos but it takes time to fully digest some of them. Thanks!

  7. Tom says:

    It seems that you have your first constructor,

    public MonsterTwo(int health, int attack, int movement, String name)

    commented out. Is that a mistake?

    Does everything from this.health = health; TO numOfMonsters++; fit under the first connstructor?

    Reason I’m asking, is that I cannot for the life of me figure out why the grid is not printing properly. My grid keeps printing one long vertical of – then |*| with the |G| then the – again. I looked very carefully to compare your nested for loop to mine, but they both match exactly. hmmmmmrrrmmm :/

  8. Tom says:

    Got it figured out. I was doing println() instead of print() in the while loop while(k <= 30){ System.out.print('-'); k++; }

    Woopsies daisies!!

  9. Mohit says:

    Hello Derek,

    I would like to know how you used the object Monster in main method without creating it or can we use classes directly in place of objects?

    Regards,
    Mohit

  10. Todd says:

    Congrats you have now replaced the kind lady from India (Prop. Calc. videos) as my favorite internet personality. Just playing around with your code a bit, and I added the ability when using the default constructor MonsterTwo() to display the first letter of the name on the board. As is (at least in the video) this don’t be a happening. But a little of “The joy of Cut and Paste,” and BAM!! Show me the ‘B’ πŸ™‚ Anyway thank you for the time and effort. I have been using my old textbook for a review, and as a guide in my plan to help my brother (he has 1301 in fall), and this is 10^(you pick) times better! I plan on watching all your videos over the next 90 days…It’s Java Boot Camp!!! …An array of objects? Who wouldn’t get fired up!!!

  11. Larry says:

    Hi Derek,
    Thanks for your help ! Enjoying a lot.
    Trying to compilate and run this one, and the Eclipse tells me:
    ‘Selection does not contain a main type’
    Sorry, I am a new.

  12. jaideep says:

    in the file lessonEight.java , you have defined a class lessonEight and you written a code ” MonsterTwo.buildBattleBoard();

    where MonsterTwo is a object according to you. but how can the object have the same name as of its class. i mean to we should have defined an object like
    MonsterTwo xyz = new Monstertwo();
    and then called the function
    xyz.buildBattleBoard();

    • Derek Banas says:

      You could definitely do it both ways. I considered parts 8 and 10 of this series to be bad. Feel free to skip them. The rest are good though. I was experimenting to much in these 2 videos

  13. srikanth says:

    int maxXBoardSpace = battleBoard.length – 1;
    int maxYBoardSpace = battleBoard[0].length – 1;

    can u explian the second line

  14. srikanth says:

    char[][] tempBattleBoard = new char[10][10];

    what is the use of above array?

    • Derek Banas says:

      To represent the game board. Feel free to skip parts 8 and 10 of this tutorial series. I think I pushed this idea to soon. I reexamine logic in programming later in the tutorial.

  15. Samrat says:

    I am having difficulty in understand how MonsterTwo.buildBattleboard(); works.
    To my understanding, MonsterTwo is the blueprint for new MonsterTwo objects to be created. Once new MonsterTwo objects are created, then we can perform different operations on the new object. But when we write MonsterTwo.buildBattleboard(); before creating a new object, where is the computer performing this action? There is no object to work with. I am a newbie and this may be a very silly question. But if you please take some time to explain a bit, it would be helpful. I hope my query is clear to you.. πŸ™‚

    • Derek Banas says:

      The best thing to do is to skip parts 8 and 10. I was trying to teach a topic that was to advanced using the limited amount of Java I had taught at that point. The rest of the tutorial is good though in my opinion. To improve I have to on occasion experiment with new ideas and parts 8 and 10 were failed experiments in my opinion.

  16. MrRager says:

    I’ve imported the apache lang3 files as you showed in your video but my Eclipse still doesn’t recognize them for some reason. At the top where you import libraries it says that the import org.apache cannot be resolved and when I try to run it anyways I get this message:

    Exception in thread “main” java.lang.Error: Unresolved compilation problem:

    at LessonEight.main(LessonEight.java:29)

    I’ve tried copying the commons-lang3-3.3.2.jar and commons-lan3.3.3.2.jar files (those are the ones I could find on their site, they should be the latest version) to the src folder. That didn’t help either.

  17. NyashaC says:

    Well hello Derek!
    I have been following your java tutorial series heretofore and everything has been going on well. I must say, you happen to be the best java tutor I have followed so far… way2go Derek!
    But it seems now I am having issues fixing this error I am getting after trying to run LessonEight.java. It says something funny like, “IOConsole Updater – An internal error has occurred.” When I click the ‘Details’ button I get “No more handles.” May you please help me troubleshoot this?

  18. Aeon says:

    please i am using netbeans 8.0 and it does not recognize “org.apache.commons.lang3.ArrayUtils;” How do i install it on Netbeans?

  19. Anonymous says:

    Great tutorials Derek, thanks so much. Just to be clear on the x and y positions, typically when we draw a graph, x is the horizontal axis and y is the vertical access but I guess when we’re dealing with the battleBoard here as constructed, x is analogous to i, which actually is the rows of the char[][] and Y is the columns. So in other words, on the battleBoard, x actually is the vertical axis and Y is the horizontal. correct?

  20. Ecalik says:

    Hi Derek.

    First off tnx a bunch for your excellent tutorials. I have a question regarding the difference between the JRE System Library versions. I tried running it with JavaSE-1.8 and it didn’t work, After some foolin around I tried changing the JRE System Libarary to version 1.6 and it miraculously worked! Any idea as to why it doesn’t work with 1.8?

  21. Yusuf says:

    Hi Derek,
    As always….great tutorial!!! I have a question….why did you make the buildBattleBoard() and redrawBoard() methods static?
    Thanks

    • Derek Banas says:

      Hi Yusuf, I did that because building the battle bored isn’t something a monster would be able to do. It is a utility method. Feel free to skip parts 8 and 10 of this tutorial series. I cover this information much better later in the tutorial.

Leave a Reply

Your email address will not be published.

Google+