In this part of my Java video tutorial, I create the spaceship object and a keyboard listener. I will use the keyboard listener to move the ship around the screen.
It is so easy to randomly add objects to the game we started making here Make a Java Video Game. I slowed things down a bit here, just to make sure you completely get the process.
All of the code is available under the video. Please feel free to ask questions.
If you like videos like this, telling Google helps [googleplusone]
Sharing is always appreciated
Code From the Video
GAMEBOARD.JAVA
// Layout used by the JPanel import java.awt.BorderLayout; // Define color of shapes import java.awt.Color; // Allows me to draw and render shapes on components import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; // Will hold all of my Rock objects import java.util.ArrayList; // Runs commands after a given delay import java.util.concurrent.ScheduledThreadPoolExecutor; // Defines time units. In this case TimeUnit.MILLISECONDS import java.util.concurrent.TimeUnit; import javax.swing.JComponent; import javax.swing.JFrame; public class GameBoard extends JFrame{ // Height and width of the game board public static int boardWidth = 1000; public static int boardHeight = 800; public static void main(String [] args) { new GameBoard(); } public GameBoard() { // Define the defaults for the JFrame this.setSize(boardWidth, boardHeight); this.setTitle("Java Asteroids"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode()==87) { System.out.println("Forward"); } else if (e.getKeyCode()==83){ System.out.println("Backward"); } } }); GameDrawingPanel gamePanel = new GameDrawingPanel(); // Make the drawing area take up the rest of the frame this.add(gamePanel, BorderLayout.CENTER); // Used to execute code after a given delay // The attribute is corePoolSize - the number of threads to keep in // the pool, even if they are idle ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5); // Method to execute, initial delay, subsequent delay, time unit executor.scheduleAtFixedRate(new RepaintTheBoard(this), 0L, 20L, TimeUnit.MILLISECONDS); // Show the frame this.setVisible(true); } } // Class implements the runnable interface // By creating this thread we can continually redraw the screen // while other code continues to execute class RepaintTheBoard implements Runnable{ GameBoard theBoard; public RepaintTheBoard(GameBoard theBoard){ this.theBoard = theBoard; } @Override public void run() { // Redraws the game board theBoard.repaint(); } } @SuppressWarnings("serial") // GameDrawingPanel is what we are drawing on class GameDrawingPanel extends JComponent { // Holds every Rock I create public static ArrayList<Rock> rocks = new ArrayList<Rock>(); // Get the original x & y points for the polygon int[] polyXArray = Rock.sPolyXArray; int[] polyYArray = Rock.sPolyYArray; // Create a SpaceShip SpaceShip theShip = new SpaceShip(); // Gets the game board height and weight int width = Lesson50.boardWidth; int height = Lesson50.boardHeight; // Creates 50 Rock objects and stores them in the ArrayList public GameDrawingPanel() { for(int i = 0; i < 10; i++){ // Find a random x & y starting point // The -40 part is on there to keep the Rock on the screen int randomStartXPos = (int) (Math.random() * (Lesson50.boardWidth - 40) + 1); int randomStartYPos = (int) (Math.random() * (Lesson50.boardHeight - 40) + 1); // Add the Rock object to the ArrayList based on the attributes sent rocks.add(new Rock(Rock.getpolyXArray(randomStartXPos), Rock.getpolyYArray(randomStartYPos), 13, randomStartXPos, randomStartYPos)); } } public void paint(Graphics g) { // Allows me to make many settings changes in regards to graphics Graphics2D graphicSettings = (Graphics2D)g; // Draw a black background that is as big as the game board graphicSettings.setColor(Color.BLACK); graphicSettings.fillRect(0, 0, getWidth(), getHeight()); // Set rendering rules graphicSettings.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Set the drawing color to white graphicSettings.setPaint( Color.WHITE); // Cycle through all of the Rock objects for(Rock rock : rocks){ // Move the Rock polygon rock.move(); // Stroke the polygon Rock on the screen graphicSettings.draw(rock); } theShip.move(); graphicSettings.draw(theShip); } }
SPACESHIP.JAVA
import java.awt.Polygon; @SuppressWarnings("serial") public class SpaceShip extends Polygon{ // Upper left hand corner of space ship int uLeftXPos = 500, uLeftYPos = 400; // Determines the direction the ship moves int xDirection = 0; int yDirection = 0; // Get the board width and height int width = GameBoard.boardWidth; int height = GameBoard.boardHeight; // Will hold the x & y coordinates for the ship public static int[] polyXArray = {500,527,500,508,500}; public static int[] polyYArray = {400,415,430,415,400}; // Creates a new space ship public SpaceShip(){ // Creates a Polygon by calling the super or parent class of Rock Polygon super(polyXArray, polyYArray, 5); } public void move(){ // Get the upper left and top most point for the Polygon // This will be dynamic later on int uLeftXPos = super.xpoints[0]; int uLeftYPos = super.ypoints[0]; // If the ship hits a wall it will go in the opposite direction if (uLeftXPos < 0 || (uLeftXPos + 25) > width) xDirection = -xDirection; if (uLeftYPos < 0 || (uLeftYPos + 50) > height) yDirection = -yDirection; // Change the values of the points for the Polygon for (int i = 0; i < super.xpoints.length; i++){ super.xpoints[i] += xDirection; super.ypoints[i] += yDirection; } } }
ROCK.JAVA
import java.awt.Polygon; import java.awt.geom.Rectangle2D; import java.util.ArrayList; // Extending the Polygon class because I'm drawing Polygons class Rock extends Polygon{ // Upper left hand corner of the Polygon int uLeftXPos, uLeftYPos; // Used to change the direction of the asteroid when // it hits something and determines how fast it moves int xDirection = 1; int yDirection = 1; // Define rock height and width int rockWidth = 26; int rockHeight = 31; // Copy of the Rock ArrayList // Holds every Rock I create static ArrayList<Rock> rocks = new ArrayList<Rock>(); // For JApplet // int width = ExampleBoard.WIDTH; // int height = ExampleBoard.HEIGHT; // Get the board width and height int width = GameBoard.boardWidth; int height = GameBoard.boardHeight; // Will hold the x & y coordinates for the Polygons int[] polyXArray, polyYArray; // x & y positions available for other methods // There will be more Polygon points available later public static int[] sPolyXArray = {10,17,26,34,27,36,26,14,8,1,5,1,10}; public static int[] sPolyYArray = {0,5,1,8,13,20,31,28,31,22,16,7,0}; // Creates a new asteroid public Rock(int[] polyXArray, int[] polyYArray, int pointsInPoly, int randomStartXPos, int randomStartYPos){ // Creates a Polygon by calling the super or parent class of Rock Polygon super(polyXArray, polyYArray, pointsInPoly); // Randomly generate a speed for the Polygon this.xDirection = (int) (Math.random() * 4 + 1); this.yDirection = (int) (Math.random() * 4 + 1); // Holds the starting x & y position for the Rock this.uLeftXPos = randomStartXPos; this.uLeftYPos = randomStartYPos; } public void move(){ // Get the upper left and top most point for the Polygon // This will be dynamic later on int uLeftXPos = super.xpoints[0]; int uLeftYPos = super.ypoints[0]; // If the Rock hits a wall it will go in the opposite direction if (uLeftXPos < 0 || (uLeftXPos + 25) > width) xDirection = -xDirection; if (uLeftYPos < 0 || (uLeftYPos + 50) > height) yDirection = -yDirection; // Change the values of the points for the Polygon for (int i = 0; i < super.xpoints.length; i++){ super.xpoints[i] += xDirection; super.ypoints[i] += yDirection; } } // public method available for creating Polygon x point arrays public static int[] getpolyXArray(int randomStartXPos){ // Clones the array so that the original shape isn't changed for the asteroid int[] tempPolyXArray = (int[])sPolyXArray.clone(); for (int i = 0; i < tempPolyXArray.length; i++){ tempPolyXArray[i] += randomStartXPos; } return tempPolyXArray; } // public method available for creating Polygon y point arrays public static int[] getpolyYArray(int randomStartYPos){ // Clones the array so that the original shape isn't changed for the asteroid int[] tempPolyYArray = (int[])sPolyYArray.clone(); for (int i = 0; i < tempPolyYArray.length; i++){ tempPolyYArray[i] += randomStartYPos; } return tempPolyYArray; } }
Could you list the key codes for us, or tell us how to know what number each key is, if there is a method for doing so (such as A = 1, so B = 2, C = 3, etc.)? Thank you, sir.
And thank you for the lessons. They are helping me pursue my dream career, despite being unable to afford to go to college. There is no price I could put on that, nor words to describe my gratitude.
Thank you 🙂 It is always great to hear that I helped so much!
Here are the key codes
backspace 8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222