180
Welcome to Kilobolt's Android game development tutorial series! I'm James, and I am so glad that you chose to begin this tutorial. The path to app/game development will be challenging and often frustrating, but it will be an extremely rewarding and satisfying process every step of the way. So my advice to you is this: persevere and don't feel like you are in this alone. We will try to answer all the questions you may have in our Forums , and there are thousands of other readers who would be happy to help. Thank you for reading, and I hope you have a wonderful journey. Lesson #1-0: What is Java? Java -- everyone's heard of it. But what is it really? I'm not going to delve too deeply into Java details, as all of that information IS available online and you are here for one thing: app/game development. All you need to know for now is that Java is both a programming language (that lets you communicate with computers) and a platform (that is driven by a virtual machine that interprets all of your code). Java was designed to be everywhere -- in phones, cars, computers, and any other object that is computerized. The developers promised that you would be able to write one program that will run on any device that runs the Java platform. This promise kind of fell short, as Java did not proliferate the world's electronics devices at the rate and the extent people expected; however, a few years ago, Android came along, and this open source platform began to do what Java could not. Android devices started making their ways into cars, desktops, tablets, phones, refrigerators, and more recently, Nexus Q's (update: cancelled). Who knows what else in the future?

Welcome to Kilobolt

Embed Size (px)

DESCRIPTION

bdhawdh

Citation preview

Welcome to Kilobolt'sAndroid game development tutorial series! I'm James, and I am so glad that you chose to begin this tutorial.

The path to app/game development will be challenging and often frustrating, but it will be an extremely rewarding and satisfying process every step of the way.

So my advice to you is this: persevere and don't feel like you are in this alone. We will try to answer all the questions you may have in ourForums, and there are thousands of other readers who would be happy to help.

Thank you for reading, and I hope you have a wonderful journey.

Lesson #1-0: What is Java?

Java -- everyone's heard of it. But what is it really?I'm not going to delve too deeply into Java details, as all of that information IS available online and you are here for one thing: app/game development.

All you need to know for now is that Java is both a programming language (that lets you communicate with computers) and a platform (that is driven by a virtual machine that interprets all of your code).

Java was designed to be everywhere -- in phones, cars, computers, and any other object that is computerized. The developers promised that you would be able to write one program that will run on any device that runs the Java platform. This promise kind of fell short, as Java did not proliferate the world's electronics devices at the rate and the extent people expected; however, a few years ago, Android came along, and this open source platform began to do what Java could not. Android devices started making their ways into cars, desktops, tablets, phones, refrigerators, and more recently, Nexus Q's (update: cancelled). Who knows what else in the future?

Well, Java will be the primary language of all Android app/game development that we will cover (at least in the predictable future), so this is why we will start with Java.

If you already know how to do something that I cover in a lesson, feel free to skip it! I will try to make this guide cumulative, yet easy to incorporate into what you already know._______________________________________________

Now we setup our development environment. I realize this is the most boring part of app/game development... bear with me here and don't be discouraged! This is important!

*One final note* : The following instructions are for Mac and Windows._______________________________________________

Lesson #1-1: Downloading Java and Eclipse.

Before we can do any sort of Java programming, we must first prepare our development machine!

To install Java Development Kit (JDK - it lets you create java programs), follow the following steps:

Mac users: Most likely, Java is pre-installed on your computer. Skip this. Optionally, check out this link:https://www.java.com/en/download/help/mac_java_update.xml

1. Here's the link to the download (To people reading this guide in the far future: if the following link no longer functions, search for JDK on Google. If Google no longer exists, I don't know... try Bing??).http://www.oracle.com/technetwork/java/javase/downloads/index.html

2. Once you are there, look for "Java SE 7uXX (where XX is any current version... it was 21 when I downloaded it in the image below)", clickDownloadbelow JDK.

3. Below Java SE Development Kit 7uXX, look for YOUR operating system and version to download the corresponding JDK.

Note: Windows x86 refers to 32-bit, while Windows x64 refers to 64-bit.

You can check this information by right clicking onMy Computer(or Computer),properties, and you should see your type next toSystem type.

.When the download is completed, follow the provided instructions to get the JDK installed!

Now we must download Eclipse, the IDE. Feel free to look up more information on Eclipse, but once you begin programming, you will easily understand what its awesome capabilities are.

Eclipse will compile your code, let you export your code, help you correct your code, organize it, etc.It's extremely useful and very powerful!

1. Follow this link to the Eclipse.org's download page:http://www.eclipse.org/downloads/

2. Download the corresponding version of Eclipse.Eclipse Standardwill be fine here.

3. You will get a .zip file containing the Eclipse folder. No installation is needed. Place it where you want to, and openeclipse.exe. I recommend that you pin it to your taskbar, dock, or Start menu.

_______________________________________________

Lesson #1-2: Setting up Eclipse:

1. Upon starting Eclipse, it will ask you where you want to place your "workspace."Your workspace is where all of your resources, code, assets, etc. will be kept.Choose a location that you will be able to access easily.

2. Once that happens, you will see a welcome screen like so:

I will pick up right here from the welcome screen in the next lesson!_______________________________________________Day 1: Summarized

Today, we discussed Java and began setting up our developmental computers, installing both the JDK and Eclipse.

Tomorrow, we will write our first Java programs and discuss the meaning of Java jargon._______________________________________________Go to Day 2: Java Basics

Welcome to Day 2 of Kilobolt'sAndroid game development tutorial series.

Lesson #1-3: Examining Java:

Today, we will dissect a Java class. For some of you, this will be your very first encounter with raw code.But first... let's talk about Eclipse.

Yesterday, we left off at the welcome screen. You won't ever need to see it again. Just exit out of the tab like so:

Now you will be greeted with the screen you will see every time you open Eclipse: the workbench. Don't worry too much about the different panels. You will learn what each of them do eventually. For now, just check the following things.

1. Eclipse has multiple perspectives suited for different tasks. Check to see that the currently selected perspective is Java. If it is not Java, go toWindow > Open Perspective > Otherand selectJava.

2. Look at the bottom panel. If you see a Console tab, move on.If not, go toWindow > Show View > Console. This will display the Console tab, where our program will display text and error messages to us.

You are now ready to start programming!

Take a look at the Package Explorer - it's on the left side of the screen. This is where Eclipse will organize all of your projects. If you are ready to start coding, read on!

1. PressFile > New > Java Project.2. Enter a project name of your choice. I will use "KiloboltTutorialSeries."

Creating a Java Project creates a folder that will hold all the files (code and other assets) that your program needs.

3. Press Finish. You should now see the project in your package explorer.4. Double click on it to expand it. You will see the following:

rcis where all of your Java source code will be created.

JRE System Library(if your version of Java is not JavaSE - 1.7 like my screenshot, don't worry about it. We won't have compatibility issues) contains pre-written Java code -- the massive Java library (the "built-in" code) -- that you can import into your own projects. This is there so programmers like me and you do not have to waste time writing code to perform frequently performed operations; you can just import it.

Sometime in your programming career, you will hear the phrases "high level" and "low level" programming. "High level" typically refers to the type of code that the developer interacts with on a regular basis. It is the simplest and most intuitive form of the language. "Low level" functions, on the other hand, are lines of code that directly translate into computer action.

We will, for the most part, be dealing with high-level programming, while some of the code in the JRE will deal with lower level programming.__________________________________________________

5. RIGHT-CLICK on src, select New, and create a (Java) Class file. Name it HelloWorld.(By convention, class names start capitalized, and every subsequent word is capitalized!)

6. Hopefully you will see this screen!

Let's talk quickly about Java syntax, or grammar.

1. The purple words "public class" basically are descriptors of the word HelloWorld that follows. They are declaring that HelloWorld is a class that is public (it can be accessed by other classes).

2. The curly braces define where the class begins and ends. The opening { denotes the beginning of the class and the closing } denotes the end of the class. Your entire class is within these two braces.

In Java, the curly braces are used to tell the compiler (which converts our Java code into code that computers can understand) where a certain section of your code begins and ends.

So what exactly is a class?First, let us talk about objects.

Objects, in the real world, describe things that have both a state and behavior. For example, your phone's state can be: turned on or turned off while its behavior can be: displaying a game or playing music.

Objects, in programming, are similar. They too have a state and behavior, storing state in fields, also called variables, and behaving via use of methods.

A class, then, is the "blueprint from which individual objects are created" -- a template. Classes are used to create objects, and classes also define these objects' states and behaviors.

The class we have created together, HelloWorld, is not the best example for what a class is, so here's another example class that better illustrates one:

Let's dissect this class. Pay careful attention to the braces, which have been color coded to demonstrate where each brace's counterpart is. (Notice how the indents give us a sense of hierarchy. The red braces comprise the largest section of the class, the brown braces comprise the second largest section, which in turn comprises two identically sized yellow and green sections).

The red braces contain the class called Phone. In other words, it contains the blueprint that you use to create Phone objects. This class contains one method called togglePower, which as we have mentioned before is used to express or change the behavior of an object - it is a way of doing something.

The yellow braces denote the beginning and end of the method called togglePower. This method checks the value of the boolean variable "turnedOn" and acts accordingly.

The green braces denote the beginning and end of one conditional if statement, and the blue braces do the same for another conditional if statement.

If you have never programmed before, I know some of these things must be strange to you, so let me explain some of these oddities.

1. Whenever a line begins with //, everything that follows is considered a "comment," meaning that the computer will ignore it. You can use comments to leave a note for yourself (for future reference) or for other programmers (to be able to easily discern the purpose of the following lines of code).

2. After the first comment, notice the three "statements" (sentences in our language):1. int weight = 0;2. boolean turnedOn = false;3. String color = "blue";All three of these are variables. You may have learned in math that variables are letters or symbols that represent another numerical value.

In programming, a variable can be an integer (negative whole numbers, zero, and positive whole numbers), a boolean (true or false), or String (text), among several others. We will talk about these types later.

As before, the purple text modifies the following word. If we refer to the first statement:int weight = 0;

This statement is creating an integer variable called "weight" and assigning a value of 0 (using the equal sign - this is called initializing a variable, giving it an initial value).

Refering to the second statement:boolean turnedOn = false;

This statement is creating a boolean variable called "turnedOn" (by convention, Java variables begin lower case and capitalize every subsequent word, like "firstSecondThirdFourth") and assigning a value of "false."

I'm sure you get the idea and can explain the third statement.

You probably have noticed that each of these statements end with a ;

Well, think of the semicolon as the period (.) in Java. It is another punctuation that will prevent your statements from becoming "run-on statements." As a general rule, whenever you are making a declarative statement, you would use a semicolon. More on this later.

Now one last thing:

There is an equal sign = and there is a double equal sign ==.

The first of these, the assignment operator, assigns the Second item as the value of the First item (i.e. "weight = 0" assigns 0 as the value of weight).

The latter of these is comparitive. It compares the first item with the second item (i.e. "turnedOn == true" DOESN'T assign true as the value of "turnedOn" but rather checks if "turnedOn" IS EQUAL to true).

An alternative explanation can be found here:http://www.javacoffeebreak.com/faq/faq0022.html_________________

Lesson #1-3.5: A Quick Lesson on Naming:

In Java, you can name classes or variables whatever you want as long as it is not one of those purple words that Java has reserved for its own use (public, static, void, int, etc).

Classes are typically named like so:

ExampleClassName.

Methods and variables are named like so:

exampleMethodName()

and

exampleVariableName.

This is called camel casing.

In the Phone class above, togglePower is just a made-up name.So until you fill that togglePower method with statements (instrutions), togglePower is just a blank method.

_________________

Lesson #1-4: Writing our first program:

You should have a class called HelloWorld now as shown below:1. public class HelloWorld {2. 3. }We are now going to add a method called the main method to this class. If you do not remember what a method does, scroll up and do a quick review before proceeding.

A main method (the method by the name of main) is the "entry-point" for your program. It will automatically be invoked (or called) when you run the program - in other words, pressing the Run (Play) button will run the main method. Nothing more.

Dissecting the Main Method:1. public static void main(String[] args) {2. // Method body3. }

1. public, static, void - are Java modifiers.We will discuss these in detail later, but know that these three words are what we would call Java keywords, meaning that these words are already pre-defined in Java and you cannot use them as variable names or method names (you can use them as part of the full name, however). The three words here describe what type of method main is, the answer to which is, public, static, and void.

public- visible to other classes. Java programs usually incorporate multiple class files, so if you want to refer to code in the class from other classes, you make it public. (The opposite is private).

static- means that this method belongs to the Class, not an instance of the class. Recall that classes are blueprints for creating objects. The main method is the first piece of code that runs. Since we have no way of creating theHelloWorldobject to call its main method, it has to be static. If that doesn't make sense, don't worry too much about it. We will discuss it in detail later.

void- whenever we call a method (call means to ask for it to run), we can ask to receive a value back. Void means that no value will be returned. For example, if we have a method that adds two values together, then we would not write void, butint, so that the method canreturnanintvalue representing the sum.

If none of these things make sense to you, that is okay! You will begin to understand as we write some more code.

2. Methods, in Java, are indicated like below:

I. methodOne()

This above method is called "methodOne" and requires no arguments, or parameters, for the method to work.

II. methodTwo(typeargumentName)

This above method is called "methodTwo" and requires an argument of the declaredtype(which can be int, boolean, etc).

When dealing with a method that requires an argument, at the moment it is invoked (or called by using a statement), it will ask for an input. It will take this input and use it in the method. I will show you how this works in the following examples.

3. Applying #2 to the main method:

main(String[] args)

We know that the main method requires an argument of type String called args. The [] indicates that this is an array, which you can think of as a table of corresponding x and y values. For now, just know that this is what goes in as the argument of the main method every time. You do not need to understand why or what it means just yet. Trust me.

Here is the main method with its braces:1. public class HelloWorld {2. 3. public static void main(String[] args) {4. // Method Body5. }6. 7. }If you were to copy this code into eclipse and pressed Run, it would compile successfully and run.

The problem is... the main method is empty. It won't do anything yet.

So let's write our first statement (or command):1. System.out.println("Hello Kilobolt!");Pretty basic right? No? Let's dissect it.

1. System refers to a class in the library that I've mentioned before (from which you can import code), also known as the API (Application Programming Interface).

2. The periods between "System" and "out" & "out" and "println" represent hierarchy. This is called thedot operator. When we use a "." on an object, we are able to refer to one of its variables or methods.

For example:

HelloWorld.main(args);

would invoke the main method in the class HelloWorld (not that you would ever do that since main methods are called automatically).

3. println requires an argument. Inside it, you can type both literals (meaning things that represent themselves) and variables (things that contain values).

You indicate literals with quotes: " " and variable names can just be written.I will show you an example on this.

(Note: If you want to know more about the System.out.println and how it works at the lowest level, you can refer to this site:http://luckytoilet.wordpress.com/201...-really-works/But I recommend not doing so until you have a better understanding of Java).

I know it's frustrating for some of you to be writing code that you don't yet fully understand, but just bear with me for a while. Everything will become clear.

Now we insert the statement into the Main Method to get the full working code:1. public class HelloWorld {2. 3. public static void main(String[] args) {4. System.out.println("Hello Kilobolt!");5. }6. 7. }Copy and paste this into eclipse and press Run!You should see:

Hello Kilobolt! What's going on here? When you press Run, the main method is called. The main method has one statement (System.out...)which displays "Hello Kilobolt!"

NOTE: To make it easier to tell which brace goes corresponds with which, press Ctrl + Shift + F. This auto-formats your code!

This concludes Day 2.See you in Day 3, andlike us on Facebook!Go to Day 1: Setting UpGo to Day 3: More Basics

Lesson #1-5: More on Variables:We will be talking about variables in this lesson.Refer to the phone pseudo-class that I created as an example:

The threefields(also calledvariables) that I've created are: an integer variable calledweight, a boolean variable calledturnedOn, and a String object calledcolor.Today, we will discuss these in detail.

There arefour kindsof variables (also called fields. Remember! Variables = Fields!)

First, recall that Classes are blueprints for creating objects. Every time you create an object with this class, you are instantiating (creating an instance, or copy, of) this class. In other words, if you were to use the Phone class to create Phone objects, every time you created a new Phone object, you would have a new instance of the Phone class.

With each of these instances, variables that are defined in the class are also created. So each of these Phone instances will now have the weight, turnedOn, and String fields. When you make adjustments to a specific phone by, for example, adding 1 to weight, IT WILL ONLY AFFECT THAT PHONE. The other phone's weights are not affected. This means that each of these Phone objects have their own sets of fields (variables) that are independent from each other.

This is because the variables (fields) are...

1. Instance variables.When a variable is declared without the keyword "static" (i.e. "int weight = 0" rather than "static int weight = 0"), you are creating instance variables, which have unique values for each instance of the Object that they belong to.

What if you wanted to be able to change the values of these variables (again, fields) and affect every single Phone object that you created?

Then you create what we call...

2. Class variables.Any time that you declare a variable with the keyword "static" ("static int weight = 0"), you are basically saying that there will only be a single copy of this variable even if there are multiple Phone objects.

Have a look at the following example. (No need to write it yourself).It will (hopefully) clear some things up.

Pretend that we live in a world where you can make real life changes happen with Java.

Let's say Samsung has created 10 Android Phones using the AndroidPhone class above.The next day, 10 users purchase these phones. We will label them phoneOne, phoneTwo, phoneThree, and so on.

When (if ever) Samsung releases an update, they would want all 10 of these devices to get the update together (I know this isn't a very realistic scenario, just pretend)!

So they would use Eclipse to say:

(Note: If you take the equal sign too mathematically, it will confuse you. So, whenever you give a value to a variable, try and interpret it like this:"versionNumber isTAKES THE VALUE OF2.3." It will make it easier to conceptualize).

Recall that we created a static double (decimal variables) called versionNumber. This means that when you change the value of versionNumber once, it will affect every instance of the AndroidPhone class, meaning that all 10 AndroidPhones will receive the update immediately!

It makes sense to create a static variable for the versionNumber, but it does not make sense to create a static variable for the power! You don't want the user to be able to turn off other people's phones - you want each phone to have its own "turnedOn" boolean (True/False variables).

How, then, do you select which phone will turn on or off?It's rather simple!

Remember that we labeled each of these phones (phoneOne, phoneTwo, etc).

Now the final variable, "final String color = "blue";String means text, and we are creating a color variable with the value of "blue" (quotes indicate literals. no quotes would give color the value of a variable called blue).

The color of these 10 AndroidPhones will never change (ignore spraypaint and cases). So, we just indicate that they are "final."

In case you forgot (or skipped) how we got into the discussion of static, non-static, and final variables, we were talking about the four types of variables in Java.

Moving on to the third type of variable!We've been creating variables that belonged to the class as a whole. Now we will talk about...

3. Local Variables. If you create a variable within a method, it will only belong to that method (and go away when that method is finished). If you try to invoke that variable by name in other methods, Eclipse will happily and correctly inform you that the variable doesn't exist!

Example:

There are three variables (NOT TWO) in this class.1. The class variable called pi.2. The local variable called hello in the main method.3. The local variable called hello in the secondaryMethod.

REMEMBER:When you declare and initialize a variable in a method, that variable will only belong to that method!

Let us finish with the discussion of the final type of variable:

4. Parameters. It is possible to use a local variable in multiple methods. This is how:

Whenever you invoke a method, you use the "methodName();" statement.If this method requires a parameter, the code will not successfully run (it will give you errors for that method).

The secondaryMethod requires a "double (decimal number)" to proceed. So you must pass in a double when you invoke the method...

What this does (when you invoke secondaryMethod from the main method):

It takes the hello double from the main method and "sends it over" to the secondaryMethod, which labels it as aLOCAL VARIABLE called hello. So there are TWO hello variables involved, just like before. NOT ONE.

What does this mean?Main method's hello will have a value of 5.14.Secondary method's hello will have a value of 10.14.Confused? Read the last few paragraphs a few more times, and then comment below.__________________

Just to clear things up regarding methods and invocation.

In Java, the code will typically be read from top to bottom.As the programmer, you are basically doing one of two things:

1. Setting up things to be invoked.2. Invoking (calling) things.

When you create a new method, let's say it's named methodName, it will be ignored until you explicitly call it into action by writing:methodName();

You can see an example of this if you compare the examples for Local Variables and Parameters. In the Local Variables example, I setup the secondaryMethod() but I never call it to happen. So nothing inside it actually getsreached when you press Play. However in the Parameters example, I state: secondaryMethod(hello);. This calls the secondaryMethod that I have setup, so everything inside will be reached and ran.

The only exception is the main method, because it is IMPLICITLY called when you press Play in Eclipse.

You can create as many methods as you want. They are there for your benefit: to group and organize your statements, and to make these statements easily accessible without re-writing each line of code.

See you in Day 4!Day 2: Java BasicsGo to Day 4: Java Math

49 Comments

Lesson #1-6: Fun(?) with MathNot bored yet? Is Java beginning to interest you now? :)

I hope you don't dislike Math. If you do, don't let this hatred spill over to your feelings about Java and game development!

I'm happy to tell you that Math is pretty straightforward. Let's begin with a fewarithmetic operators.

How to follow Examples:(if you are writing these programs yourself in Eclipse, your procedure should be:)

1. Create a new class file in thesrcfolder of your Eclipse project, and name it MathLearning.2. Start by declaring the class (if it's not declared already):

class MathLearning{

}

2. Add the main method inside:

class MainLearning{

public static void main(String[] args){

}

}

3. Add the variable declarations: static int a = 10...and so on.4. Write the first 10 statements of the main method.5. Define theblahBlahBlah(int output)method below the main method, and write its single statement.6. Finish the est of the main method (the last 5 statements)

***Remember that // denotes comments. Do not write those! :) ***

Before you copy this code into Eclipse, let's see if you know what the code will do.Try and follow the code to see if you can write down the five outputs.

If you get stuck, check below:

1. We first declare a new class called MathLearning.2. Next we declare 3 class-wide variable integers: a, b, and c.3. We move on to create the main method with its typical parameter (String[] args).4. Then we create 5 integers. Unlike before, we don't initialize (meaning we don't give them a starting value).5. We assign values to the 5 integers that we created in step 4.6. The statements that begin with blahBlahBlah... areinvokingthe blahBlahBlah method with a required integer parameter.7. We setup the blahBlahBlah(int output) method.

Important notes:

The location of the blahBlahBlah(int output) method does not matter. We can put it above the main method or below the main method.The main method, if you recall, will ALWAYS run first.

When the statements from step 6 above are "reached" (again, think Top to Bottom in the main method), Java will look for the method by the name of blahBlahBlah and followthe instructions contained therein.

The resulting output is...

Wait a second. Everything makes sense, but resultFour is completely off!22/15 is not 1... or is it?

Remember that the variables c and b (22 and 15) are both integers.resultFour, which is calculated using c / b is also an integer. This means that when the calculation happens, the computer willround down to the nearest whole number to keep the value of resultFour as an integer, as in the remainder is just thrown away.This is why you do not see a decimal result, but a lower value of 1.

The solution?Let's change all the int declarations to double declarations.

There's another problem. We get five lines of numbers, but they aren't labeled.If we want each of the lines to display:

Result 1 is 25.Result 2 is -5.Result 3 is 220.......

What could we do?

There's only one line that outputs text (System.out.println...) within the blahBlahBlah class, and it treats all the inputs the same way.It has no idea of telling whether a given input is result or resultFive.

This is when we use a counter.

To do so, we will learn...two more operators today:

There are differences between

and

But the latter is much more commonly used and you can (for the most part) accomplish the exact same things without the former,so we won't waste timediscussing it at the moment.

Example of a counter follows:

Let's dissect this class.

1. We declare a Counter class.2. We create an integer called counter with initial value of zero.3. We create a main method.4. Inside the main method, we create a "while loop" (we will learn this soon!)5. The while loop, as long as counter is below 10, will add one, and display that number.

int counter starts at zero. As soon as Java reaches the while loop, it will add one, and print the new value of counter: 1.int counter is now 1. The loop will add 1 again and print the new value of counter: 2.int counter is now 2. The loop will add 1 again and print the new value of counter: 3....int counter is now 10. The while (counter < 10) condition is no longer met, so the loop ends.

________________

Now let's apply this to the first MathLearning class example:

Compare this to today's first example.

1. I changed all the int declarations to double declarations to show decimal values.2. I created a static int called counter (if this is not static, each time that the method is invoked,the value of counter will be 1, as each instance of this method will get its own counter integer), and used it to label each line of output.

The console will display:

2. Let's talkabout this:

You are familiar withSystem.out.println();But what are the plusses used for?

In this case, these plusses are not additions. They just let you combine different variables and literals into one String (this is called concatenating) that can be displayedusing System.out.println();

So what ("Result " + counter + " is " + output) is really showing is:

"Resultcounterisoutput"

And we will conclude Day 4 here. :D

Thanks for reading!Confused? Comment below. Go to Day 3: More BasicsGo to Day 5: More Math

Lesson #1-7: More Fun with Math

First, a quick review:In Java, you will frequently see statements written like the following:(Assume that number is an integer)

This tends to confuse many beginning programmers, because they are missing the fundamental purpose of the equal sign.

Like I've said before, the equal sign does not just state equality; instead, it is used to ASSIGN a value (hence the name -- assignment operator).

In other words, it doesn't state that the operand on the left and the value on the right are equal. Instead, it says that the operand isnow equalto the value - that the operand takes the value on the right side of the equal sign.

Interpreting the example above, you should think to yourself, 'number isnow equalto number + 5.'

This will save you a lot of headache.If you understand this,here is a list of equivalent expressions that will save you some time in programming:

Lesson #1-8: Randomization

Predictability makes for boring games. If you want games to challenge players, you will want to userandomization.Let's use TUMBL as an example. For those of you who are not familiar with the game,click here.

1. Each row is generated randomly, meaning that the player will not be able to figure out a pattern that lets them stay alive longer.2. Stars are generated randomly on the left or right side of the screen.3. Power-ups appear randomly.And so on.

So how do you integrate randomization to a game?

It's quite simple. Take a look at this example class:

In this classnamed Randomization, we create a Random object called rand.Let's break up this statement:

thinkof this just like:

You are creating a new object called rand using the type Random.

The second part of the statement:

assignsa new Random object with a default seed (I will explain seed in a second) as the value of the newly-createdrandvariable.

In other words...you are basically telling Java:"I want to create a Random object called rand. Use the Random class (specifically something called the constructor) to create this new object."

If you are confused, that's okay. We will go into object creation and constructors in a lot more detail in the coming lessons.

Just know that:

creates a new Random object called rand (you can change this name).

Mini Lesson : Imports

When you copy and paste the following class into Eclipse:Figure 1: randomization class// In this class, we will create a Random object called rand.

class Randomization {

public static void main(String[] args){

Random rand = new Random();}

}Youwill see red squigglylines below the word Random, indicating the presence of an error:

This error occurs because the "Random class" is not recognized by your current class (Randomization class).

Earlier, I mentioned that thesrcfolder contains all your Java code and that theJRE System Librarycontains importable codethat you can incorporate into your own projects.

Think of this Library as one containing "books" (Java classes). When you write an essay and you reference a book, you cite it.

Same with Java. When you use a "book" (Java classes) from the Library, you must state that you are using this "book" so that the compiler knows where to find the Random class and its associated methods.

This is accomplished byimporting.How do we import? It's pretty simple.

1. The easiest way is to press:

This will automatically import the class that the compiler thinks you are most likely to use.

2. Another way is to put your mouse over the words that show an error (in this case Random) and click on the quick fix that suggests importingthe Random class from Java.util.Either way, when you successfully import, the error will disappear, and you will see the following above your class name:import java.util.Random;- indicating that your class makes use of this Random class which can be found in the full address ofjava.util.Random.

The full class, after importing, will look like this.Figure 2: randomization class with imports

Well, now that we have a random object called rand, we can use it to randomize things.The easiest method we will learn is:

What does this method do?When you call this from a random object such as rand like so:

It will generate an integer between 0 and 10 (11 numbers).Using this, you can simulate chance and probability.How? We will go overprobabilityandif statementstomorrow!

If you have any questions, please post on theForum!

If you are learning from and enjoying the tutorials, please supportKilobolt Studios!AndLike us on Facebookto receive updates when a new lesson is posted!

Lesson #1-9: If and else statements

In Java, we can control the "flow" of the program by using conditional statements.Let's take a look at this simple example.

This is a pretty simple class.Let me explain some of the things we have here.

1. class DrinkingAgeTest creates a class called DrinkingAgeTest.2. We then create a static integer age (this does not have to be static if it is placed inside the main method).3. Of course we create a main method, as all Java programs will look for this as a starting point.4. Now the interesting parts:

Meettheif statement. It is written like so

When Java encounters the if statement, it checks each condition to see if it is satisfied (true).If so, it carries out everything inside the braces for that if statement. If not, the statement is completely skipped.

Applying this to the example class, the compiler checks if age, which is 18, is greater than or equal to 21.It is not, so it skips the line:

Since none of the previous conditions aremet, it automatically goes into the else statement, which outputs:

Note: If you have multiple "if" statements, each of them is checked to see if true. If only one of the conditions can be true (i.e. the conditions you are testing for aremutually exclusive), it is therefore

Now we are going to apply this to simulate probability.

Lesson #1-10: Simulating Probability: Relational Operators

In the lesson #1-8, we created a random object called rand and invoked the method "nextInt."

Recall that the above generates a number between 0 and 10 (11 numbers starting with zero).

Now let's simulate probability, starting with a simple example.

importjava.util.Random;

//Let's simulate a coin toss!publicclassSimulation{ publicstaticvoidmain(String[]args){ Randomrand=newRandom(); intresult=rand.nextInt(2); if(result==0){ System.out.println("heads"); } elseif(result==1){ System.out.println("tails"); } elseif(result==3){ System.out.println("side. fix your random number generator"); } }}This is also a pretty straightforward class. We use the random number generator to create an number between 0 and 1 (inclusive) and set it equal to a newly created integer:result.

We arbitrarily decide that the value of 1 is equal to heads and the value of 0 is equal to tails. Now we test the value ofresultusingelse ifstatements (mutually exclusive events) and display the appropriate string (text).

Since the value ofresultshould never (theoretically) be 3, I created a third statement that is only read ifresultdoes somehow become 3 (it should be as common as landing a coin on its side).

In these two lessons, we used two operators: == and >=.

Here are all six relational operators:

Lesson #1-11: Conditional Operators and Our First Game

In this lesson, we are going to create a simple game. Oh, don't get too excited. By simple, I meansimple.Before we do that, here's a quick lesson onconditional operators:

When youhave an if statement like below:

Thenif eitherconditionOne or conditionTwo is true, it will invoke the "doThis()" method;

When you have a statement like this:

ThenbothconditionOne and conditionTwo must be satisfied before "doThat" method is called.NOTE: When you just write a boolean (variables with value of either true or false, such as conditionOne) without stating: == true or == false, it is assumed that you actually wrote boolean = true.

In other words:

And

Are equivalent.

Now back to our game!Here is how the game works. You roll a 6-sided die. If you land a 1 or 2 you lose. If you get a 3, 4, or 5, you roll again. If you get a 6, you win.

To write good programs, you have to plan beforehand. You should think the following:

1. I need a random number generator.2. I should test if:

I. a number is less than or equal to 2.II. if not, I should test whether if that number is between 3 and 5 (inclusive)III. if not, I should test whether if that number is 6.

3. I should carry out an appropriate response.

Simple. Now let's create this class.figure 3: BySimpleIMeanSimple class, Complete import java.util.Random;

//The greatest game ever made follows.class BySimpleIMeanSimple { static int dieValue; public static void main(String[] args) { rollDie(); } // ends main

static void rollDie() { Random rand = new Random(); // Assign a random number between 1 and 6 as dieValue dieValue = rand.nextInt(6) + 1; System.out.println("You rolled a " + dieValue); // Why add 1? Think about it. testDieValue(dieValue); } // ends rollDie()

static void testDieValue(int dieValue) { if (dieValue = 10) { earthIsSpinning = false; } // ends If

} // ends While

} // ends Main

} // ends Looping Class Most of this code is self explanatory, because it incorporates elements that we have seen before.Let's talk about some of the things that you may have forgotten or have unanswered questions about.

Within the main class:

1. We create a boolean earthIsSpinning, and initialize the value to be true.2. We also create a counter and set the value as 0;

A while loop that has the condition (earthIsSpinning == true) is created.Inside it,1. We display "The earth is still spinning."2. We display the value of the integercounter.3. We add 1 to counter's value.

An if statement iscontained inside the while loop.If counter is less than 10, this if statement is ignored!

With each iteration, or execution, of the while loop, the value of thecounterinteger, which begins at 0, increases by 1.This means that after the 10th display, earthIsSpinning would be set equal to false, and the condition of the while loop will no longer be satisfied, meaning that it will terminate.

Why does this if statement have to be inside the while loop? Because if we put the if statement outside the while loop, it will only run once right after the first execution of the while loop, whencounteris equal to 1. The if condition will not be satisfied and the statement will never be called again.

Another way you could end the loop is by callingbreak;whenever you need to. That way, you don't have to stop spinning the earth to stop your loop._____________________

Do you ever find it difficult to count? Me neither, but let's create a counting program for the heck of it.

This program will use two values: an initial value and a final value. It will then sequentially count the integers between the two values.

_____________________Figure 4: Looping Class public class Looping { public static void main(String[] args) {

int initialValue = 0; int finalValue = 10;

int counter = 0;

if (initialValue < finalValue) { System.out.println("Input accepted!"); System.out.println("Initial Value: " + initialValue); System.out.println("Final Value: " + finalValue); System.out.println(); System.out.println("Initiating count."); System.out.println();

System.out.println(initialValue); counter++;

while (initialValue < finalValue) { initialValue++; System.out.println(initialValue); counter++;

}

if (initialValue == finalValue) { System.out.println(); System.out.println("Counting complete."); System.out.println("There are " + counter + " numbers (inclusive) between " + (initialValue - counter + 1) + " and " + finalValue + "."); }

} else { // Executed if: if (initialValue < finalValue) above is not true.

System.out.println("Final value is less than initial value!"); System.out.println("Please choose new values."); }

}} The Output:

Try to study this code and see if you can figure out what it is doing.It looks complex, but it is very straightforward!

We will analyze this in detail tomorrow!_____________________

If you want to thank me for the guide, you can press Thanks ordonate hereordownload TUMBL +!Go to Day 7: More Control FlowGo to Day 9: More on Looping

I think after 3 more days, we can begin actual game development.

Of course there's a lot more to learn, but I think it would be more fun and more efficient to learn some of the tougher concepts by application.

Without further ado, let's jump into our next lesson!

Lesson #1-16: Analyzing the Looping Class

In the last lesson, I created a class called Looping as follows: public class Looping { public static void main(String[] args) {

int initialValue = 0; int finalValue = 10;

int counter = 0;

if (initialValue < finalValue) { System.out.println("Input accepted!"); System.out.println("Initial Value: " + initialValue); System.out.println("Final Value: " + finalValue); System.out.println(); System.out.println("Initiating count."); System.out.println();

System.out.println(initialValue); counter++;

while (initialValue < finalValue) { initialValue++; System.out.println(initialValue); counter++;

}

if (initialValue == finalValue) { System.out.println(); System.out.println("Counting complete."); System.out.println("There are " + counter + " numbers (inclusive) between " + (initialValue - counter + 1) + " and " + finalValue + "."); }

} else { // Executed if: if (initialValue < finalValue) above is not true.

System.out.println("Final value is less than initial value!"); System.out.println("Please choose new values."); }

}} The Output:

It might have been a while since we discussed some of these concepts, so please refer to previous lessons if you are confused!And of course, you can comment below with questions as always.

Now toanalyze:

1. The blue text begins the Looping class. (I hope you know this by now).2. The light blue text then begins the main method (you should know what the main method is also).

3. The next three statements beginning "int..." initialize three integers: initialValue, finalValue, and counter.

4. The point of this program is to count from a lower number to a higher number, so the first condition it tests for, using an if statement is whether initialValue < finalValue.

5. If this condition is satisfied, we see a bunch of System.out.println("...")

6. The counter variable is increased by 1.

7. The while loop then initiates, and this increases initialValue by 1, and displays the new initialValue.

8. Counter variable is again increased by 1.

9. With each iteration (repetition) of the while loop, we check if the initialValue (which increases by 1 with each iteration) is equal to finalValue, because that is when we can stop counting.

10. When this if condition (colored gold) is satisfied, we stop counting, and display the counter variable, which has been increasing by 1 with each increase in value of the initialValue variable.

Make sure you run this code a few times with your own numbers to understand what exactly is happening at each step.

If you want to make your own programs, you should be able to analyze and at least have a general sense of what other programmers are trying to accomplish with their code.

Lesson #1-17: The For Loop

The while loop utilized a counter that we coded ourselves. Now we will implement thefor loopwhich comes with a built-in counter, so to speak.

The form of a for loop is as follows (as stated in Java docs):

"When using this version of the for statement, keep in mind that:

1. The initialization expression initializes the loop; it's executed once, as the loop begins.2. When the termination expression evaluates to false, the loop terminates.3. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value."

Let's look at an example: class ForLoop { public static void main(String[] args){ for(int variable = 1; variable > Class, and typing GraphicsDemo for the name. You should then get this:

public class GraphicsDemo{

}

We now need to apply what we learned about Inheritance in theprevious lesson.To display images, we mustextendthe superclass JFrame like so:

public class GraphicsDemo extendsJFrame{

}

Eclipse will give you an error saying that JFrame cannot be resolved. So you have to import it.

Shortcut:Ctrl + Shift + OAlternate:Put your mouse over "JFrame," which will have a red underline, and import JFrame like so:

You will now see:import javax.swing.JFrame;

public class GraphicsDemo extends JFrame{

}

One of the first things we talked about in Unit 1 for Game Development is that classes are blueprints for objects. We never really discussed how this works.

In this lesson, we will use the GraphicsDemo class to create an object, much like we created a Thread object above.

To do so, we add a constructor to our class. A constructor is basically a set of instructions for creating an object:

import javax.swing.JFrame;

public class GraphicsDemo extends JFrame {

// The constructor follows: public GraphicsDemo() {

}

// All classes need a main method, so we create that here too! public static void main(String args[]) { // We will create a GraphicsDemo object in the main method like so: // This should be familar, as we used this to create Random objects and // Thread objects: GraphicsDemo demo = new GraphicsDemo();

}

}

The above code, when executed, will look for the main method. This main method contains one statement: GraphicsDemodemo= new GraphicsDemo();

When this statement executes, you will be creating a GraphicsDemo object using the constructor (so named because it is used for construction of objects) of the GraphicsDemo class: and the name of this object will bedemo.

At the moment, the constructor is empty: public GraphicsDemo(){

}

So when the GraphicsDemo object called demo is created, it will have no function. So we proceed by adding a few built-in statements that belong to theJFrame superclass(we can utilize these because we imported JFrame in the first line of code).

public GraphicsDemo(){ setTitle("GraphicsDemo with Kilobolt"); setSize(800,480); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE);}

The four statements within the constructor are self-explanatory.setTitlesets the title of the window when it is opened. The second statementsetSizesets the resolution in pixels of the window.setVisibleensures that this window is visible when you create it. The final statement just allows the window to close properly and terminate the program.

We now add the constructor back into place:

import javax.swing.JFrame;

public class GraphicsDemo extends JFrame {

// The constructor follows: public GraphicsDemo() { setTitle("GraphicsDemo with Kilobolt"); setSize(800, 480); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE);

}

// All classes need a main method, so we create that here too! public static void main(String args[]) { // We will create a GraphicsDemo object in the main method like so: // This should be familar, as we used this to create Random objects and // Thread objects: GraphicsDemo demo = new GraphicsDemo();

}

}

Now if you run the code, you will see a window of size 800,480 (X,Y).

IMPORTANT! The origin (0,0) of the coordinate system on a monitor is the TOP LEFT not BOTTOM LEFT. This means that the Y values increase as you go down the screen!

To add images, we simply need to add one more method:

public void paint(Graphics g){

}

This method requires that you import Graphics, so...Addimport java.awt.Graphics;to the top of your code (remember that this just specifies to the compiler where it can find the Graphics class).

Now this paint method will draw whatever you ask it to draw on the window that you created. I will now teach you a few basic statements.

Note: Theg.just denotes the fact that these statements (which are built-in methods of the Graphics class) are being executed on the object g.

g.clearRect(int x, int y, int width, int height);- Creates a filled rectangle with the current color (or default color if g.setColor() has not been called) with the top left corner at (0,0) with widthwitdhand heightheight.

g.setColor(Color c); - Sets the current color of g as Color c.g.drawString(String str, int x, int y); - Draws whatever string (text) str at the point (x,y).g.drawRect(int x, int y, int width, int height); - Draws the outline of a rectangle beginning at (x,y) with widthwidthand heightheight.

Let's add each of these to the paint method above.

public void paint(Graphics g){

//This sets the color of g as Black. g.setColor(Color.WHITE);

//The first statement creates the background rectangle on which the others are drawn. g.fillRect(0,0,800,480);

//This sets the color of g as Blue. g.setColor(Color.BLUE);

//This will draw the outline of a Blue rectangle, as the color of g when this is called is Blue. g.drawRect(60, 200, 100, 250);

//This sets the color of g as Black. g.setColor(Color.BLACK);

//This will display a black string. g.drawString("My name is James", 200, 400); }

We are using Color.BLUE and Color.Black from the Color superclass in the Java library, so we must import that too:

import java.awt.Color;

We add all this to the full class like below:

import java.awt.Color;import java.awt.Graphics;import javax.swing.JFrame;

public class GraphicsDemo extends JFrame {

// The constructor follows: public GraphicsDemo() { setTitle("GraphicsDemo with Kilobolt"); setSize(800, 480); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE);

}

public void paint(Graphics g) { g.setColor(Color.WHITE); g.fillRect(0, 0, 800, 480); g.setColor(Color.BLUE); g.drawRect(60, 200, 100, 250); g.setColor(Color.BLACK); g.drawString("My name is James", 200, 400); }

// All classes need a main method, so we create that here too! public static void main(String args[]) { // We will create a GraphicsDemo object in the main method like so: // This should be familar, as we used this to create Random objects and // Thread objects: GraphicsDemo demo = new GraphicsDemo();

}

}

Running this results in:

And there, we have created our first "graphics."

Thank you so much for sticking with these tutorials! This concludes Unit 1.We've covered a lot of material, and I hope that this Unit was both informative and fun for you.

I hope to implement a slightly different style of teaching in Unit 2, where we will build our first game together. Please join me there!

And finally...

Go to Day 10: Inheritance, InterfaceGo to Unit 2: Creating a Game

This is where the fun begins.All the hard work. The hours of dedication. The years of dreaming. It culminates here.Welcome to Unit 2. By the time you walk away from this Unit, you will have made a fully playable game.

Before we get into the actual coding,let's talk about logistics.

1. You will be making a Java based applet. The purpose of this is to make it easy to embed into HTML, so you will be seeing live examples on this page.

2. If you have not followed Unit 1, we will be using Eclipse throughout this series. So I suggest that you go read the first few lessons in the first Unit to get yourself ready to develop.

In the past, many of you (nearly a hundred) participated in the survey that was available on this page, and I read each response.

Thank you so much for your feedback.

Game Idea:The most popular game idea was a platforming shooter. So that is the direction we will be headed.

Lesson #2-1: Setting up a Project

You're back for more! This Unit will be fun.

Open up Eclipse and create a Java project. You can do this by right clicking on thePackage Explorer >> New >> Java Project:

Call itKiloboltGame(consistency will ensure that we won't have errors due to naming). Also the JRE version can be either 1.6 or 1.7. It does not matter!

Inside this project'ssrc folder(remember this is where we store all our code):

1. Create a Package.Name it kiloboltgame. By convention its the package name begins lowercase.

Packages are ways of organizing classes into folder-like structures.Right click on your newly created package and create a class:StartingClass.

KiloboltGame Project containing a kiloboltgame Package containing a StartingClass class.Now we can start coding.

Lesson #2-2: Adding Methods and extending Applet

By this time, I trust that you are all experienced Java programmers capable of discerning which brace corresponds with which.

As such I will no longer be color coding unless I believe it is absolutely necessary.

1. AddextendsAppletafter "StartingClass". Recall that we can borrow methods from a superclass by inheriting it.

2. You will see a red line under Applet. Import Applet by pressingCtrl+Shift+Oor by manually selecting the import by mouseover.

3. You can now add the following methods:init(), start(), stop(), destroy(). These are part of the Applet superclass, and by importing Applet, you gain the ability to use them.

4. An easy way to add a pre-defined method (as in one that is already written for you), is to use the auto-complete function. Begin typing "init" and then pressCtrl + Space. It will open an auto-complete suggestions box, from which you can choose the first init() function. Proceed to do this with all four methods and you will see this:

5. PressCtrl + Shift + Fto auto-organize your code.

Shortcuts such as these will help you save a lot of time.

Figure 2-1 package kiloboltgame;

import java.applet.Applet;

public class StartingClass extends Applet {

@Override public void init() { // TODO Auto-generated method stub super.init(); }

@Override public void start() { // TODO Auto-generated method stub super.start(); }

@Override public void stop() { // TODO Auto-generated method stub super.stop(); }

@Override public void destroy() { // TODO Auto-generated method stub super.destroy(); }}

Now, as always, we will talk about each of these methods.

The four methods:init(), start(), stop(), and destroy()are frameworks for execution provided by the Applet class. In this Applet's life cycle, major events will call one of these methods and execute it.

The@Overridetests for errors upon compilation. In this case, we are using it to annotate that we are overriding methods from a parent class. It informs you when you make mistakes.

More information on this can be found on Google. But for now, don't worry about it. :)Within each method, you will see a "super." This "super" is referring to the superclass (in this case Applet). You might also see a "this" in the future, which will refer to the current class. Don't worry about this for now. We can safely delete each"super"line (or leave it, if you choose):

Before we move on!Mini Quiz:1. How can you make a program keep running? How do you repeat statements?2. What tool do we use for simultaneous processes in Java?3. What is a game loop?

Answer these questions and check below!

Answers:1. We utilize a loop.2. A thread.3. A game loop is the central component of a game. People refer to it as the heartbeat of the game. To put simply, it is a loop that will continuously check for changes in the game and make necessary updates. Graphics, controls, movement, physics all rely on the game loop in some way.

Here's a fake game loop that will help you understand:Figure 2-2 while (playerIsAlive) { updatePosition(); applyGravity(); drawCharacterAtCurrentLocation(); } Figure 2-3 incorporates three pseudo-methods (they are simply there for illustration).

We have a condition that while the playerIsAlive is true, we update his position, redraw his character at that new position, and apply gravity.

This is a simplified example of a game loop.

As we get into more advanced gaming concepts, we will talk about creating a proper game loop. But for now, a simple one will have to suffice (And on modern computers, a little bit of slacking here won't hurt us). But wait until we start developing on Android. Technical considerations can be PAINFUL.

Day 1 will stop here. Day 2 will be up in an hour or two.

In Day 2, we will talk about applying threads and loops to create the heartbeat of our upcoming game.

Be excited.

Thank you for being an awesome audience, and please share our page on Faceboo

I've been thinking about the direction that I want to go with this game, and as of now, I am considering making it a game about a Q-bot (cube robot)*going around shooting things and jumping across platforms. Two games that I am taking inspiration from are Metal Slug and Megaman.

As we get deeper into the series, I want to add character upgrades, different types of platforms and power ups, and much more.

But first, let us talk about the game thread and the game loop.

(*Name not final)

Lesson #2-3: Implementing a Thread:As mentioned in the previous unit, threads are a way of running simultaneous processes.We will be adding a thread to our code like so:Figure 2-4: start() in StartingClass.java @Overridepublic void start() { Thread thread = new Thread(); thread.start();}

Simple right? The first line creates a new instance of a thread (a Thread object called "thread"), and the second line starts the thread.

When you call:thread.start();, however, nothing will happen. Why?

Refer to this example fromLesson #1-21:Figure 2-5: Example of a Thread Thread thread = new Thread() { public void run() { for (int i = 0; i < 10; i += 2) { System.out.println("hello"); } }

}; Threads require a run method that determines what will happen in that thread. InFigure 2-4we never declared a run method. There's a reason for this. We will be extracting the run method from the thread and creating a separate method in the class by doing the following:

1. Implement theRunnableinterface by adding: "implements Runnable"to the class declaration like so:

public class StartingClass extends Appletimplements Runnable{...

2. Create a run() method in the class by typing outrunand then pressing Ctrl + Space and selecting the first option:run() : void. It will auto complete the method for you.

When you try to create a run method, it will give you the following information:

This tool tip describes that when we implement interface, we can extract the run method from the Thread that we created.

So to "bridge" or connect this newly created run() method and the thread that we have created above:

3. Go back to this statement in the start method:

Thread thread = new Thread();

and add "this":

Thread thread = new Thread(this);

We will talk more about "this"in the future. It is quite a flexible keyword, and therefore I think it's best if we talk about it from another perspective with more understanding. For now, think of it as "this" class. More specifically, "this" instance of the class.

The final result:Figure 2-6: StartingClass.java package kiloboltgame;

import java.applet.Applet;

public class StartingClass extends Applet implements Runnable {

@Override public void init() {

}

@Override public void start() { Thread thread = new Thread(this); thread.start(); }

@Override public void stop() { // TODO Auto-generated method stub }

@Override public void destroy() { // TODO Auto-generated method stub }

@Override public void run() { // TODO Auto-generated method stub }} Lesson #2-4: Creating the infinite game loop:In this lesson, we will be creating a game loop. I mentioned in Day 1 that a game loop is the heartbeat of the game. It constantly checks for changes and makes updates to the game accordingly.

More sophisticated game loops will be used in our later games, but for our purposes, all our game loop needs to do is the following:

1. Update characters2. Update environment3. Repaint the scene.4. Sleep for 17 milliseconds.

Why 17 milliseconds you ask? I'll tell you why.

I'm sure many of you know that when you go on YouTube and watch the Epic Rap Battles or something, you are seeing a sequence of still images that are changing fast enough to give your brain the illusion of fluid motion. The number of times that the image changes in one second is referred to as FPS or frames per second (frame rate).

At about ~30, we are able to see a smooth movement in games and movies; however, 60 fps is what most people consider an ideal to have no noticeable glitches or stuttering.

Sleeping for 17(1000/60)milliseconds each time that the game loop runs means that the game will update every 17 milliseconds (which results in 60 updates per second). Of course this assumes that the computer is capable of handling the processes every 17 milliseconds and can bedisastrous when the machine slows down (hence this is a bad game loop), but for the purposes of our simple Java game on your modern day computer (and for this beginner's tutorial), it is simple, effective, easy to implement, and very intuitive.

So first we create a game loop in therun()method of the class:

1. This loop will be a while loop, and will run indefinitely. To make a while loop run forever, we just writetrueas the condition for the loop:

while(true){

}

2. Within this add the following segment of code:

repaint();// this calls paint

try { Thread.sleep(17);} catch (InterruptedException e) { e.printStackTrace();}

Yourrun()method will look like this:Figure 2-7: run() in StartingClass.java @Overridepublic void run() { while (true) { repaint(); try { Thread.sleep(17); } catch (InterruptedException e) { e.printStackTrace(); } }} Let's look at this line by line:

repaint();- built in method - calls the paint method (in which we draw objects onto the screen). We haven't created the paint method yet, but every 17 milliseconds, the paint method will be called..

Whenever we do something that may fail (likeThread.sleep(17);) the Java Compiler gives us an error saying that we need to surround the statement with a Try and Catch.

What a try/catch does is the following.

1. In try, we attempt to do something, like sleep.2. If something goes wrong, then the catch will save information regarding errors, and will print it to a console.

Don't worry too much about it. It's just a built-in fail-safe system. It won't fail here. Just click the suggested quick fix.

At this point theStartingClass.javawill look like this:Figure 2-8: StartingClass.java package kiloboltgame;

import java.applet.Applet;

public class StartingClass extends Applet implements Runnable {

@Override public void init() { }

@Override public void start() { Thread thread = new Thread(this); thread.start(); }

@Override public void stop() { // TODO Auto-generated method stub }

@Override public void destroy() { // TODO Auto-generated method stub }

@Override public void run() { while (true) {

repaint(); try { Thread.sleep(17); } catch (InterruptedException e) { e.printStackTrace(); } }

}} Lesson #2-5: Defining size, background, and title.This will be a short lesson that should wrap up most of our setup process.

We briefly talked about the four methods that we setup in Day 1: init(), start(), stop(),anddestroy().

These four methods run according to the program's life cycle. We will now discuss theinit()method.When the applet runs for the first time, it will run theinit()method (much like how a typical program runs themain(String args[])method).

So within this method, we define certain parameters for the applet including:

1. Size of the applet2. Background color.3. Applet Title.

Inside this method, we will be adding

1.setSize(800, 480);to change the size to 800 pixels by 480 pixels (the most common Android resolution)

2.setBackground(Color.BLACK);to set background with the Color Black.NOTE: Color.BLACKrefers to a constant called BLACK in the Color superclass, and hence you must import Color:

To use a constant from the Color superclass, we must import the Color superclass.3.setFocusable(true);This statement makes sure that when the game starts, the applet takes focus and that our input goes directly into it. If this is not enabled, then you would have to click inside the applet before it starts handling keyboard events.

4. Frame frame = (Frame) this.getParent().getParent(); frame.setTitle("Q-Bot Alpha");

Here again, you must importFrameto create a Frame object called frame. This is slightly complicated, but just know that the first line assigns the applet window to theframevariablean the second line just sets the title to beQ-Bot Alpha.

At this point, you will have this:Figure # 2-9: StartingClass.java, end of Day 2 package kiloboltgame;

import java.applet.Applet;import java.awt.Color;import java.awt.Frame;

public class StartingClass extends Applet implements Runnable {

@Override public void init() {

setSize(800, 480); setBackground(Color.BLACK); setFocusable(true); Frame frame = (Frame) this.getParent().getParent(); frame.setTitle("Q-Bot Alpha"); }

@Override public void start() { Thread thread = new Thread(this); thread.start(); }

@Override public void stop() { // TODO Auto-generated method stub }

@Override public void destroy() { // TODO Auto-generated method stub }

@Override public void run() { while (true) {

repaint(); try { Thread.sleep(17); } catch (InterruptedException e) { e.printStackTrace(); } } }} Short Cut Reminders:

Ctrl+Shift+O:Auto import code (may import the wrong classes)Ctrl+Shift+F:Auto format code into proper indentsCtrl+Space: Open auto complete suggestions.

Thank you everyone for reading, and feel free to leave comments and questions below!

From now on, I will be including the project folder as a source code for people who don't want to write their own code, or just want to examine their own.

Lesson #2-6: Implementing KeyListener

Welcome to Day 3. Today we will be adding code that will allow our game to respond to the user's actions on the keyboard.

Here's how we will approach it:1. In order for our game to "listen" for key presses and releases, we have to give it a listener.2. To accomplish #1, we simply need to implement the "KeyListener" interface, and then add the KeyListener in ourinit()method.3. Implementing an interface requires that you take every method defined in the KeyListener superclass and add it to your code. These three methods are:keyPressed(),keyReleased(), andkeyTyped().

So let's get started by implementing the KeyListener.

1. Go to your StartingClass.java and examine your class declaration:

public class StartingClass extends Applet implements Runnable{

You will notice that you are already implementing the Runnable interface, so you simply add:", KeyListener" to the end like so:

public class StartingClass extends Applet implements Runnable, KeyListener{

2. When you add this, Java will give you an error saying "KeyListener cannot be resolved to a type". To resolve this error, just import KeyListener.

3. You will now see an error: "The type StartingClass must implement the inherited abstract method KeyListener.keyReleased(KeyEvent)."

Recall that when you implement an interface, you must take all of its methods and declare them in your class. So you can easily resolve this by choosing:Add unimplemented methods.

4. Adding unimplemented methods will do two things: First, it will add the three methods:keyPressed(),keyReleased(), andkeyTyped()to your code. These three methods require a KeyEvent object as a parameter. Java is smart enough to import KeyEvent for you.

5. Finally, add this implemented KeyListener to the current Applet by adding to theinit()method:addKeyListener(this);

The resulting code is as follows:Figure 2-10: StartingClass.javapackage kiloboltgame;

import java.applet.Applet;import java.awt.Color;import java.awt.Frame;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;

public class StartingClass extends Applet implements Runnable, KeyListener{

@Override public void init() {

setSize(800, 480); setBackground(Color.BLACK); setFocusable(true); addKeyListener(this); Frame frame = (Frame) this.getParent().getParent(); frame.setTitle("Q-Bot Alpha");}

@Override public void start() { Thread thread = new Thread(this); thread.start(); }

@Override public void stop() { // TODO Auto-generated method stub }

@Override public void destroy() { // TODO Auto-generated method stub }

@Override public void run() { while (true) {

repaint(); try { Thread.sleep(17); } catch (InterruptedException e) { e.printStackTrace(); } } }

@Overridepublic void keyPressed(KeyEvent e) { // TODO Auto-generated method stub }

@Overridepublic void keyReleased(KeyEvent e) { // TODO Auto-generated method stub }

@Overridepublic void keyTyped(KeyEvent e) { // TODO Auto-generated method stub }

}The first two methods are self-explanatory. keyTyped is slightly more complicated, but you can learn more about it here:http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/event/KeyEvent.htmlLesson #2-7: Listening for Key PressesIn our 2D-platformer, we will need at least five buttons to start. The four directional arrows will each be a button, and for now we will use the Space Bar for jump.

We are now working in thekeyPressed()method. Inside, we will create a switch that will carry out the appropriate action depending on which button is pressed:@Overridepublic void keyPressed(KeyEvent e) {

switch (e.getKeyCode()) { case KeyEvent.VK_UP: break;

case KeyEvent.VK_DOWN: break;

case KeyEvent.VK_LEFT: break;

case KeyEvent.VK_RIGHT: break;

case KeyEvent.VK_SPACE: break; }}Let's examine this in detail. We learned about switches in Unit 1. It is an alternative to a long list of if statements. A switch will compare thekey, which is the variable we are checking for, withvalues, and then carry out the appropriate response.

In this case, thekeyise.getKeyCode(). e.getKeyCode() will return the code of the button that you press on the keyboard. (If you were to typeSystem.out.println(e.getKeyCode());, each time that you press a button, it will display the key code on the console).

What the switch is doing here, then, is comparing the e.getKeyCode() returned from your button presses, and comparing it to multiple cases ofvalues.Lesson #2-8: Listening for Key ReleasesWe will apply the exact same concept to Key Releases.In this situation,e.getKeyCode()will return the key code upon release of a button (since it is in thekeyReleased()method). Then it will carry out an appropriate response depending on which button is released.@Override

public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: break;

case KeyEvent.VK_DOWN: break;

case KeyEvent.VK_LEFT: break;

case KeyEvent.VK_RIGHT: break; case KeyEvent.VK_SPACE: break;

}}At the present, we have no character to actually move or stop. Therefore, we will just output some text to the console like so:Figure 2-12: StartingClass.java, End of Day 3package kiloboltgame;

import java.applet.Applet;import java.awt.Color;import java.awt.Frame;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;

public class StartingClass extends Applet implements Runnable, KeyListener {

@Override public void init() {

setSize(800, 480); setBackground(Color.BLACK); setFocusable(true); addKeyListener(this); Frame frame = (Frame) this.getParent().getParent(); frame.setTitle("Q-Bot Alpha"); }

@Override public void start() { Thread thread = new Thread(this); thread.start(); }

@Override public void stop() { // TODO Auto-generated method stub }

@Override public void destroy() { // TODO Auto-generated method stub }

@Override public void run() { while (true) {

repaint(); try { Thread.sleep(17); } catch (InterruptedException e) { e.printStackTrace(); } } }

@Override public void keyPressed(KeyEvent e) {

switch (e.getKeyCode()) { case KeyEvent.VK_UP: System.out.println("Move up"); break;

case KeyEvent.VK_DOWN: System.out.println("Move down"); break;

case KeyEvent.VK_LEFT: System.out.println("Move left"); break;

case KeyEvent.VK_RIGHT: System.out.println("Move right"); break;

case KeyEvent.VK_SPACE: System.out.println("Jump"); break;

}

}

@Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: System.out.println("Stop moving up"); break;

case KeyEvent.VK_DOWN: System.out.println("Stop moving down"); break;

case KeyEvent.VK_LEFT: System.out.println("Stop moving left"); break;

case KeyEvent.VK_RIGHT: System.out.println("Stop moving right"); break;

case KeyEvent.VK_SPACE: System.out.println("Stop jumping"); break;

}

}

@Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub

}

}

That's today's lesson! On Friday, we will be adding the background, our main character, and then add some movement!

Thanks for following my tutorials, and let me know if I can help you in any way!

KiloboltGame - Day 3

Download File

Instructions on importing projects can be foundhere.

Go to Day 2: Basic FrameworkGo to Day 4: Enter the Robot

56 Comments

Lesson #2-9: Creating the Main CharacterWelcome to the fourth day! Now that we got the basic frameworks set up, we will be adding our main character.

To do so, we will be creating a new class.Within this class, we will do the following:

1. Manage x, y coordinates and speed.2. Make updates to speed and position.3. Allow other classes to retrieve its x, y related variables.

Therefore, the methods of this class will be divided into these categories:

1. Constantly updated methods that are called on each iteration of the game loop.2. Methods that are only called upon player input.3. Helper methods that retrieve and change the value of variables in the class.

Let's get started.

We begin by creating a new class calledRobot.javain the kiloboltgame package (or whatever you named your package).

Copy and paste the following:Figure 2-13: Robot.javapackage kiloboltgame;

import java.awt.Graphics;

public class Robot { //In Java, Class Variables should be private so that only its methods can change them.private int centerX = 100;private int centerY = 382;private boolean jumped = false;

private int speedX = 0;private int speedY = 1;

public void update() {

// Moves Character or Scrolls Background accordingly.if (speedX < 0) {centerX += speedX;} else if (speedX == 0) {System.out.println("Do not scroll the background.");

} else {if (centerX = 382) {centerY = 382;}else{ centerY += speedY; }

// Handles Jumpingif (jumped == true) {speedY += 1;

if (centerY + speedY >= 382) {centerY = 382;speedY = 0;jumped = false;}

}

// Prevents going beyond X coordinate of 0if (centerX + speedX = 382) { //382 is where the character's centerY would be if he were standing on the ground.centerY = 382;}else{ centerY += speedY;//Add speedY to centerY to determine its new position }

// Handles Jumpingif (jumped == true) {speedY += 1;//While the character is in the air, add 1 to his speedY. //NOTE: This will bring the character downwards!

if (centerY + speedY >= 382) {centerY = 382;speedY = 0;jumped = false;}

}

// Prevents going beyond X coordinate of 0if (centerX + speedX Clean > OK).Figure 2-17: StartingClass.java, After Fixing character Errorspackage kiloboltgame;

import java.applet.Applet;import java.awt.Color;import java.awt.Frame;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.net.URL;

public class StartingClass extends Applet implements Runnable, KeyListener {

private Image image, character;private Graphics second;private URL base;

@Overridepublic void init() {

setSize(800, 480);setBackground(Color.BLACK);setFocusable(true);addKeyListener(this);Frame frame = (Frame) this.getParent().getParent();frame.setTitle("Q-Bot Alpha");try {base = getDocumentBase();} catch (Exception e) {// TODO: handle exception}

// Image Setupscharacter = getImage(base, "data/character.png");

}

@Overridepublic void start() {robot = new Robot();

Thread thread = new Thread(this);thread.start();}

@Overridepublic void stop() {// TODO Auto-generated method stub}

@Overridepublic void destroy() {// TODO Auto-generated method stub}

@Overridepublic void run() {while (true) {

repaint();try {Thread.sleep(17);} catch (InterruptedException e) {e.printStackTrace();}}}

@Overridepublic void update(Graphics g) {if (image == null) {image = createImage(this.getWidth(), this.getHeight());second = image.getGraphics();}

second.setColor(getBackground());second.fillRect(0, 0, getWidth(), getHeight());second.setColor(getForeground());paint(second);

g.drawImage(image, 0, 0, this);

}

@Overridepublic void paint(Graphics g) {g.drawImage(character, robot.getCenterX() - 61, robot.getCenterY() - 63, this);

}

@Overridepublic void keyPressed(KeyEvent e) {

switch (e.getKeyCode()) {case KeyEvent.VK_UP:System.out.println("Move up");break;

case KeyEvent.VK_DOWN:System.out.println("Move down");break;

case KeyEvent.VK_LEFT:System.out.println("Move left");break;

case KeyEvent.VK_RIGHT:System.out.println("Move right");break;

case KeyEvent.VK_SPACE:System.out.println("Jump");break;

}

}

@Overridepublic void keyReleased(KeyEvent e) {switch (e.getKeyCode()) {case KeyEvent.VK_UP:System.out.println("Stop moving up");break;

case KeyEvent.VK_DOWN:System.out.println("Stop moving down");break;

case KeyEvent.VK_LEFT:System.out.println("Stop moving left");break;

case KeyEvent.VK_RIGHT:System.out.println("Stop moving right");break;

case KeyEvent.VK_SPACE:System.out.println("Stop jumping");break;

}

}

@Overridepublic void keyTyped(KeyEvent e) {// TODO Auto-generated method stub

}

}II. Addressing the get... errorsWe still have these errors in our StartingClass:

In my previous description of the Robot class, I mentioned that we would be creating:

1. Constantly updated methods that are called on each iteration of the game loop.2. Methods that are only called upon player input.3. Helper methods that retrieve and change the value of variables in the class.

We never did create the helper methods. So here we do that.

1. Open Robot.java again.2. Right click anywhere on the white space, click Source >> and select Generate Getters and Setters.

3. Select all, sort by getters then setters, and then press OK.

What are getters and setters?Again, in Java, it is common practice to set class-wide variables asprivate. For other classes to access these private variables, they must use helper functions known as getters and setters.

Let's have a look at a pair:

public int getSpeedX() {return speedX;}

andpublic void setSpeedX(int speedX) {this.height = speedX;}

Whenever a getter method is called, it returns the value that you "get." When I say:myNewVariable = getSpeedX(), my new variable will get the value of speedX.

If I say:setSpeed(10);then my speedX will now have a value of 10.

With these three things finished, the result is:Figure 2-18: StartingClass.java After Fixing the get... Errorspackage kiloboltgame;

import java.applet.Applet;import java.awt.Color;import java.awt.Frame;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.net.URL;

public class StartingClass extends Applet implements Runnable, KeyListener {

private Robot robot;private Image image, character;private Graphics second;private URL base;

@Overridepublic void init() {

setSize(800, 480);setBackground(Color.BLACK);setFocusable(true);addKeyListener(this);Frame frame = (Frame) this.getParent().getParent();frame.setTitle("Q-Bot Alpha");try {base = getDocumentBase();} catch (Exception e) {// TODO: handle exception}

// Image Setupscharacter = getImage(base, "data/character.png");

}

@Overridepublic void start() {robot = new Robot();

Thread thread = new Thread(this);thread.start();}

@Overridepublic void stop() {// TODO Auto-generated method stub}

@Overridepublic void destroy() {// TODO Auto-generated method stub}

@Overridepublic void run() {while (true) {

repaint();try {Thread.sleep(17);} catch (InterruptedException e) {e.printStackTrace();}}}

@Overridepublic void update(Graphics g) {if (image == null) {image = createImage(this.getWidth(), this.getHeight());second = image.getGraphics();}

second.setColor(getBackground());second.fillRect(0, 0, getWidth(), getHeight());second.setColor(getForeground());paint(second);

g.drawImage(image, 0, 0, this);

}

@Overridepublic void paint(Graphics g) {g.drawImage(character, robot.getCenterX() - 61, robot.getCenterY() - 63, this);

}

@Overridepublic void keyPressed(KeyEvent e) {

switch (e.getKeyCode()) {case KeyEvent.VK_UP:System.out.println("Move up");break;

case KeyEvent.VK_DOWN:System.out.println("Move down");break;

case KeyEvent.VK_LEFT:System.out.println("Move left");break;

case KeyEvent.VK_RIGHT:System.out.println("Move right");break;

case KeyEvent.VK_SPACE:System.out.println("Jump");break;

}

}

@Overridepublic void keyReleased(KeyEvent e) {switch (e.getKeyCode()) {case KeyEvent.VK_UP:System.out.println("Stop moving up");break;

case KeyEvent.VK_DOWN:System.out.println("Stop moving down");break;

case KeyEvent.VK_LEFT:System.out.println("Stop moving left");b