Thread: Noob Friendly 2D Client Base

Page 1 of 2 12 LastLast
Results 1 to 10 of 14
  1. #1 Noob Friendly 2D Client Base 
    Extreme Donator


    Join Date
    Nov 2012
    Posts
    647
    Thanks given
    9
    Thanks received
    18
    Rep Power
    1301
    This client application was created for users with little to no experience with Java 2D game development!
    We all have to start off by reading our examples and javadocs, and look up tutorials for reference when starting.. So I tried to write this simple 2d client base in a very easy to understand fashion that should make sense to any new developer

    Features
    Java2D rendering
    Key & Mouse input
    Entity examples

    Controls
    Press an arrow key to step
    Click the information icon to render an 'interface'

    Preview


    Download
    Download here

    If you have questions, post them here. Do not private message me.

    If you don't have anything nice to say, keep it to yourself, and re-read the first paragraph.
    Reply With Quote  
     


  2. #2  
    Registered Member
    Rainaka's Avatar
    Join Date
    Nov 2008
    Age
    29
    Posts
    1,391
    Thanks given
    273
    Thanks received
    89
    Rep Power
    870
    Thanks! I'm downloading right now.
    Reply With Quote  
     

  3. #3  
    Registered Member
    Polish Civil's Avatar
    Join Date
    May 2010
    Age
    28
    Posts
    1,345
    Thanks given
    484
    Thanks received
    191
    Rep Power
    463
    Cool,thanks.


    Reply With Quote  
     

  4. #4  
    Registered Member
    whac's Avatar
    Join Date
    Nov 2011
    Posts
    176
    Thanks given
    35
    Thanks received
    84
    Rep Power
    245
    Not bad. However, I can't tell if you were attempting a singleton design pattern in the class com.bbghub.Cache. It confuses me. If a class has a public constructor then it really isn't a singleton, is it?

    [code=java]

    package com.bbghub;

    import java.awt.Image;
    import java.awt.Toolkit;
    import java.util.HashMap;

    public class Cache {

    private static final Cache INSTANCE = new Cache();
    private HashMap<String, Image> images = new HashMap<String, Image>();
    private final String CACHE_DIR = "./cache/raw/"; // Path to cache files
    public boolean loaded = false;

    public Cache() {
    // Load cache files
    for (int i = 0; i < Constants.SPRITE_INDEX.length; i++) {
    images.put(Constants.SPRITE_INDEX[i][0], Toolkit.getDefaultToolkit().getImage(CACHE_DIR+Con stants.SPRITE_INDEX[i][0]+"."+Constants.SPRITE_INDEX[i][1]));
    System.out.println("Added sprite '"+Constants.SPRITE_INDEX[i][0]+"' to image cache.");
    }
    loaded = true;
    }

    public Image getSprite(String name) {
    return images.get(name);
    }

    public static Cache getInstance() {
    return INSTANCE;
    }

    }
    [/code]
    Reply With Quote  
     

  5. Thankful user:


  6. #5  
    Registered Member
    Join Date
    Oct 2012
    Posts
    45
    Thanks given
    7
    Thanks received
    3
    Rep Power
    21
    hey, i'm really bad at java and using starting to use it lol.. do you mind if I use this for one of the game dev projects in my java class? and how would I run this with netbeans? tyy
    Reply With Quote  
     

  7. #6  
    Registered Member
    whac's Avatar
    Join Date
    Nov 2011
    Posts
    176
    Thanks given
    35
    Thanks received
    84
    Rep Power
    245
    Quote Originally Posted by tereve View Post
    hey, i'm really bad at java and using starting to use it lol.. do you mind if I use this for one of the game dev projects in my java class? and how would I run this with netbeans? tyy
    Of course you can use it in your projects. See the license:
    This release is free to use in your productions; public or personal.
    Special thanks to the awesome people at Browser Based Game Hub

    No credits required
    I suggest using a search engine if you need help with NetBeans.
    Reply With Quote  
     

  8. #7  
    Extreme Donator


    Join Date
    Nov 2012
    Posts
    647
    Thanks given
    9
    Thanks received
    18
    Rep Power
    1301
    @Whac: I only need to initialize the Cache class once, to load contents. The getInstance() usage is to keep static context out of the rest of the source code.
    I don't see a problem here... unless you've read something I haven't and are pointing out that this isn't following AAA quality conventions, and in that case Idc
    Reply With Quote  
     

  9. #8  
    Registered Member
    Polish Civil's Avatar
    Join Date
    May 2010
    Age
    28
    Posts
    1,345
    Thanks given
    484
    Thanks received
    191
    Rep Power
    463
    I know this isnt nice to say but drawing loop is terrible
    You should update it


    Reply With Quote  
     

  10. #9  
    Extreme Donator


    Join Date
    Nov 2012
    Posts
    647
    Thanks given
    9
    Thanks received
    18
    Rep Power
    1301
    Quote Originally Posted by Polish Civil View Post
    I know this isnt nice to say but drawing loop is terrible
    You should update it
    Don't have the src on desktop; not too concerned. If you want to update you can
    Reply With Quote  
     

  11. #10  
    Registered Member
    Polish Civil's Avatar
    Join Date
    May 2010
    Age
    28
    Posts
    1,345
    Thanks given
    484
    Thanks received
    191
    Rep Power
    463
    Processor use thing fix:

    Code:
    package com.dhareauxk;
    
    import java.awt.Canvas;
    
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.KeyEvent;
    import java.util.List;
    import java.util.concurrent.CopyOnWriteArrayList;
    
    import javax.swing.JFrame;
    
    import com.dhareauxk.input.KeyController;
    import com.dhareauxk.input.MouseController;
    import com.dhareauxk.model.Entity;
    import com.dhareauxk.model.Npc;
    import com.dhareauxk.model.Player;
    
    public class Game extends Canvas implements Runnable {
    
    	private static final long serialVersionUID = 1L;
    
    
    	// Rendering related variables
    	private int averageFrameCount;
    	private Graphics2D graphics;
    	private int applicationState = 0;
    
    	// Fps variables
    	private int ONE_SECOND_IN_NANO = 1000 * 1000 * 1000;;
    	private int reqFps = 120;
    	private int secondsRunning;
    
    	// Spawn local player
    	private List<Entity> entities = new CopyOnWriteArrayList<Entity>();
    	private final Player localPlayer = new Player(0, "user", 100, 100);
    	private final Npc anNpc = new Npc(1, "tux", 100, 100);
    
    
    	long period = ONE_SECOND_IN_NANO / reqFps;
    
    	public static void main(String args[]) {
    		System.out.println("Initializing 2D client..");
    		new Thread(new Game()).start();
    	}
    
    	public Game() {
    		JFrame frame = new JFrame(); // Create a JFrame to put the canvas on
    		frame.setTitle(Config.FRAME_TITLE);
    		frame.setSize(Config.FRAME_WIDTH, Config.FRAME_HEIGHT);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.add(this);
    		frame.setResizable(false);
    
    		// Show the frame
    		frame.validate();
    		frame.pack();
    		frame.setVisible(true);
    		frame.toFront();
    
    		// Update the dimensions of the window to allot for the overlap
    		// prevention
    		final Insets insets = frame.getInsets();
    		frame.setSize(Config.FRAME_WIDTH + insets.left + insets.right, Config.FRAME_HEIGHT + insets.top + insets.bottom);
    
    		// Set up double buffering
    		createBufferStrategy(2);
    		this.graphics = (Graphics2D) super.getGraphics(); // XXX should be
    															// right..
    
    		// Add the mouse mapper to the canvas.
    		addMouseListener(MouseController.MAPPER);
    		addMouseMotionListener(MouseController.MAPPER);
    
    		// Add the key mapper to the canvas.
    		addKeyListener(new KeyController(this));
    
    		requestFocus();
    
    		// Initialize entities
    		entities.add(localPlayer);
    		entities.add(anNpc);
    	}
    	private int totalFrameCount;
    
    	@Override
    	public void run() {
    		long 
    		endTime = 0L,
    		timeDiff = 0L,
    		startTime = 0L,
    		sleepTime = 0L,
    		overSleepTime = 0L;
    		long previousSampleTime = System.nanoTime();
    
    		while (Cache.getInstance().loaded) {
    			startTime = System.nanoTime(); // cycle start time
    			update(); // UPDATING before rendering
    			render(); // Core rendering method
    			endTime = System.nanoTime();//end time  :)
    			timeDiff = endTime - startTime;//how much cycle takes?
    			sleepTime = (period - timeDiff) - overSleepTime;
    			if(sleepTime > 0){
    				try {
    					Thread.sleep(sleepTime/(ONE_SECOND_IN_NANO/1000));//we are sleeping here so no more eating processor
    				} catch(final InterruptedException ignore){//^^  Ignore this
    					Thread.currentThread().interrupt();
    					break;
    				}
    				overSleepTime = (System.nanoTime() - endTime) - sleepTime;
    			}else{
    				overSleepTime = 0L;
    			}
    			totalFrameCount++;
    			if(System.nanoTime() - previousSampleTime > ONE_SECOND_IN_NANO){//passed one second 
    				secondsRunning++;
    				averageFrameCount = totalFrameCount/secondsRunning;
    				previousSampleTime =  System.nanoTime();
    
    			}
    		}
    	}
    
    	// Update game logic here.
    	private void update() {
    		handleMouseInput();
    	}
    
    
    	private void render() {
    		if (getBufferStrategy() == null) {
    			createBufferStrategy(3);
    			return;
    		}
    		graphics = (Graphics2D) getBufferStrategy().getDrawGraphics();
    
    		// Clear the screen
    		graphics.setColor(Color.BLACK);
    		graphics.fillRect(0, 0, super.getWidth(), super.getHeight());
    
    		switch (applicationState) {
    		case 0: // login state
    			graphics.setColor(Color.GREEN);
    			graphics.drawString("Press Enter to Play!", 100, 100);
    			break;
    		case 1: // game state
    			render2DWorld(graphics);
    			break;
    		}
    
    		// Debug hud
    		graphics.setColor(Color.BLUE);
    		graphics.drawString("Used memory: " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "MB", 5, 15);
    		graphics.drawString("FPS: " + averageFrameCount, 5, 30);
    		graphics.dispose();
    		// Show the graphics.
    		getBufferStrategy().show();
    		Toolkit.getDefaultToolkit().sync();
    
    	}
    
    	private void render2DWorld(Graphics2D graphics2) {
    		// Draw "map"
    		for (int x = 0; x < 10; x++) {
    			for (int y = 0; y < 8; y++) {
    				graphics.drawImage(Cache.getInstance().getSprite("tile"), x * 32, y * 32, null); // 32
    																									// =
    																									// tile
    																									// size
    			}
    		}
    
    		// Draw entities
    		graphics.drawImage(localPlayer.getSprite(), localPlayer.getX(), localPlayer.getY(), null);
    		graphics.drawImage(anNpc.getSprite(), anNpc.getX(), anNpc.getY(), null);
    
    		// Draw "ui"
    		graphics.setColor(Color.WHITE);
    		graphics.fillRect(0, 0, Config.FRAME_WIDTH, 36);
    		graphics.setColor(Color.BLACK);
    		graphics.drawRect(0, 0, Config.FRAME_WIDTH, 36);
    
    		// The icons..
    		graphics.drawImage(Cache.getInstance().getSprite("door"), 300, 7, null);
    		graphics.drawImage(Cache.getInstance().getSprite("information"), 280, 7, null);
    	}
    
    	// Handle key input here
    	public void handleKeyboardInput(KeyEvent e) {
    		if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
    			System.out.println("Application terminated by user.");
    			Runtime.getRuntime().exit(0);
    		}
    		switch (applicationState) {
    		case 0: // login
    			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
    				applicationState = 1;
    			}
    			break;
    		case 1: // game
    			if (e.getKeyCode() == KeyEvent.VK_M) {
    				localPlayer.setSprite("user");
    			}
    			if (e.getKeyCode() == KeyEvent.VK_F) {
    				localPlayer.setSprite("user_female");
    			}
    			if (e.getKeyCode() == KeyEvent.VK_UP) {
    				localPlayer.move(0, -5);
    			}
    			if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    				localPlayer.move(0, 5);
    			}
    			if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    				localPlayer.move(-5, 0);
    			}
    			if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    				localPlayer.move(5, 0);
    			}
    			break;
    		}
    	}
    
    	public void handleMouseInput() {
    		if (MouseController.isButtonDown(0)) {
    			// Handle left click
    			System.out.println("Left cliked @ " + MouseController.getX() + ":" + MouseController.getY());
    			if (MouseController.getX() >= 283 && MouseController.getY() <= 293) {
    				if (MouseController.getY() >= 8 && MouseController.getY() <= 19) {
    					// TODO info button
    				}
    			}
    			if (MouseController.getX() >= 302 && MouseController.getY() <= 312) {
    				if (MouseController.getY() >= 10 && MouseController.getY() <= 21) {
    					// TODO info button
    				}
    			}
    		}
    		if (MouseController.isButtonDown(1)) {
    			// Handle right click
    		}
    	}
    
    }


    Reply With Quote  
     

  12. Thankful users:


Page 1 of 2 12 LastLast

Thread Information
Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)


User Tag List

Similar Threads

  1. [613/614]Working Client[Noob-Friendly]
    By rowan092001 in forum Downloads
    Replies: 12
    Last Post: 10-13-2011, 08:21 PM
  2. Running a client on 64-bit! Noob-friendly!
    By farmerscape in forum Tutorials
    Replies: 7
    Last Post: 09-18-2010, 04:19 AM
  3. Replies: 6
    Last Post: 05-22-2009, 08:07 PM
  4. Fishing - Noob friendly.
    By Concious in forum Tutorials
    Replies: 4
    Last Post: 12-14-2008, 07:23 PM
  5. Replies: 7
    Last Post: 02-23-2008, 09:34 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
  •