Keyboard Input -- July 18, 2011 1) Fill in the template code to create a sprite with a starting position of (20, 50), then use keyboard input to move the sprite up, down, left and right. You are given some of the keyboard code below (highlighted), but must fill in the necessary code for loading the sprite’s image, the sprite’s position x and y, and for moving the sprite. 2) Finally, code your solution in JCreator and run it. Does your sprite move in the correct directions? public class GamePanel extends JPanel implements Runnable{ // More variables go here, left out for brevity... // Sprite Image variables private BufferedImage bgImage; // Sprite Position variables // GamePanel Constructor public GamePanel() { setBackground(Color.blue); // white background setPreferredSize( new Dimension(PWIDTH, PHEIGHT)); // Give the JPanel focus, so it can receive key events setFocusable(true); requestFocus(); // Add key listener addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { processKey(e); } }); // load the images bgImage = loadImage("C:\\...\\background.jpg"); } // end of GamePanel() public void run() /* Repeatedly update, render, sleep */ { running = true; while(running) { gameUpdate(); // game state is updated gameRender(); // render to a buffer paintScreen(); // paint with the buffer try { Thread.sleep(20); // sleep a bit } catch(InterruptedException ex){} } System.exit(0); } // end of run() // so enclosing JFrame exits private void gameUpdate() { if (!gameOver) // update game state ... ; Keyboard Input -- July 18, 2011 // Update sprite positions } private void gameRender() { // Render game content if (dbImage == null){ dbImage = createImage(PWIDTH, PHEIGHT); if (dbImage == null) { System.out.println("dbImage is null"); return; } else dbg = dbImage.getGraphics(); } // draw the background: use the image or a black colour if (bgImage == null) { dbg.setColor(Color.black); dbg.fillRect (0, 0, PWIDTH, PHEIGHT); } else { // Draw the background image dbg.drawImage(bgImage, 0, 0, this); } // Draw any sprite images } private void processKey(KeyEvent e) // handles termination and game-play keys { int keyCode = e.getKeyCode(); // end game keys - listen for esc on the canvas end game if (keyCode == KeyEvent.VK_ESCAPE) running = false; // game-play keys if (!isPaused && !gameOver) { if (keyCode == KeyEvent.UP) { // Do something } else if (keyCode == KeyEvent.DOWN) { // Do something else } } } } // end of processKey() // end of GamePanel class