Results 1 to 8 of 8
Like Tree1Likes
  • 1 Post By pj6444

Thread: Tell me something about my code, please?

  1. #1
    Nozz is offline Member
    Join Date
    Apr 2014
    Posts
    49
    Rep Power
    0

    Default Tell me something about my code, please?

    Hi,
    I'm learning now java applets and my project was to recreate flappy birds with some changes, and I nearly finished now. Main game mechanic isworking, just game menu isn't designed yet, and some improvemetns like movement of enemies, changing their speed etc... But it works now.
    And here is my question. Can you tell me something about my code?
    Can you rate it in 10 points scale? How "professional" does it look? How much have I learned since my first console hello word, and how much I have to learn yet?
    Is it good to write it like this? For example, in paintComponent there is part of painting game and menu, it changes while variable menu changes... Is it ok or should be written all other way? What should I do like I did, and what should be changed to improve quality of this?
    Maybe should I post here all source files and images to your review?

    So, here is my code:
    Java Code:
    package jumperSwing;
    // DRAW MENU CONTENT IN PANEL
    /*TODO 
    * ACHIEVEMENTS
    * Add tooltip on stars. *
    * Each achivement should have its own ID. *
    * Loop for achievement conditions (if's).
    *
    * GAME
    * Enemies random movement for 2 or more enemies.
    * Enemies movement up and down on harder levels.
    * Start button change name to restart if paused or lost.
    * Death Effects.
    *
    * IMAGES
    * Loop images loading.
    * Finally get nice graphics with transparent background so it all will work fine.
    
    * COMMENTS
    * Finish comments in not commented lines.
    * 
    * MENU
    * Build whole menu.
    * Functions like buttons etc merged and managed by arguments.
    * 
    * * = Maybe will be done, but is not prerequisite.
    * 
    */
    import java.awt.*;
    
    import javax.swing.JPanel;
    import javax.swing.JButton;
    
    import java.awt.image.BufferedImage;
    import java.io.File; 
    import java.io.IOException; 
    
    import javax.imageio.ImageIO;
    
    import java.awt.event.ActionEvent; 
    import java.awt.event.ActionListener; 
    import javax.swing.Timer; 
    
    import java.util.Random;
    
    public class Game extends JPanel implements ActionListener{ 
    
    	private Timer timer; // timer variable 
    	int jumpNow = 0, pauseGame = 0; // jump state needed to execute jump in main loop
    	int closeRoof = 0, closeRoofPause = 0, closeFloorPause = 0, pointsReach = 0, deathsReach = 0, achiCount;
    	
    	Config Config = new Config(); // taking data from config file
    	Random rand = new Random(); // randomizer
    
    	private static final long serialVersionUID = 1L; // serial number?
    	private JButton play, jump, pause, start, cheat; // buttons
    	private BufferedImage MenuBG, MenuBar, MenuFloor, player, Star, emptyStar, enemy; // images
    	
    	public Game() { 
    	        super(); 
    	        setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 8)); // layout - mainly used for buttons position here
    	         
    	       getImages();
    	       createButtons();
    	       if(Config.menu == 1)
    	       showMenuButtons();
    	       else
    	       showGameButtons();
    	       
    		 ActionListener action = new ActionListener() 
    		 {   
    
    		     @Override
    		     public void actionPerformed(ActionEvent event) 
    		     {
    		    	 if(Config.started == 1){ // if started by config or start button
    		    		
    		    		IncrasePointsOverTime(); // incrase points for each jump over time, start value = 1
    		    		enemyMove(); // enemy moves from right to left
    		    		
    			    	if (checkHeight() && checkWidth()) // if player collide with enemy
    			    		Death(); // player dies
    		    		if(jumpNow > 0) // if jump pressed executes jump here by loop
    		    			Jump(); // player jumps
    		    		if(Config.pos >= Config.defFloor || Config.pos <= Config.defRoof) // if player dies
    		    			Death(); // player dies
    		    		if(Config.pos < Config.defFloor && jumpNow == 0) // if player didnt fall on floor and didnt jumped
    		    			Fall(); // player falls if didn't jumped
    		    	 }
    		    }
    		 };
    
    		 timer = new Timer(-Config.fallSpeed, action); // timer that do main loop
    		 timer.setInitialDelay(0);
    		 timer.start();
    		 
    	 }
    	 
    public boolean checkHeight() // check hight of player and enemy, if its close returns true
    {
    	 if(Config.pos+Config.ballHeight > Config.enemyPos &&
    		Config.pos+Config.ballHeight < Config.enemyPos+Config.enemyHeight ||
    		Config.pos > Config.enemyPos &&
    		Config.pos < Config.enemyPos+Config.enemyHeight)
    	return true;
    	else
    	return false;
    }
    
    public boolean checkWidth() // check width of player and enemy, if its close returns true
    {
    	if(Config.windowWidth/3 > Config.enemyMove &&
    	   Config.windowWidth/3 < Config.enemyMove+Config.enemyWidth ||
    	   Config.windowWidth/3+Config.ballHeight > Config.enemyMove &&
    	   Config.windowWidth/3+Config.ballHeight < Config.enemyMove+Config.enemyWidth
    	   )
    	return true;
    	else
    	return false;
    }
    	
    public void Jump() // if player click jump button instead of falling, character jumps
    	 {
    		// if jumped and was close to roof achivement++
    			if(Config.pos < Config.defFloor+Config.closeRoofReq && Config.pos > Config.defFloor && closeRoof == 0 && Config.started == 1) closeRoof = 1;
    
    		if(jumpNow >= Config.jumpStagesCount) // delay for jump, its slowing down while near jump peak, and stops for a while on top
    			Config.points+=Config.pointsOverTime; // points for each jump
    			jumpNow--; // sets jump to not execute twice in loop
    			if(Config.points == Config.pointsReach && pointsReach == 0 && Config.started == 1) pointsReach = 1; // reach points achivement++
    		if(jumpNow > 3 && jumpNow < 2) // slowing jump
    			Config.pos = Config.pos + Config.jump/Config.jumpStagesCount/3; 
    		if(jumpNow > 1) // pausing jump on top of jump
    			Config.pos = Config.pos + Config.jump/Config.jumpStagesCount;
    			repaint();
    	 }
    
    public void Fall() // player falling down over time
    	 {
    		// floor a achi in play
    		 Config.pos = Config.pos + Config.step; // main action did in this loop - falling down
    		 repaint();
    	 }
    
    public void Death() // player touch sky, floor or enemy = death
    	 {
    		 if(deathsReach < Config.deathsReach && Config.started == 1) deathsReach++; // death counter achi++
    		 	restarts(); // restarts positions etc
    		 	hideGameButtons(); // hides game buttons
    		 	showMenuButtons(); // shows menu buttons
    		 	Config.menu = 1; // needed for plaint component to draw menu instead of game
    			Config.pointsOverTime = 1; // restarts incrasing points for each jump 
    
    		 	validate(); // to redraw buttons
    		 	repaint(); 
    	 }
    	 
    public void IncrasePointsOverTime() // each jump give more points after a while
    	 {
    		 if (Config.pointsDelay == Config.pointsDelayTime)
    		 {
    			 Config.pointsDelay = 1;
    			 Config.pointsOverTime++;
    		 }
    		 else
    			 Config.pointsDelay++;
    	 }
    
    public void getImages() // take images from giles
    		{
    			 // TODO : LOOP images declarations
    	        /*  String images [] = {"images/sky.png", "images/bar.jpg"};
    	        String imagesName [] = {"MenuBG","MenuBar"};
    	        for(int i = 0; i < 6; i++){
    	        File i = new File(images[i]); */
    			File imageFile7 = new File("images/flappy/enemy.gif");
    	        File imageFile = new File("images/flappy/sky.png"); // image sky variable
    	        File imageFile2 = new File("images/flappy/bar.jpg");// image bar variable
    	        File imageFile3 = new File("images/flappy/floor.png");// image floor variable
    	        File imageFile4 = new File("images/flappy/player.gif");// image player variable
    	        File imageFile5 = new File("images/flappy/star.png");// image star variable
    	        File imageFile6 = new File("images/flappy/emptyStar.png"); // image emptstar variable
    	        //}
    	        try { // testing if images exist etc
    		      /*for(int i = 0; i < 6; i++){
    		        imagesName[i] = ImageIO.read(i);
    		        } */
    	        	enemy = ImageIO.read(imageFile7);
    		        emptyStar = ImageIO.read(imageFile6); // read image from prev variable
    	        	Star = ImageIO.read(imageFile5);// read image from prev variable
    	        	player = ImageIO.read(imageFile4);// read image from prev variable
    	        	MenuFloor = ImageIO.read(imageFile3);// read image from prev variable
    	        	MenuBar = ImageIO.read(imageFile2);// read image from prev variable
    	        	MenuBG = ImageIO.read(imageFile); // read image from prev variable
    	        } catch (IOException e) { // if some images dont exist = error
    	            System.err.println("Some images was not found. Check file names, paths and extensions."); // error text
    	            System.err.println(""); // enter error text
    	            e.printStackTrace();
    	            //System.exit(0); // system off
    	        }
    		}
    		
    public void createButtons() // create every button in program
    		{
    		 
    					 jump = new JButton("Jump"); // jump button done
    					 start = new JButton("Start"); // start button done
    					 pause = new JButton("Pause"); // pause button done
    					 cheat = new JButton("Cheat"); // pause button done
    					 play = new JButton("Play Game"); // start button done
    
    					 play.addActionListener(this); // listener for start
    					 jump.addActionListener(this); // listener for jump
    					 start.addActionListener(this); // listener for start
    				     pause.addActionListener(this); // listener for pause
    				     cheat.addActionListener(this); // listener for cheat
    		}
    	 
    public void showGameButtons() // shows buttons in game
    	 {
    		 add(jump); // creating jump button
    		 add(start); // creating start button if in game config start is after button press, not default after applet start
    		 add(pause); // creating pause button
    		 if(Config.debugMode == 1) add(cheat); // if debug mode on creating cheat button
    	}
    	 
    public void showMenuButtons() // shows buttons in menu
    	 {
    			 add(play); // creating start button if in game config start is after button press, not default after applet start
    	 }
    	 
    public void hideGameButtons() // hides game buttons in menu
    	 {
    			remove(jump);
    			remove(pause);
    			remove(start);
    			remove(cheat);
    	 }
    	 
    public void hideMenuButtons() // hides menu buttons in game
    	 {
    		 remove(play);
    	 } 
    	 
    public void restarts() // restart pos, enemy, jump, game pause ent everything
    	 {
    		 	Config.pos = Config.defPos; // pos normalizer if roof hited
    		 	Config.enemyMove = Config.defEnemyMove;
    		 	jumpNow = 0; // restart jump - fix auto jump after restart
    		 	Config.started = 2; // started at 2 pauses game
    		 	repaint();
    	 }
    
    public void enemyMove() // enemy moves right to left
    {
    	 Config.enemyMove = Config.enemyMove-Config.enemyStep;
    	 if(Config.enemyMove < -Config.enemyWidth) 
    	 {
    		 // tables need to have same length because of reason
    		 int enemyPositionsUp[] = {55, 70, 120, 140, 160, 180};
    		 int enemyPositionsDown[] = {220, 240, 290, 320, 350, 380};
    		 int random = rand.nextInt(enemyPositionsUp.length);
    		 Config.enemyMove = Config.defEnemyMove;
    		 if(Config.upDownPos == true)
    		 {
    		 Config.enemyPos = enemyPositionsUp[random];
    		 Config.upDownPos = false;
    		 }
    		 else
    		 {
    		 Config.enemyPos = enemyPositionsDown[random];
    		 Config.upDownPos = true;
    		 }
    	}
    	 repaint();
    }
    	 
    	 	@Override
    	 public void actionPerformed(ActionEvent e) 
    	 	{ 
    	        Object click = e.getSource(); 
    	        if(click == play)
    	        {
    	        	hideMenuButtons();
    	        	showGameButtons();
    	        	Config.menu = 0;
    	        	Config.points = 0;
    	        	
    	        	validate();
    	        	repaint();
    
    	        }
    	        else if(click == cheat)
    	        {
    	        	Config.points = Config.points + Config.cheatPoints; // incrase points while cheat 
    	        	repaint(); // repaint all
    	        }
    	        else if(click == start) // start button action
    	        {
    	        	if(pauseGame == 0) // if game state paused
    	        	{
    	        		Config.started = 1; // starts game
    	        		Config.points = 0; // resets points
    	        		Config.pos = Config.defPos; // changes player pos to default
    	        	}
    	        	else // otherwise
    	        	{
    	        		pauseGame = 0; // sets pause game state to 0
    	        		Config.started = 1;  // stars game
    	        	}
    	        }
    	        else if(click == pause) // pause game button action
    	        {
    	        	// pause achievements close to roof and floor
    	        	if(Config.pos >= Config.defFloor-Config.closeFloorPauseReq && closeFloorPause == 0 && Config.started == 1) closeFloorPause = 1;
    	        	if(Config.pos <= Config.defRoof+Config.closeRoofPauseReq && closeRoofPause == 0 && Config.started == 1) closeRoofPause = 1;
    
    	        	if(Config.started != 2) // fix pause > start save points
    	        	pauseGame = 1; // pause game status save
    	        	if(Config.started == 1)	Config.started = 0; // stop game activity 
    	        	else if(Config.started == 0) // if game is not running
    	        	{
    	        		Config.started = 1; // start game activity
    		        	pauseGame = 0; // pause game status save
    
    	        	}
    	        	repaint(); // repaint all
    	        }
    	        else if(click == jump) // jump button action
    	        {
    	       	
    	              	if(Config.started == 1){ // only if game is active
    	              		jumpNow = Config.jumpStagesCount; // setting jump variable, jump is executed in timer loop
    	              		repaint(); // repainting
    	              	}
    	        
    	        }
    	   }
    	   
    	 @Override// main painting
    	 protected void paintComponent(Graphics g)
    	 { 
    		 super.paintComponent(g);
    		 Graphics2D g2d = (Graphics2D) g; // 2d graphics
    		 if(Config.menu == 0)
    		 {
    			 double backgroundWidth = Toolkit.getDefaultToolkit().getScreenSize().getWidth(); // take window width to repaint background images for full width window
    	     
    			 for(int i = 0; i < backgroundWidth; i = i+Config.bgWidth) // repeat BG
    				 g2d.drawImage(MenuBG, i, 0, this); // background pic
    	     
    			 for(int i = 0; i < backgroundWidth; i = i+Config.defRoof) // menu bar in game background loop
    				 g2d.drawImage(MenuBar, i, 0, this);  // menu bar in game background pic
    	     
    			 for(int i = 0; i < backgroundWidth; i = i+Config.floorWidth) // repeat floor
    				 g2d.drawImage(MenuFloor, i, Config.windowHeight-110, this); // paint floor pic
      	     
    			 // points and player color changes while points reach peak points
    	     
    			 if(Config.points < Config.redPointsMax) // when points have to be red
    			 {
    				 g2d.setColor(new Color(235, 25, 25)); // set to red
    			 }
    			 else if(Config.points >= Config.redPointsMax && Config.points < Config.orangePointsMax)// when points have to be orange
    			 {
    				 g2d.setColor(new Color(225, 150, 10)); // set to orange
    			 }
    			 else if(Config.points >= Config.orangePointsMax && Config.points < Config.yellowPointsMax)// when points have to be yellow
    			 {
    				 g2d.setColor(new Color(235, 220, 60)); // set to yellow
    			 }
    			 else // when points have to be green
    			 {
    				 g2d.setColor(new Color(20, 215, 25)); // set to green
    			 }	
    			 g2d.drawImage(enemy, Config.enemyMove, Config.enemyPos, this); // enemy1
    			 //g2d.drawImage(enemy, Config.enemyMove, Config.enemyPos+300, this); // enemy2
    			 g2d.drawImage(player, Config.windowWidth/3, Config.pos, this); // character
    			 
      	     // 	diplay points
    			 Font font = new Font("ARIAL BLACK", Font.BOLD, 22); // set font settings
    			 g2d.setFont(font); // set font 
    			 g2d.drawString("Punktów: "+Config.points, 10, 30); // draw points
      	     // 	achievements
      	     // 	TODO : LOOP on achi
    
    			 if(pointsReach == 1)
    			 {
    			  	 	pointsReach = 2;
    			  	 	achiCount++;
    			 }
    			 if(deathsReach == Config.deathsReach)
    			 {
    				 deathsReach = Config.deathsReach+1;
    				 achiCount++;
    			 }
    			 if(closeRoof == 1)
    			 {
    				 achiCount++;
    				 closeRoof = 2;
    			 }
    			 if(closeFloorPause == 1)
    			 {
    				 achiCount++;
    				 closeFloorPause = 2;
    			 }
    			 if(closeRoofPause == 1)
    			 {
    				 achiCount++;
    				 closeRoofPause = 2;
    			 }
    			
    			 
    			 for(int i = 0; i < Config.maxAchi; i++)
    				 g2d.drawImage(emptyStar, (10+i*30), 55, this);
    			 
    			 for(int i = 0; i < achiCount; i++)
    				 g2d.drawImage(Star, 10+i*30, 55, this);
    			 
    		 }
    		 else
    		 {				 
    			 Font menuFont = new Font ("Courier New", Font.BOLD, 25);
    			 g2d.setFont(menuFont);
    			 g2d.drawString("Menu Gry", 100, 100); 
    			 g2d.drawString("Created by: "+Config.creatorGame, 100, 200);
    			 g2d.drawString("Graphics by: "+Config.creatorGraphics, 100, 300); 
    			 g2d.drawString("Points: "+Config.points, 100, 400);
    			 if(Config.points > Config.bestPoints) Config.bestPoints = Config.points;
    			 g2d.drawString("Best Points: "+Config.bestPoints, 300, 400);
    			 g2d.drawString("Acichements: "+achiCount+"/"+Config.maxAchi, 100, 450);
    
    		 }
    		 
      	     // 	debugger 
    			 if(Config.debugMode == 1)
    			 {   
    				 Font debugFont = new Font ("Courier New", Font.BOLD, 15);
    				 g2d.setFont(debugFont);
    				 g2d.setColor(Config.debugColor);
    				 g2d.drawString("-- DEBUGGER --", 5, Config.windowHeight-235);
    				 g2d.drawString("Pos: "+Config.pos, 5, Config.windowHeight-175);
    				 g2d.drawString("Pause: "+pauseGame, 5, Config.windowHeight-160);
    				 g2d.drawString("Started: "+Config.started, 5, Config.windowHeight-145);
    				 g2d.drawString("Roof Pos: "+Config.defRoof, 5, Config.windowHeight-130);
    				 g2d.drawString("Floor Pos: "+Config.defFloor, 5, Config.windowHeight-115);
    				 g2d.drawString("Points Delay: "+Config.pointsDelay, 5, Config.windowHeight-100);
    				 g2d.drawString("Jump High: "+-Config.jump, 5, Config.windowHeight-85);
    				 g2d.drawString("Deaths: "+deathsReach, 5, Config.windowHeight-70);
    				 g2d.drawString("PointsOT: "+Config.pointsOverTime, 5, Config.windowHeight-55);
    				 
    				 g2d.drawString("EnemyMove: "+Config.enemyMove, 5, Config.windowHeight-190);
    				 g2d.drawString("EnemyPos: "+Config.enemyPos, 5, Config.windowHeight-205);
    				 g2d.drawString("Enemy Step: "+Config.enemyStep , 5, Config.windowHeight-220);
    
    
    				 g2d.drawLine(Config.windowWidth/3, Config.pos, Config.windowWidth/3+200, Config.pos);
    				 g2d.drawLine(Config.windowWidth/3, Config.pos+Config.ballHeight, Config.windowWidth/3+200, Config.pos+Config.ballHeight);
    				 
    				 g2d.drawLine(Config.enemyMove, Config.enemyPos, Config.enemyMove-300, Config.enemyPos);
    				 g2d.drawLine(Config.enemyMove, Config.enemyPos+Config.enemyHeight, Config.enemyMove-300, Config.enemyPos+Config.enemyHeight);
    			 }
    	}
    	 
    }
    Last edited by Nozz; 04-13-2014 at 07:51 PM. Reason: comments

  2. #2
    pj6444 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    162
    Rep Power
    2

    Default Re: Tell me something about my code, please?

    If it works that is a step, but for a professional look of code, you should add comments so other people know what it does. Also, you might want to try spacing out your code a little to make it easier to read. And for the "game states" you could use a stack to store different classes or you can stick with the if statements that you have in the paintComponent() method.

  3. #3
    Nozz is offline Member
    Join Date
    Apr 2014
    Posts
    49
    Rep Power
    0

    Default Re: Tell me something about my code, please?

    @up
    There with some comments etc. I deleted them to check how much lines of pure code there is. Well, should upload this version first time. Even if not everything is made good way. Well, I'm not experinced with this, so it looks like it looks.
    Anyway.
    Can you give me example of how I should handle with this "game states" changing? I tried few things, but I have no idea how to make it works...

  4. #4
    pj6444 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    162
    Rep Power
    2

    Default Re: Tell me something about my code, please?

    Here's how I do it:

    I have a GameStateManager class:
    Java Code:
    public class GameStateManager {
    
    	public Stack<GameState> states;
    	
    	public GameStateManager() {
    		states = new Stack<GameState>();
    		states.push(new MenuState(this));
    	}
    	
    	public void tick() {
    		states.peek().tick();
    	}
    	
    	public void draw(Graphics g) {
    		states.peek().draw(g);
    	}
    	
    	public void keyPressed(int k) {
    		states.peek().keyPressed(k);
    	}
    	
    	public void keyReleased(int k) {
    		states.peek().keyReleased(k);
    	}
    	
    }
    Basically what this does is contain a stack of classes that extend the GameState type. So it calls these methods from your main game class and then calls the current "state" that is on top of the Stack.

    Here is the GameState superclass
    Java Code:
    public abstract class GameState {
    
    	protected GameStateManager gsm;
    	
    	public GameState(GameStateManager gsm) {
    		this.gsm = gsm;
    		init();
    	}
    	
    	public abstract void init();
    	public abstract void tick();
    	public abstract void draw(Graphics g);
    	public abstract void keyPressed(int k);
    	public abstract void keyReleased(int k);
    }
    So then you create classes that extend GameState and use them for your Stack. This will allow you to change what is happening by manipulating which object in the stack is being updated, painted, etc.
    BinaryDigit09 likes this.

  5. #5
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    448
    Rep Power
    1

    Default Re: Tell me something about my code, please?

    Hmm .. My quick view on it:
    - use a strict coding line. Example: sometimes the { is on the next line and sometimes on the same line.
    - to many comments. Comments are easily misleading. Instead try to write code that explains itself
    - to long functions. Try to write functions that do one thing. That way the function name will document, what the function is doing.

    Maybe I will take some time and try a refactoring tomorrow.

    Konrad

  6. #6
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    448
    Rep Power
    1

    Default Re: Tell me something about my code, please?

    Hi Nozz,

    for a real refactoring I am missing part of your code. It seems that you have a class Config which is not posted here.

    So what steps did I see for a refactoring:
    - Most comments are not required. The bif comment block on top of the code does not belong there. It has nothing to do with the code itself. If you want to take care of TODO things, then use any system you like (e.g. a simple text file stored with the source if you only have all stuff inside your source management system or use a project management suite to store stuff as open task or backlog items.) Another example are comments like "Config config = new Config(); // Configuration" - So Config is your configuration ... never thought that :) So such comments can go completly. More extreme is code like add(jump); // Creating jump button. The comment seems wrong because you are adding it - not creating. A big reason why I do not like comments because they often give wrong information. (That is not because you was doing something wrong or you are bad. That will happen all the time! Maybe not as extrem but stuff like that is very likely!)
    - I already mentioned coding styles. Examples seen in your code are: Placement of { or case of names. (Variables are lowercase but your Config instance is stored in Config - should be config.)
    - Your class simply seems to do to much things. It is the Frame window. I includes the logic of the game. It is the main application. I would suggest to divide it up completly. That would make everything much easier to read and people know exactly where to find something.
    - Big methods are hell. First example is getImages(). The code itself is great. But you placed comments in there. And you can get rid of a lot of comments through more methods.
    Java Code:
    public void getImage() {
      try {
        loadImagesFromFiles();
      } catch (IOException e) {
        printErrorMessage(e, "Some images was not found. Check ...");
      }
    }
    So the comment that you are loading image files is no longer required. The function name already tells it to you.
    And the code to print the exception: You might have that code on multiple places. If you decide to remove the blank line between stack trace and message you have to modify multiple locations. Now it is simply one method that you have to change.
    You can do that with a lot of functions. Try to keep functions small and easy. Important points can be:
    - If you feel that a comment is required to understand what the function is doing: This could be a hint.
    - If your function is doing more than one thing. (So if you have a lot of ifs or so!)
    - if your function is doing work on multiple "levels" (so you call the highlevel function DoSomethingSpecial but also low level API stuff. That can be a sign.
    All these are no strict rules. Sometimes a short comment might be the best solution...

    So an actionPerformed method would look like this in my code:
    Java Code:
    	@Override
    	public void actionPerformed(ActionEvent e) {
    		switch (e.getSource()) {
    		case play:
    			playButtonClicked();
    			break;
    
    		case cheat:
    			cheatButtonClicked();
    			break;
    
    		case start:
    			startButtonClicked();
    			break;
    
    		case pause:
    			pauseButtonClicked();
    			break;
    
    		case jump:
    			jumpButtonClicked();
    			break;
    		}
    	}
    When you divide stuff in multiple classes, then your game window might have an instance of your Game class. So code like
    if (pauseGame==0) // if game state paused
    could simply be
    if (game.isPaused()) or to have your comment, you could call the game variable gameState:
    if (gameState.isPaused())

    I hope you got the big picture from my description. Your paintComponent needs a lot of this work, too :)

    And maybe just as a small note: That is not stuff that I found out. All this was part of the book "Clean Code: A Handbook of Agile Software Craftmanship" by Robert C. Martin published by Prentice Hall in 2008. (I found that a great book and I even think that it is worth reading it multiple times so you just think about it and maybe you can change a few habbits, too.)

    And very important: Nobody directly writes clean code! Even experienced developers simply write code first. But if they care then they directly refactor their code so that it is really readable. There is no other way because when you start coding you often do not know how complex some areas might get. (So you write code and then find out that a test case failed because you forgot a special case. So you add it to your code. But that could already lead to code that might need refactoring. And even after taking care of the code: You will have a code review and then others who didn't write the code will find some points - because they don't understand something directly or stuff like that.)

    So d onot understand me wrong: Even if I pointed out, that I see optimisations in your code and possibilities - that does not mean that you did a bad job! You build a working game if I understood you correctly and that is great! It is really great! And nobody expects perfect code from a beginner. (How could I get a good sallary if my job could be done by some pupils without much experience?) Just look if you could adapt a few points. Would be great if your next code could be cleaner. But concentrate on more practice! That might be more important.

    Konrad

  7. #7
    Nozz is offline Member
    Join Date
    Apr 2014
    Posts
    49
    Rep Power
    0

    Default Re: Tell me something about my code, please?

    Great. Thanks for your comments.

    I've seen code in this topic yesterday:
    Add color to ball in Pong, Add speed
    Well, I see some differences.
    If I get back to this project, I see many things that can be done here. Also some things taken from your posts.

    for a real refactoring I am missing part of your code. It seems that you have a class Config which is not posted here.
    Yeah, I just posted bigges file, in config there are just variables and thats it.

    Maybe I will take some time and try a refactoring tomorrow.
    If you thing, this can help me better than watching other code to compare differences, it would be great. But if not, don't force yourself.

    In next project, which I'm currently working on, I will try to write better code. And then, I hope someone will tell me something, If it is better or is not. And then maybe will I get back to this one to update it, but I don't know.
    I'm sometimes bored while I have to make big changes in code and it barely affects whole program, thats why I started something else instead of completing this. The game wouldn't change at all, but it requies some time to refactor this code...
    Thats also reason why I let go my school project. It wasn't really important, just would waste few hours to draw some rectangles etc in awt... It wasn't sensible to me, so I dropped it after making easiest part... Just to make something more complicated and actually learn something.
    Should I focus on completing my projects? Or isn't it important and I can go to another ones?

  8. #8
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    262
    Rep Power
    2

    Default Re: Tell me something about my code, please?

    If you are writing in an IDE formatting is automated. Me, I always write it into proper style in the process as a habit. I have become a code format maniac ocd.
    Read the conventions, but the most important part is keeping consistency in the style and structure. i.e. not having curly brackets in some statements and in others to have.

Similar Threads

  1. Replies: 1
    Last Post: 03-25-2012, 02:40 AM
  2. Replies: 16
    Last Post: 01-31-2012, 08:36 PM
  3. Replies: 3
    Last Post: 08-10-2011, 09:17 AM
  4. Replies: 0
    Last Post: 08-07-2011, 08:32 PM
  5. Replies: 0
    Last Post: 02-21-2011, 11:50 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •