Vous êtes sur la page 1sur 76

GAME DEVELOPMENT TUTORIAL: Day 1-1: Setting Up

09/16/2012
61 Comments


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?

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)" , click Download below 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 on My Computer (or Computer), properties, and
you should see your type next to System type.

3. 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 Standard will 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.
_______________________________________________
GAME DEVELOPMENT TUTORIAL: DAY 1-2: Java Basics
09/16/2012
51 Comments


Welcome to Day 2 of Kilobolt's Android 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 to Window > Open Perspective > Other and
select Java.


2. Look at the bottom panel. If you see a Console tab, move on.
If not, go to Window > 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. Press File > 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:

__________________________________________________
src is 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 ==
1
.

1
Question
What's the difference between = & ==?
Answer

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.

One of the most common programming mistakes that one can make is to confuse the equal sign (=) with a double
equal signs (==). While experienced programmers can still make the same mistake, knowing the difference between
the two is a good way to avoid it. When we wish to assign a value to a variable or member, we use the equals sign
(=). As an example, the following would assign the value of three to the variable a.
a = 1 + 2; // assignment operation
When we wish to make a comparison, such as in an if statement, we use the double equals sign (==). A simple
example would be the following
if ( a == b ) then System.out.println ("Match found!");
Now consider what would have happened if we used an assignment operator instead. A would be assigned the value
of B - destroying the current contents of A and giving us an incorrect comparison. Finding this type of error can be
difficult, because the two operators look so similar. So why does Java use such confusing operators? Java draws its
roots from C, which shares the same problem. Unfortunately, its something that all Java programmers must learn to
live with.


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 body
3. }

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 theHelloWorld object 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, but int, so that the method can return an int value
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(type argumentName)

This above method is called "methodTwo" and requires an argument of the declared type (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 Body
5. }
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
the dot 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, and like us on Facebook!
GAME DEVELOPMENT TUTORIAL: DAY 1-3: More Basics
09/16/2012
34 Comments


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 three fields (also called variables) that I've created are: an integer variable called weight, a
boolean variable called turnedOn, and a String object called color.
Today, we will discuss these in detail.

There are four kinds of 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 is TAKES THE VALUE OF 2.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 a LOCAL 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 gets
reached 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!
GAME DEVELOPMENT TUTORIAL: DAY 1-4: Java Math
09/16/2012
111 Comments


Lesson #1-6: Fun(?) with Math
Not 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 few arithmetic 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 the src folder 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 the blahBlahBlah(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... are invoking the 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 follow
the 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 will
round 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 time discussing 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:

3. Let's talk about this:

You are familiar with System.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 displayed
using System.out.println();

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

"Result counter is output"


And we will conclude Day 4 here. :D

Thanks for reading!
Confused? Comment below.
September 16th, 2012
02/11/2014
16 Comments


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 is now equal to 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 is now equal to 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
use randomization.
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 class named Randomization, we create a Random object called rand.
Let's break up this statement:

think of this just like:

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

The second part of the statement:

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

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();

}

}
You will see red squiggly lines 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 the src folder contains all your Java code and that the JRE System
Library contains importable code that 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 by importing.
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 importing
the 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 over probability and if statements tomorrow!

If you have any questions, please post on the Forum!

If you are learning from and enjoying the tutorials, please support Kilobolt Studios!
And Like us on Facebook to receive updates when a new lesson is posted!
GAME DEVELOPMENT TUTORIAL: DAY 1-6: If... else...
09/16/2012
55 Comments


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:

Meet the if 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 are met, 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 are mutually 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.
import java.util.Random;

//Let's simulate a coin toss!
public class Simulation {
public static void main(String[] args){

Random rand = new Random();

int result = rand.nextInt(2);

if (result == 0){
System.out.println("heads");
}

else if(result == 1){
System.out.println("tails");
}

else if(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 of result using else if statements (mutually exclusive events) and display the
appropriate string (text).

Since the value of result should never (theoretically) be 3, I created a third statement that is only
read if result does 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
mean simple.
Before we do that, here's a quick lesson on conditional operators:

When you have an if statement like below:

Then if either conditionOne or conditionTwo is true, it will invoke the "doThis()" method;

When you have a statement like this:

Then both conditionOne 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 <= 2) {
System.out.println("You Lose.");
} // ends if

else if (dieValue == 3 || dieValue == 4 || dieValue == 5) {
System.out.println();
System.out.println("Rerolling.");
System.out.println();
rollDie();
} // ends else if

else if (dieValue == 6) {
System.out.println("You win! Congratulations!");
} // ends else if

} // ends testDieValue()

} // ends BySimpleIMeanSimple Class
I want you to spend time with this class. Copy and paste it into eclipse and play around with it.
We will discuss this class in detail in tomorrow's lesson!

You might be surprised by what you have already learned!

A tip: if you don't know what the purpose of a certain line of code is, it is a good idea to remove it
temporarily (comment it out and run it). You can compare results with and without the statement =)
You can also modify the code and see how it works differently.

If you have any questions:
Comment below!
GAME DEVELOPMENT TUTORIAL: DAy 1-7: More Ctrl.
Flow
09/16/2012
35 Comments


Lesson #1-12: Analysis of the BySimpleIMeanSimple class

Looking at yesterday's "game" in-depth.

Yesterday, we created our very first game. Now we will dissect the class behind it.

Here's the code:
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 <= 2) {
System.out.println("You Lose.");
} // ends if

else if (dieValue == 3 || dieValue == 4 || dieValue == 5) {
System.out.println();
System.out.println("Rerolling.");
System.out.println();
rollDie();
} // ends else if

else if (dieValue == 6) {
System.out.println("You win! Congratulations!");
} // ends else if

} // ends testDieValue()

} // ends BySimpleIMeanSimple Class
1. The first line is simple: import the Random class.
2. We then declare the name of the class: BySimpleIMeanSimple
3. Then a static integer called dieValue, which will hold the value of the rolled die is created
4. Next, we create the main method, which just invokes a method called rollDie();

5. The rollDie() method is then created. It has the following parts.

I. Creation of the Random object called rand.
II. Assignment of a random number between 0 and 5 (+1 since numbers range from 1 to 6 on a die)
to the dieValue integer we created earlier.
III. It uses System.out.println to display the value of the integer dieValue.
IV. It invokes the method testDieValue(), which is defined below the rollDie() method. This
testDieValue() method requires an integer parameter, so we input the new dieValue, which contains
the random number between 1 and 6.

6. Next we declare the testDieValue() method. This is where the Control Flow statements happen
(we control the way that the program proceeds based on conditional statements).
It takes the value of integer dieValue and then carries out the appropriate if statement.

I. If the value is less than or equal to 2, the player loses, so it displays, "You lose."
II. If the value is exactly 6 (==), it displays "You Win! Congratulations!"
III. If the value is 3 or 4 or 5 (This could've been written in many ways, such as: if (dieValue >= 3 &&
dieValue <= 5)...), it rerolls, invoking again the rollDie() method, which creates a random number and
assigns it as the value of dieValue and then uses this value to invoke the testDieValue();

Someone asked earlier, what is the purpose of the: System.out.println();
Well, it is there to create an empty line in the console (where the output is displayed). It helps
organize the way the program "speaks" to you.

NOTE: Make sure you are keeping up with the braces. When you do actually programming,
braces won't be color coded to show you where the boundaries of each class or method are!

Lesson #1-13: Switches in Java

Java, much like railroad tracks, incorporates switches to direct the path of execution.
We will look at switches using an example that we have used before: a coin toss.

NOTE: Make sure that the class name in the Package Explorer to the left side of the screen on
Eclipse matches that of the one stated in the code. Otherwise, you will get an error. The reason for
this is that when you press Play, Eclipse looks for the class that with the name of the file that you are
executing, and it will not be able to locate it.

(i.e. You should create a class named CoinTossSwitch.java and copy this code):
import java.util.Random;

class CoinTossSwitch {

public static void main(String[] args) {

Random rand = new Random();
int randomInt = rand.nextInt(2);

System.out.println(randomInt);

switch(randomInt) {

case 0:
System.out.println("Tails!");
break;
case 1:
System.out.println("Heads!");
break;

} // Ends switch

} // Ends main

} // Ends Class
Let's examine the switch in detail:
switch (randomInt) {

case 0:
System.out.println("Tails!");
break;
case 1:
System.out.println("Heads!");
break;

} // Ends switch
As you can tell, the format of a switch is as follows :
switch (variable){

case 1: // if variable == 1
doThis();
break;

case 2: // if variable == 2
doThat();
break;

case 3:
doOther();
break;

case 4: case 5: case 6: // if variable == 4, 5 or 6
doSomethingElse();
break;

default:
doDefault();
break;
}

Inside the parentheses (), you write the variable name that you are testing.
If this variable is an integer, you write:

case 1, case 2, and so on (You can combine cases and include a default case for all other cases).

If it is is a boolean, you would write:

case true, case false.

If it is a String, you would write whichever values that the String variable can take.
For example, if your String can contain any color value, you would use:

case "red", case "blue", and so on.

The purpose of the "break;" is to separate the cases. If you forget to put the break, the code will not
stop executing after a case is satisfied. It will keep going. Break can also be used to end loops
(which we will discuss in the coming lessons).

__________

Applying this to the example code above,

1. We are testing an integer called randomInt.
2. If randomInt is 0, the computer will output: "Heads!" and break the case.
3. If randomInt is 1, the computer will output: "Tails!" and break the case.

What would be a practical application of this code? Let's say that we have a game in which the
player can select one of three characters.
Let's name them Mario, Luigi, and Yoshi.

We would then create a String variable that holds the value of the name, and then use a switch to
carry out the appropriate response.

Note: The following will only work in Java 1.7. On Java 1.6 and below, we would use integers to
represent our characters, like in the example at this link.
//Sample Character Selection Screen

class CharacterSelect {

public static void main(String[] args) {

String currentCharacter = "Mario";

int maxLife;
int maxJump;
int maxSpeed;

switch (currentCharacter) {

case "Mario":
System.out.println("You have selected Mario!");
maxLife = 70;
maxJump = 50;
maxSpeed = 25;
break;

case "Luigi":
System.out.println("You have selected Luigi!");
maxLife = 40;
maxJump = 70;
maxSpeed = 30;
break;

case "Yoshi":
System.out.println("You have selected Yoshi!");
maxLife = 50;
maxJump = 30;
maxSpeed = 40;
break;

}

}

}
We store the current character's value in the String variable currentCharacter and use a switch to
change the character's attributes.


Tomorrow we will discuss looping. We are getting closer to developing a game, so hang tight and
stay tuned!

If you want to thank me for the guide, you can donate here or download TUMBL +!

Thank you guys for reading and I'm here if you have any questions!
GAME DEVELOPMENT TUTORIAL: DAY 1-8: Looping
09/16/2012
16 Comments


Lesson #1-14: Introduction to Loops

In the previous lessons, we discussed conditional statements (such as the if statement) that carry
out an appropriate response depending on the condition satisfied.

We will now begin covering loops, which are also often conditionally executed.

First, what is a loop? Well, as the name suggests, loops refer to code that is executed multiple
times.

When is a loop useful?
A very simple scenario: if you wanted to output a specific line of text a hundred times.
One solution to this would be to copy and paste the System.out.println(...) statement 100 times.

This is not very efficient for both the programmer and the computer.
Instead, the proper solution would be to utilize a loop and a counter to execute one line of
System.out.println(...) 100 times.

A more practical (and relevant) example is the game loop. We will have a hefty discussion about this
crucial loop later, but here's a little preview of what is coming.

You will soon discover that games are very mechanical in nature. Behind the fancy graphics and
beautiful sounds, there is a "heart" that causes the game to "update" its contents (move all in-game
objects to the new location based on their velocity) and to render the graphics (re-draw the objects in
the newly defined location). The game loop is the closest thing to this heart.

Like I said before, loops tend to be conditional. The game loop is too.

Here's an example of a fake game loop.
while (playerAlive == true){

updateGame(deltaTime);
renderGame(deltaTime);

}
In this example of the while loop, if the condition playerAlive == true is satisfied, the updateGame()
method and the renderGame() method will be executed.

The updateGame() method will handle things like collision or physics, while renderGame() method
will display the characters and environment in the current location.

I added a deltaTime parameter to the methods, which is typically the number of nanoseconds that
have passed since the previous execution of the loop. I'll explain why, although this might not have
any meaning to you until you actually start game programming.

Processors, especially those found on modern mobile devices, are erratic; the speed at which the
loop is executed varies.

Why is this a problem? Let's say that updateGame() method moves a character right by 5 pixels.
Now consider what would happen if updateGame() was not run at equal intervals. If the game
slowed down and the loop took double the amount of time to execute again, the character would
move at half speed. This would be disastrous for even a simple game like Temple Run.

So what a lot of game developers do is this. Instead of moving 5 pixels, the character would move 5
pixels MULTIPLED BY the amount of time that elapsed since the last execution of the loop (which
we can define as deltaTime). This means that no matter how much the processor slows down, the
character will always travel at the same speed.

Enough with the theory. Let's meet the first loop!

Lesson #1-15: The While Loop

We saw a quick example of a while loop above. Let's discuss it in a little more depth.

The while loop will continue to execute as long as the condition is satisfied.
Take a look at this example:
while (earthIsSpinning){
//The compiler will read this as:
//earthIsSpinning == true

System.out.println("The earth is still spinning.")


}
If this was an actual program, it would just flood your console as fast as the computer is capable of
with the sentence "The earth is still spinning." At least for the predictable future.

We rarely want programs that run forever (unless you are running the Matrix).
So how do you end a while loop?
Simple. When the loop is executed to your satisfaction, you change the variable earthIsSpinning to
false so that the condition is no longer satisfied. Then the loop will terminate.

A full class example follows:
public class Looping {

public static void main(String[] args) {

boolean earthIsSpinning = true;
int counter = 0;

while (earthIsSpinning) {
System.out.println("The earth is still spinning.");
System.out.println(counter);
counter++;

if (counter >= 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 integer counter.
3. We add 1 to counter's value.

An if statement is contained 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 the counter integer, 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,
when counter is 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 calling break; 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 or donate here or download TUMBL
+!
GAME DEVELOPMENT TUTORIAL: DAY 1-9: More on
Looping
09/16/2012
34 Comments


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 to analyze:

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 the for loop which
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 <11; variable++){
System.out.println("Count is: " + variable;
}
}
}
The output would be:

The for loop is quite simple:

The first part of the for (...) is the initialization of a variable.
We initiate an integer called variable, with the value of 1.

The second part "variable <11" is the condition. Think of this as: while (variable < 11)...
Everything inside the for loop will run as long as this second part is satisfied.

The third part "variable++" is what happens to the initialized variable after each iteration. We
increase it by one.


Lesson #1-18: Applying the For Loop

In this lesson, we will recreate the Looping program using not the while loop, but the for loop!

Have a look at the while loop example again:
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.");
}

}
}
We can safely remove all the counter variable related statements, as the for loop will handle that for
us.
The only other segment of code we need to modify is the while loop section.

We will replace this with the for loop :
public class ForLooping {
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++;

for (initialValue = 1; initialValue < finalValue + 1; initialV
alue++) {
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 {
System.out.println("Final value is less than initial value!");
System.out.println("Please choose new values.");
}

}
}
Remember to change the name of the class (Select it on the left side of the screen in the Package
Explorer, use F2) before running the code!

Also, this code is not color coded. Try to keep track of what each pair of braces contain. An easy
way to do this is to start from the highest level and go deeper into the code: (Class, main method, if
statement, for loop, if statement). The indentations should help you discern which braces
correspond.

If you need help, refer to the previous class "Looping." It is mostly similar.
Also if you copy and paste this into Eclipse, you can click next to a curly brace and Eclipse will draw
a small rectangle on its counterpart to make it easier to tell.

Ctrl + Shift + F automatically indents your code for you! Use that well.


The output:

Using the for loop is another way to do the same work!

This concludes Day 9.
GAME DEVELOPMENT TUTORIAL: DAY 1-10: Inheritance,
Interface
09/16/2012
33 Comments


Welcome to Day 10, Unit 1's penultimate lesson!

This is the beginning of the end of the Basic Java unit.
With that said, you will still be learning Java throughout the future Units, so keep your minds open
and ready to learn!

In this lesson, we will be discussing inheritance and interfaces (not in extensive detail, as they will
come up frequently in future Units and it is easiest to understand them as you manipulate them
yourself).

Since this lesson is the culmination of the previous lessons in the Unit, we will be applying much of
what we learned previously.

If you need to refresh your memory, refer to the previous lessons!

Let's get started!

Lesson #1-19: Interfaces

If you've ever seen highly functional Java code, you might notice something like this in the class
declaration:
public class ClassName implements InterfaceName {
... //implemented methods
}
This line of code creates a class named ClassName and declares that it implements the interface
named InterfaceName.

Yeah, that's quite a mouthful... so you can think of it this way.

An interface is a collection of abstract (meaning that it's not really used, but it's just there as a
reference) methods and constants that define a group.

If a class implements this interface, then it chooses to take on all the abstract methods and
constants.

For example, let's say we have an interface called Human as below:
public interface Human {

public void eat();
public void walk();
public void pee();

}
The interface is some thing of a contract. If we create an interface, we are telling people, "Hey, you
can be a Human if you do the following..."

Notice that an interface does not have method bodies. Instead, we simply declare what methods we
need for something to be "Human", and we leave them blank. Each implementation of Human can
choose how they want to approach the eat, walk and pee methods.

Here's an example:
I am implementing Human (that is, accepting its three requirements) in the class King:
public class King implements Human {

public void eat() {
System.out.println("The King eats.");
}

public void walk() {
System.out.println("The King walks.");
}

public void pee() {
System.out.println("The King urinates.");
}
}
When class King implements interface Human, the class is basically saying, "I will eat, walk, and
pee. Please make me Human."

In other words, King is saying that, first and foremost, he is Human.

When you implement an interface in a Class, you must implement (or finish) everything you have
stated in the interface. That means the King cannot remove the pee() method from his Class
because he is, after all, only human.

You can add as many Interfaces to King as you want, such as "Male" and "Royalty". Then, you can
use the King object in any method that requires a King or Human or Male or Royalty input, such as:
// You can pass in a King object into this method.
public void doSomething(Human h) {
// do something
}
This is called polymorphism. You will see the power of polymorphism throughout this tutorial series.


Lesson #1-20: Inheritance

This is a very similar topic to interfaces.

The key difference is that inheritance deals with two classes, not a class and an interface.
Another key difference is that inheritance uses the keyword "extends" rather than "implements."

So how is "extends" different from "implements?"

Recall that when you implement an interface, you must take all the abstract qualities of the interface
and implement it into the Class that is implementing it.

Not so when a class extends another class, which we refer to as a Superclass, and the extending
class is called asubclass.

A class is a blueprint for objects, as I have repeated over and over again.
A superclass is a blueprint for other classes.

In inheritance, we take an abstract concept, like Phone, and create a class which will hold all the
shared properties of all Phones. Then, we can use this as a blueprint to create more specialized
objects, such as the iPhone class or the GalaxyS class.


Let's have a look at an example:
// This is the 'generic' superclass

class Phone {

// Phone class variables
int weight = 10;
int numProcessingCores = 4;
int price = 200;
boolean turnedOn = false;

public void togglePower() {
// turnedOn is now its opposite (true becomes false, and vice versa)
turnedOn = !turnedOn;
}
}
This superclass holds all the information that all phones should have, such as weight, number of
cores, price and etc. Using this superclass, we can create a subclass, which will (this is key) ADD
ITS OWN UNIQUE PROPERTIES to the GENERIC properties described in the superclass (meaning
that iPhone below will have all the methods and variables in the Phone method and also its own
methods and variables):
public class iPhone extends Phone {

boolean hasAppleLogo = true;
String color = "black";

void adjustPrice() {
if (hasAppleLogo) {
// Although we did not declare a price variable in this class
// we have inherited a copy of it from the Phone class.
price += 4500;
}
}
}
Now the class iPhone will be able to use all the methods and constants defined in the superclass
Phone... and add its own methods (like adjustPrice())

Now the class iPhone will be able to use all the methods and variables defined in the superclass
Phone... and add its own methods (like adjustPrice())

Polymorphism also works with inheritance.

Let's say we have a Hammer class:
public class Hammer {

public boolean destroy(Phone p) {
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM");
}

}
Its destroy method can destroy any Phone, and any other Object that extends Phone. Here's how
you might do that.
public class Hammer {

public boolean destroy(Phone p) {
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM");
}

public static void main(String[] args) {
Hammer h = new Hammer(); // Create new hammer object
Phone phone = new Phone(); // Create new Phone object
iPhone phone2 = new iPhone(); // Create new iPhone object

h.destroy(phone); // Destroy Phone object
h.destroy(phone2); // Destroy iPhone object (POLYMORPHISM!)
}

}
The destroy method does not have to be static, because we are using an instance of the Hammer
class, named h, to call the destroy method. If we didn't want to create a specific Hammer to destroy
things, we would make the destroy method static, and call:

Hammer.destroy(...);

Not an extremely long lesson, but this is a very important one. Read through it thoroughly!
One more thing...

If each of you told your friends about this tutorial and asked them to like us on Facebook, it would
help us out tremendously.

Take the time to support Kilobolt! :D
GAME DEVELOPMENT TUTORIAL: DAY 1-11: Threads and
Graphics
09/16/2012
77 Comments

Welcome to the final lesson of Unit 1 of our Game Development Tutorial Series.
If you have stuck with me this far, you have taken a small step that will become a giant leap for your
game development career.

Before we continue, I'd like to ask you once more to support Kilobolt! These lessons are offered to
you free-of-charge, but it costs us real money from our pockets to maintain this website and our
Dropbox.

So if you could support us by:

1. Downloading TUMBL+ from the Play Store
2. Sending us a little donation
3. Liking us on Facebook
4. Linking to us on your blog or website

It would help us a lot! Really!

Or if you are unable to do any of these things, just tell your friends about us or put up a link to our
site on your website, blog, or whatever!

Thank you so much for being a Kilobolt supporter!
We will continue to deliver high-quality content to you, and hopefully you guys will learn a lot from us!

Let's begin!

Lesson #1-21: Threads

So far in Java, we have followed a simple and general rule: when you press the Run button, the
program runs line by line from top to bottom (unless it is looping).

When you start game development, however, you may realize that you require simultaneous
processes for your game to work.

This is where a Thread comes in handy.

As the word thread may suggest, a thread is a single, lightweight process. When you have multiple
threads, these processes are carried out simultaneously.

How do we create a thread?

The method is similar to how we would create a random object.

To create a random object, we used the code:

Random random = new Random();

To create a Thread, we do the following:

Thread thread = new Thread();

This creates a new Thread object called "thread."

Unlike random objects, however, creation of thread objects is a bit more lengthy process.

Threads require a built-in "run()" method, and we will incorporate it directly into the statement above.

Example 1: Threads
1. We begin like so, adding braces to the end of the statement:

Thread thread = new Thread(){ };


2. These braces will contain the run method (which is, again, REQUIRED for a
thread). I know this is new for you guys, so just try to apply your knowledge of
hierarchy in code when you examine this next part:

Thread thread = new Thread(){
public void run () {

}

};


3. When you want this thread to start, you would type a built-in Java function
(meaning that it is already defined by the language when used with a
thread: .start();

thread.start();


4. When thread is started by .start(); it looks for the thread's run method and
begins to run the lines of code there. At the moment, it is empty, so we will
add a few lines of code to the run method:

Thread thread = new Thread(){
public void run () {
for (int i = 0; i < 10; i += 2){
System.out.println("hello");
}
}

};


5. And now when we execute the thread with: thread.start(); we will see:

Output:
hello
hello
hello
hello
hello


6. Now threads would be useless by themselves, so we will create another
one. Here is what the full code will look like! To run this thread on your own
eclipse, create a Class file called ThreadDemo and copy and paste.
public class ThreadDemo {
public static void main(String args[]) {

// This is the first block of code
Thread thread = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread one");
}
}

};

// This is the second block of code
Thread threadTwo = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread two");
}
}

};

// These two statements are in the main method and begin the two
// threads.
// This is the third block of code
thread.start();

// This is the fourth block of code
threadTwo.start();
}

}


Let's now discuss step by step what happens when you run this code. Of course, as with all Java
Programs, when this class is run, it will look for the main method. The main method contains 4 main
blocks of code (indicated above with comments //).

The first one creates a Thread called thread and defines its run method. The second one creates a
thread called threadTwo and defines its run method. The third one starts Thread thread, and the
fourth one starts Thread threadTwo.


Output:
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two

Hold on. I mentioned that a thread allows simultaneous processes. Why didn't it alternate between
thread one and thread two?


We will discuss this in Unit 2. Stay tuned! :)
Lesson #1-22: Graphics

Nobody likes programs running on a shell like DOS (on second thought, I know a few people who
enjoy showing off on Command Line). Most people like GUI's (graphical user interface) that they can
interact with. Functionality is important, but interfaces are sometimes even more important.

We now begin our discussion of graphics. There is so much to talk about in graphics, so we will just
touch upon a few statements that allow us to display graphics.

Note*: When I use the word graphics, I am referring to a digital image and not to game graphics, so
keep that in mind!

In this lesson, we are first going to create a window, which can display images, and then try
displaying some graphics on that.

To start, create a class called GraphicsDemo in Eclipse. This can be done by right clicking on
the src folder of a project (in the package explorer to the left), selecting New >> 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 the previous lesson.
To display images, we must extend the superclass JFrame like so:

public class GraphicsDemo extends JFrame{

}

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

Shortcut: Ctrl + Shift + O
Alternate: 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:
GraphicsDemo demo = 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 be demo.

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 the JFrame 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. setTitle sets the title of the window
when it is opened. The second statement setSize sets the resolution in pixels of the
window. setVisible ensures 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...
Add import 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: The g. 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 width witdh and
height height.

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 widthwidth and height height.

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...

Vous aimerez peut-être aussi