#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0

    Need help with uni coursework


    Hi there guys, i've got an assignment in university due tomorrow. And im struggling on finishing my code. Its 2D btw.

    Basically we have to make a Lunar Lander type game (Accelerating, gravity, crash zone, land pad etc).

    Ive done all the gravity, acceleration.

    But i'm having trouble making the certain areas of my screen a crash zone and land pad.

    The crash zone is basically all the floor (no including the land pad). so that when the image hits the crash zone it changes to an explosiong gif,

    And the land pad i need to have the lander speed low enough and it to land on the land pad to be a successfull landing if that makes sense?

    Basically I can't get my head around how i tell it that the floor area is solid and is a crash zone and that the land pad is solid and able to land on?

    Lunar Lander

    sort of like that game but not as many complex cliffs etc.

    Any helps appreciated cheers - Jay.

    Code:
    /**
     * Write a description of class LunarLander here.
     * 
     * @author (your name) 
     * @version (a version number or a date)
     */
    
    //Functionality
    import javax.swing.JFrame;      // window functionality
    import java.awt.Color;          // RGB color stuff
    
    import javax.swing.Timer;       // import timer functionality
    import java.awt.event.*;        // functionality for the event fired by the timer
    
    import java.awt.*;              // Graphics stuff from the AWT library, e.g. Graphics
    import javax.swing.*;           // Graphics stuff from the Swing library, e.g. JLabel
    import java.awt.image.BufferedImage; // Graphics drawing canvas
    import java.awt.event.KeyEvent;
    import java.util.Random;
    public class LunarLander extends JFrame{
    
        // The Java window
        private static JFrame window;
        
        // Graphics "Handle"
        private static Graphics gr; 
        
        // Image Storage
        private static Image theBackground; // Background Image
        private static Image theLander; // PNG of the Lunar Lander
        private static Image theBang; // Animated Explosion
        public static Random randomGen= new Random();
        
        private static int landerX = randomGen.nextInt(800 - 50), landerY = 50; // Starting position of the lander
        private static boolean  explosion=false; // Sets explosion to false
        public static int speedY = 0;
        public static int speedX = 0;
        public static double speedStopping = 1;
        public static int speedAccelerating = 2;
        public static int topLandingSpeed = 5;
        
        
        // Main Method, Create window
        public static void main(String[] args) {
            
            //Window Setup
            window = new JFrame(); // Renames the new window
            
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Sets the X to close
            window.setTitle("Moon Lander, Can you be the first man on the moon!"); // Title Name
            window.setSize(800, 600); // Window Size
            window.setResizable(true); // Disables resizable window
            window.setLocationRelativeTo(null); // Sets location to top of the screen
            
            BufferedImage canvas=new BufferedImage(800,600,BufferedImage.TYPE_INT_ARGB); // Creates A Canvas
            gr=canvas.getGraphics(); // Creates handle for drawing on the canvas
            JLabel label=new JLabel(new ImageIcon(canvas)); // Creates label to draw on
            window.add(label);
            
            window.setVisible(true); // Displays above
            
            //Loading Images
            theBackground = GameImage.loadImage("Images//Background.png"); // Loads background
            theLander = GameImage.loadImage("Images//LunarLander.png"); // Loads lander
            theBang = GameImage.loadImage("Images//explosion.gif"); // Loads Explosion
                 
            GameKeyboard.initialise(); // Starts keyboard input
            
            
            
            //Timer Setup
            ActionListener taskPerformer = new ActionListener()
                {
                    public void actionPerformed(ActionEvent evt) // Calls the actionPerformed() method
                    {
                        doTimerAction();
                    }    
                };
            Timer ScreenTimer = new Timer(75, taskPerformer); // Creates Timer
            ScreenTimer.start(); // Starts Timer
        }
        
        // Method to draw all needed images, then timer resets to display on the screen
        private static void doTimerAction() {
            
            gr.drawImage(theBackground, 0, 0, null); // Overwrites everything with the background image
            
            // User Instructions
            gr.setColor( Color.red );  // Sets colour red
            gr.setFont(new Font("Arial", Font.BOLD, 16)); // Sets font
            gr.drawString("Arrow keys to move, land on the platform to win", 200,200); // Output and location
            
    
            
            // Get keys pressed from the keyboard
            char key= GameKeyboard.getKey();
            int specialKey=GameKeyboard.getSpecialKey();
            
            
            //Keyboard Binding
            
            
            if (landerY >= 500){
                gr.drawImage(theBang, landerX, landerY, null);
                gr.setColor( Color.red );  // Sets colour red
            gr.setFont(new Font("Arial", Font.BOLD, 16)); // Sets font
            gr.drawString("You have crashed! Restart game!", 200,400);
            }else{  
                
                
            if (specialKey == 38){
                speedY -= speedAccelerating;
            }else{ 
                speedY += speedStopping;
            }  
            
            if (specialKey == 37){
                speedX -= speedAccelerating;
            }else{
                speedX += speedStopping;
            }
                
            if (specialKey == 39){
                speedX += speedAccelerating;
            }else{
                speedX -= speedStopping;
            }
            
            landerX += speedX;
            landerY += speedY;
            
    
            
    
            gr.setColor( Color.red );  // Sets colour red
            gr.setFont(new Font("Arial", Font.BOLD, 16)); // Sets font
            gr.drawString("speedX" + speedX + "speedY" + speedY + "speedAccelerating" +speedAccelerating + "speedStopping" + speedStopping + "landerY" + landerY + "landerX" + landerX, 200,400);
            gr.drawImage(theLander, landerX, landerY, null); // Draws lander and its position
            
        }    
        window.repaint();  // Re paints everything onto the screen
        }    
    }
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    348
    how i tell it that the floor area is solid and is a crash zone and that the land pad is solid and able to land on?
    What values can the program look at to make that decision?

    There are missing classes when compiling for testing.
    Last edited by NormR; February 3rd, 2013 at 06:40 AM.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0
    Oops forgot to post them.


    Code:
    /* 
     * This class implements a simple keyboard event dispatcher. Normally a Java application attaches so
     * called 'KeyListeners' to individual objects such as text input fields. In a game, however, we want
     * all parts of the game window to respond to keyboard inputs without having to click on them first.
     * We also don't want the repetitive task of attaching a 'KeyListenr' to each and every object that
     * may appear in the game.
     * The drawback of this apprach is that it is now tricky to use a standard text input field - alas,
     * that is probably not really what we want anyway.
     * 
     * USAGE:
     * ======
     * In the game class just add this line:
     *         GameKeyboard.initialise();
     *         
     * You can then interrogate two variables: 'key' and 'specialKey' like this:
     *         if(GameKeyboard.getKey() == 'q') {  ...
     *         if(GameKeyboard.getSpecialKey() == 38) { // 'up' arrow key is 38, down is 40, ...
     */
    
    
    import java.awt.*;              // Graphics stuff from the AWT library, her for the KeyEventDispatcher
    import java.awt.event.*;        // Event handler, here for keyboard events
    
    public class GameKeyboard implements KeyEventDispatcher {
    
        // The variable 'key' and 'specialKey' are private but can be accessed via the public
        // 'get' methods 'getKey()' and 'getSpecialKey()'. These are coded below.
        // These can be interrogated from the main application
        private static char key=' ';
        private static int  specialKey=0;
    
        // This constant is public so that other classes can check if a key has been pressed.
        // e.g.  if(kbd.getKey() != kbd.NONE) {...
        public final int NONE=0;
    
        private static GameKeyboard kbd;
    
        // Attach a keyboard focus manager to the keyboard event dispatcher
        // Don't worry if you don't understand this. Just leave it as it is.
        public GameKeyboard() {
            KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            manager.addKeyEventDispatcher( this );    
        }
    
        // This is the method that actually checks the keyboard for key strokes and sets the two
        // private variables of this class ('key' and 'specialKey') to its values accordingly.
        public boolean dispatchKeyEvent(KeyEvent e) {
    
    
            // To start with, let's reset both variables
            key= NONE;
            specialKey= NONE;
    
            // Read the special keys (e.g. arrow keys, Shift, Alt, ...)
            specialKey= e.getKeyCode();
    
            // Only if no special character was pressed, check for normal keys, otherwise you
            // get the scan codes of the special keys
            if(specialKey == NONE) {
                key = e.getKeyChar();
            }
    
            // If a key is going up, reset the two variables.
            if (e.getID() == KeyEvent.KEY_RELEASED) {
                key= NONE;
                specialKey= NONE;
            } 
    
            return false;
        }
    
        public static void initialise() {
            GameKeyboard kbd= new GameKeyboard();
        }
    
        public static char getKey() {
            return key;
        }
    
        public static int getSpecialKey() {
            return specialKey;
        }
        
    }
    Code:
    /*
     * This is a very simple class that encapsulates the loading
     * of images only.
     * 
     * Access from other classes: 
     *     Image myImg = GameImage.loadImage("C://MyImage.gif");
     */
    
    import java.awt.*;              // Graphics stuff from the AWT library, here: Image
    import java.io.File;            // File I/O functionality (for loading an image)
    import javax.swing.ImageIcon;   // All images are used as "icons"
    
    
    
    public class GameImage
    {
        public static Image loadImage(String imagePathName) {
            
            // All images are loades as "icons"
            ImageIcon i = null;
            
            // Try to load the image
            File f = new File(imagePathName);
            
            
            if(f.exists()) {  // Success. Assign the image to the "icon"
                i = new ImageIcon(imagePathName);
            }
            else {           // Oops! something is wrong.
                System.out.println("\nCould not find this image: "+imagePathName+"\nAre file name and/or path to the file correct?");            
                System.exit(0);
            }
            
            // Done. Either return the image or "null"
            return i.getImage();
            
        } // End of loadImages method
    
    }
    Basically its all begginer stuff, I have the images braught in via the gameImage class, displayed then moved around by co ordinates.
    The keyboard input is listened to by the keyboard class (W,A,D etc)

    I just cant figure out how to make the lander its self colide with certain areas of the 800x600 screen.
  6. #4
  7. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    348
    how to make the lander its self colide with certain areas of the 800x600 screen
    Compare the lander's location with the location of the areas it can collide with.
    It helps to see by using a piece of paper to draw the objects and label their locations in x and y values and then see what comparisons are needed to detect when there is a collision.

IMN logo majestic logo threadwatch logo seochat tools logo