Kilobolt
  • Home
  • Tutorials
    • Game Development Tutorial >
      • Unit 1: Beginning Java >
        • Before you begin...
        • Day 1: Setting Up
        • Day 2: Java Basics
        • Day 3: More Basics
        • Day 4: Java Math
        • Day 5: More Math
        • Day 6: If... else...
        • Day 7: More Control Flow
        • Day 8: Looping
        • Day 9: More on Looping
        • Day 10: Inheritance, Interface
        • Day 11: Threads and Graphics
      • Unit 2: Creating a Game I >
        • Day 1: Foundations
        • Day 2: Basic Framework
        • Day 3: Taking User Input
        • Day 4: Enter the Robot
        • Day 5: Background and Sprites
        • Day 6: Adding Enemies
        • Day 7: Shooting Bullets
        • Day 8: Animations
        • Day 9: 2D-Arrays
        • Day 10: Painting the Tilemap
      • Unit 3: Creating a Game II >
        • Day 1: Level Creation - Part 1
        • Day 2: Level Creation - Part 2
        • Day 3: Level Creation - Part 3
        • Collision Detection Basics
        • Day 4: Collision Detection Part 1
        • Day 5: Collision Detection Part 2
        • Day 6: Collision Detection Part 3
        • Day 7: Health System & Death
        • Day 8: Basic AI & Final Touches
      • Unit 4: Android Game Development >
        • Day 1: Introduction to Android
        • Day 2: Setting up for Development
        • Day 3: Creating our First Android Application
        • Day 4: Parts of an Android Application
        • Day 5: The Android Game Framework: Part I
        • Day 6: The Android Game Framework: Part II
        • Create an Android Game From Scratch (or port your existing game)
        • Day 7: Creating an Android Game (From Start to Finish)
      • Reference Sheet
    • Zombie Bird Tutorial (Flappy Bird Remake) >
      • Unit 1: Building the Game >
        • Introduction
        • Day 1: Flappy Bird - An In-depth Analysis
        • Day 2: Setting up libGDX
        • Day 3: Understanding the libGDX Framework
        • Day 4: GameWorld and GameRenderer and the Orthographic Camera
        • Day 5: The Flight of the Dead - Adding the Bird
        • Day 6: Adding Graphics - Welcome to the Necropolis
        • Day 7: The Grass, the Bird and the Skull Pipe
        • Day 8: Collision Detection and Sound Effects
        • Day 9: Finishing Gameplay and Basic UI
        • Day 10: GameStates and High Score
        • Day 11: Supporting iOS/Android + SplashScreen, Menus and Tweening
        • Day 12: Completed UI & Source Code
    • Android Application Development Tutorial >
      • Unit 1: Writing Basic Android Apps >
        • Before you begin...
        • Day 1: Android 101
        • Day 2: Getting to Know the Android Project
        • Day 3: The Development Machine
        • Day 4: Building a Music App - Part 1: Building Blocks
        • Day 5: Building a Music App - Part 2: Intents
        • Day 6: Building a Music App - Part 3: Activity Lifecycles
  • New Forum
  • About Us
    • Contact Us
  • Our Games
    • TUMBL: FallDown
  • Facebook
  • Twitter

GAME DEVELOPMENT TUTORIAL: DAY 1-2: Java Basics

9/16/2012

69 Comments

 
Picture
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:
Picture
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. 
Picture
Picture
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.
Picture
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.
Picture
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: 
Picture
__________________________________________________
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!)
Picture
6. Hopefully you will see this screen! 
Picture
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: 
Picture
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 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 the HelloWorld 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!
Go to Day 1: Setting Up
Go to Day 3: More Basics
69 Comments

    Author

    James Cho is the lead developer at Kilobolt Studios. He is a college student at Duke University and loves soccer, music, and sharing knowledge. 


© 2014 Kilobolt, LLC. All rights reserved.