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 2-3: Taking User Input

10/9/2012

58 Comments

 
Picture
Lesson #2-6: Implementing KeyListener


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

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


So let's get started by implementing the KeyListener.

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


public class StartingClass extends Applet implements Runnable{

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

public class StartingClass extends Applet implements Runnable, KeyListener{


2. When you add this, Java will give you an error saying "KeyListener cannot be resolved to a type". To resolve this error, just import KeyListener.
Picture
You need to import KeyListener before you can implement the interface.
3. You will now see an error: "The type StartingClass must implement the inherited abstract method KeyListener.keyReleased(KeyEvent)."

Recall that when you implement an interface, you must take all of its methods and declare them in your class. So you can easily resolve this by choosing: Add unimplemented methods.
Picture
To implement an interface, you must make use of all of its methods.
4. Adding unimplemented methods will do two things: First, it will add the three methods: keyPressed(), keyReleased(), and keyTyped() to your code. These three methods require a KeyEvent object as a parameter. Java is smart enough to import KeyEvent for you. 

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



The resulting code is as follows:

Figure 2-10: StartingClass.java

package kiloboltgame;

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


public class StartingClass extends Applet implements Runnable, KeyListener{

   @Override
   public void init() {

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

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

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

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

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

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

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

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

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

}
The first two methods are self-explanatory. keyTyped is slightly more complicated, but you can learn more about it here: http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/event/KeyEvent.html

Lesson #2-7: Listening for Key Presses
In our 2D-platformer, we will need at least five buttons to start. The four directional arrows will each be a button, and for now we will use the Space Bar for jump.

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

@Override
public void keyPressed(KeyEvent e) {

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

   case KeyEvent.VK_DOWN:
   break;

   case KeyEvent.VK_LEFT:
   break;

   case KeyEvent.VK_RIGHT:
   break;

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

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

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

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

   case KeyEvent.VK_DOWN:
      break;

   case KeyEvent.VK_LEFT:
      break;

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

   }
}
At the present, we have no character to actually move or stop. Therefore, we will just output some text to the console like so:

Figure 2-12: StartingClass.java, End of Day 3

package kiloboltgame;

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

public class StartingClass extends Applet implements Runnable, KeyListener {

    @Override
    public void init() {

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

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

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

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

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

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

    @Override
    public void keyPressed(KeyEvent e) {

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

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

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

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

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

        }

    }

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

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

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

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

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

        }

    }

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

    }

}

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

Thanks for following my tutorials, and let me know if I can help you in any way!
Picture
KiloboltGame - Day 3
File Size: 3 kb
File Type: zip
Download File

Instructions on importing projects can be found here.
Picture
Go to Day 2: Basic Framework
Go to Day 4: Enter the Robot
58 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.