Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: How can I improve on this?

  1. #1
    Junior Member
    Join Date
    Aug 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default How can I improve on this?

    I'm not sure if this is the right thread, but I'm not sure where to post. I just want information on things like if I'm writing it in a bad way or maybe theres an easier way.
    PLEASE DON'T GIVE ME THE AWNSER. I don't wanna be spoon fed. Give me a simple nudge so I get my brain thinking its a much better learning technique. The code in it self runs fine although my crappy collision detection which I used pointers for sucks.

    Basically I just want to know why my code sucks.
    How I can improve it.
    If I'm using methods or calling stuff or other things I don't need.
    I know the walls are dumb an I'll make a new class for level and make a code in there so I can create walls much easier.

    I might be confusing you guy, but I'm only wondering how to improve my code and organize it better so I can keep on coding a very simple game. I don't know what it is even going to do yet. It's all for learning as a I have a bigger idea for a game that isn't out of my way.

    Screen.java

    package com.projectgaming.game1;
     
    import java.awt.Color;
    import java.awt.event.KeyListener;
     
    import javax.swing.JFrame;
     
    public class Screen {
     
    	private static final long serialVersionUID = 1L;
     
    	public static int w = 800;
    	public static int h = 600;
     
    	public static void main(String[] args){
    		Game g = new Game();
    		JFrame frame = new JFrame();
    		frame.add(g);
    		frame.pack();
    		frame.setResizable(false);
    		frame.setSize(w, h);
    		frame.setTitle("Game Test");
    		frame.setBackground(Color.BLACK);
    		frame.setVisible(true);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setLocationRelativeTo(null);
    	}
    }


    Game.java
    package com.projectgaming.game1;
     
    import java.awt.*;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
     
    import javax.swing.*;
     
    public class Game extends JPanel implements Runnable, KeyListener{
     
    	private static final long serialVersionUID = 1L;
     
    	public Rectangle character;
    	public Rectangle floor;
    	public Rectangle wall1;
    	public Rectangle wall2;
    	public Rectangle wall3;
    	public Rectangle wall4;
     
    	public int keyUp = KeyEvent.VK_W;
    	public int keyDown = KeyEvent.VK_S;
    	public int keyRight = KeyEvent.VK_D;
    	public int keyLeft = KeyEvent.VK_A;
     
    	public int characterWidth = 24;
    	public int characterHeight = 36;
    	public int characterX = 400;
    	public int characterY = 300;
     
    	public int floorWidth = 400;
    	public int floorHeight= 300;
    	public int floorX = 200;
    	public int floorY= 200;
     
    	public int wall1Width = 400;
    	public int wall1Height = 10;
    	public int wall1X = 200;
    	public int wall1Y = 200;
     
    	public int wall2Width = 10;
    	public int wall2Height = 300;
    	public int wall2X = 600;
    	public int wall2Y = 200;
     
    	public int wall3Width = 410;
    	public int wall3Height = 10;
    	public int wall3X = 200;
    	public int wall3Y = 500;
     
    	public int wall4Width = 10;
    	public int wall4Height = 300;
    	public int wall4X = 200;
    	public int wall4Y = 200;
     
    	public int movementSpeed = 1;
    	public int movementFrame = 0;
     
    	public boolean running = true;
    	public boolean objectsDefined = false;
     
    	public boolean alive = true;
     
    	public boolean up = false;
    	public boolean down = false;
    	public boolean right = false;
    	public boolean left = false;
    	public boolean moving = false;
     
    	public Thread game;
     
    	public Game(){
    		super();
    		game = new Thread(this);
    		game.start();
     
    		defineObjects();
    		setFocusable(true);
    		addKeyListener(this);
    	}
     
    	public void keyPressed(KeyEvent e){
    		//System.out.println("Key pressed");
    		if(e.getKeyCode() == keyUp){
    			up = true;
    		}
     
    		if(e.getKeyCode() == keyDown){
    			down = true;
    		}
     
    		if(e.getKeyCode() == keyLeft){
    			left = true;
    		}
     
    		if(e.getKeyCode() == keyRight){
    			right = true;
    		}
    	}
    	public void keyReleased(KeyEvent e){
    		if(e.getKeyCode() == keyUp){
    			up = false;
    		}
     
    		if(e.getKeyCode() == keyDown){
    			down = false;
    		}
     
    		if(e.getKeyCode() == keyLeft){
    			left = false;
    		}
     
    		if(e.getKeyCode() == keyRight){
    			right = false;
    		}
    	}
    	public void keyTyped(KeyEvent e){}
     
    	public static void main(String[] args){
    		new Game();
    	}
     
    	public void defineObjects(){
    		character = new Rectangle(characterX, characterY, characterWidth, characterHeight);
    		floor = new Rectangle(floorX, floorY, floorWidth, floorHeight);
    		wall1 = new Rectangle(wall1X, wall1Y, wall1Width, wall1Height);
    		wall2 = new Rectangle(wall2X, wall2Y, wall2Width, wall2Height);
    		wall3 = new Rectangle(wall3X, wall3Y, wall3Width, wall3Height);
    		wall4 = new Rectangle(wall4X, wall4Y, wall4Width, wall4Height);
     
    		objectsDefined = true;
     
    		repaint();
    	}
    	public void paintComponent(Graphics g){
    		super.paintComponent(g);
     
    		this.setBackground(Color.BLACK);
     
    		if(objectsDefined){
    			g.setColor(Color.RED);
    			g.fillRect(floor.x, floor.y, floor.width, floor.height);
     
    			g.setColor(Color.BLUE);
    			g.fillRect(wall1.x, wall1.y, wall1.width, wall1.height);
    			g.fillRect(wall2.x, wall2.y, wall2.width, wall2.height);
    			g.fillRect(wall3.x, wall3.y, wall3.width, wall3.height);
    			g.fillRect(wall4.x, wall4.y, wall4.width, wall4.height);
     
    			if(alive){
    				g.setColor(Color.WHITE);
    				g.fillRect(character.x, character.y, character.width, character.height);
    			}
    		}
    		repaint();
    	}
     
    	public void run() {
    		while(running){
     
    			Point rightFoot = new Point(character.x, (character.y + 1) + character.height);
    			Point leftFoot = new Point(character.x + character.width, character.y + character.height);
    			Point rightHand = new Point(character.x, character.y - 1);
    			Point leftHand = new Point(character.x - 1, character.y);
    			//Movement
    			if(movementFrame >= movementSpeed){
    					if(up){
    						if(wall1.contains(rightHand) || wall1.contains(leftHand)){}else{
    							character.y -= 1;
    						}
    					}
     
    					if(down){
    						if(wall1.contains(rightFoot) || wall1.contains(leftFoot)){}else{
    							character.y += 1;
    						}
    					}
     
    					if(left){
    						if(wall1.contains(leftHand) || wall1.contains(leftFoot)){}else{
    							character.x -= 1;
    						}
    					}
     
    					if(right){
    						if(wall1.contains(rightHand) || wall1.contains(rightFoot)){}else{
    							character.x += 1;
    						}
    					}	
    					movementFrame = 0;
    				}else{
    					movementFrame += 1;
    				}
    			try {
    				Thread.sleep(1);
    			} catch (Exception e) {
    			}
     
    			repaint();
    		}
    	}
    }
    Last edited by Erko; August 3rd, 2012 at 11:03 AM. Reason: Forgot the code haha


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,619
    Thanks
    25
    Thanked 322 Times in 300 Posts

    Default Re: How can I improve on this?

    A few suggestions from my point of view:
    1. Class Variables that you intend on ONLY being used inside of the class, should be set to private instead of public (or protected if you think the variable will need to be inherited at some point in the future).
    2. Instead of having different variables for the keyUp, keyDown, ect., you could instead just use constants (eg: KeyEvent.VK_W) and check each one using a switch statement. I suspect you created variables for them for readability and, if so, commenting is a better alternative to creating variables for each constant.
    3. Instead of having a boolean whose entire purpose is to check if variables have been initialized, do a check if(wall1!=null) in your paint method instead of if(objectsDefined).
    4. Why are you repainting in the paintComponent() method?
    5. Instead of having a blank if statement for the purpose of having an else statement (in your run() method), check the negative case in your if statement. Check out the sudo-code below:
    this:
    if(somecase) {
         do nothing;
    } else {
         do something;
    }
     
    is the same as:
    if(!somecase) {
         do something;
    }
    6. If the values of some variables are never going to change, such as the width, height, x, and y of the floor and walls, it is best to make them constants instead of normal variables.

    That's all for now. There are probably other things that can be improved upon.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Junior Member
    Join Date
    Aug 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How can I improve on this?

    Thank you for the reply. Also uhhm how would I use a switch case? I've only ever used them with variables like
    switch(age){
       case 16:
               System.out.println("You are under 18");
       case 21:
               System.out.println("You can drink!");
    }

    But how would I use it in this case? with the key like KeyEvent.VK_W etc etc.
    Also when you said I had an empty if statement in my method run() I don't see the empty one your talking about to only run the else statement.

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,619
    Thanks
    25
    Thanked 322 Times in 300 Posts

    Default Re: How can I improve on this?

    Constants are just values. So, you can say:
    switch(someKey) {
    case KeyEvent.VK_W:
         do something;
         break;
    case KeyEvent.VK_S:
         do something;
         break;
    ...
    }
    Don't forget the break statements in a switch.


    In your run() method, you have if/elses that look like this:
    if(wall1.contains(rightHand) || wall1.contains(rightFoot)){}else{
    							character.x += 1;
    						}
    that can simply be changed to:
    if(!(wall1.contains(rightHand) || wall1.contains(rightFoot))){
    							character.x += 1;
    						}
    Last edited by aussiemcgr; August 3rd, 2012 at 12:52 PM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. #5
    Junior Member
    Join Date
    Aug 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How can I improve on this?

    Yes I forgot the break; statement haha. and alright I'm an idiot I overlooked that statement.

  6. #6
    Junior Member
    Join Date
    Aug 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How can I improve on this?

    Ok so

    public void keyPressed(KeyEvent e){
    		switch(keyPressed){
    		//Move up
    		case KeyEvent.VK_W:
    			up = true;
    			break;
    		//Move down
    		case KeyEvent.VK_S:
    			down = true;
    			break;
    		//Move left
    		case KeyEvent.VK_A:
    			left = true;
    			break;
    		//Move right
    		case KeyEvent.VK_D:
    			right = true;
    			break;
    		}
    	}
    	public void keyReleased(KeyEvent e){
    		//Stop moving up
    		switch(keyPressed){
    		//Stop moving up
    		case KeyEvent.VK_W:
    			up = false;
    			break;
    		//Stop moving down
    		case KeyEvent.VK_S:
    			down = false;
    			break;
    		//Stop moving left
    		case KeyEvent.VK_A:
    			left = false;
    			break;
    		//Stop moving right
    		case KeyEvent.VK_D:
    			right = false;
    			break;
    		}
     
    	}

    I also added private int keyPressed; But now I can't move I've never done a switch statement this way before so I'm kind of lost now.

  7. #7
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,619
    Thanks
    25
    Thanked 322 Times in 300 Posts

    Default Re: How can I improve on this?

    Instead of sending the switch statement the keyPressed variable, just send it: e.getKeyCode()
    e is the KeyEvent parameter of the method.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  8. #8
    Junior Member
    Join Date
    Aug 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How can I improve on this?

    Ahhh I didn't even think of that I was wondering what to use haha, well thank you it makes perfect sense to you use that since thats what you use to find which key is pressed if I'm right.

Similar Threads

  1. I want to improve my code.
    By niigata in forum What's Wrong With My Code?
    Replies: 3
    Last Post: January 11th, 2012, 09:17 AM
  2. Help me improve my code.
    By JeremiahWalker in forum What's Wrong With My Code?
    Replies: 6
    Last Post: January 10th, 2012, 08:24 PM
  3. How can i improve this code?
    By ziplague in forum What's Wrong With My Code?
    Replies: 16
    Last Post: December 12th, 2011, 11:24 AM
  4. This program works but Want to improve
    By SHStudent21 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: January 8th, 2011, 04:53 PM
  5. Critique Java Game: Help Me Improve
    By gretty in forum What's Wrong With My Code?
    Replies: 4
    Last Post: July 21st, 2010, 07:49 PM