I 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) { } }
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
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.
I’m glad you figured it out. Sorry, I couldn’t get you an answer quick enough. I’m glad you are enjoying the videos π
Love the your tutorials! Is there a single file with the source code I could download?
Thanks
MB
I have all of the code attached to each individual part of the Java tutorial series. You can find every part of it on one page here Java Video Tutorial. I hope that helps
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?
I show how to get that library here How to install java libraries
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;
this is answered in tutorial 9.thanks and great tutorials really enjoying them
Thank you very much π You’re very welcome
There is no such thing as a stupid question. I created a multidimensional array named battleBoard. To get the length or size of the second part of the array I have to follow battleBoard with [0]. Does that make more sense?
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
Sorry about that. The return type should be boolean. I corrected the code. I don’t know how I missed that
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!
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 :/
Got it figured out. I was doing println() instead of print() in the while loop while(k <= 30){ System.out.print('-'); k++; }
Woopsies daisies!!
I’m glad you got it fixed. Sorry I couldn’t help quicker
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
MonsterTwo[] Monsters creates an array of MonsterTwo objects. It is named Monsters. Does that help?
Thanks, it helps π
You’re very welcome π
I didn’t quite get it. The MonsterTwo class is not defined as an array. How is that you are able to directly create a array of it?
It is an array filled with MonsterTwo objects. Feel free to skip parts 8 and 10 of this tutorial series. I was experimenting with an idea, but I don’t like how it came out. I’m very happy with the rest of the tutorial though.
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!!!
Thank you very much for the kind words π I’m very happy that you are enjoying the videos
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.
Hi,
I’m glad you’re enjoying the videos π
You normally get that error if you don’t save your file in the src folder. I made a tutorial to help with many of the other common Eclipse errors that may help called Install Eclipse for Java. I hope that helps
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();
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
int maxXBoardSpace = battleBoard.length – 1;
int maxYBoardSpace = battleBoard[0].length – 1;
can u explian the second line
char[][] tempBattleBoard = new char[10][10];
what is the use of above array?
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.
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.. π
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.
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.
I show how to install java libraries here. I hope it helps
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?
Hello, I’m very happy that you like the videos π
That is an Eclipse error that occurs for complex reasons. Take a look at my tutorial on how to install Eclipse for Java. It will sort that out.
please i am using netbeans 8.0 and it does not recognize “org.apache.commons.lang3.ArrayUtils;” How do i install it on Netbeans?
1. Download the commons-lang-2.5-bin.zip
2. Extract it, and find the commons-lang-2.5.jar
3. Add that jar to the classpath of your project by:
4. right click your project > Properties > Libraries > Add Jar/Folder
Source : http://stackoverflow.com/questions/3692559/using-apache-systemutils-java
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?
Thank you π Yes you are correct. Sorry about any confusion that caused.
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?
Eclipse doesn’t like Java 8. I don’t use it. Stick with 7
Hi Derek,
As always….great tutorial!!! I have a question….why did you make the buildBattleBoard() and redrawBoard() methods static?
Thanks
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.