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 7 of 7

Thread: My first Java 2D Game won't work

  1. #1
    Junior Member
    Join Date
    Jan 2013
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question My first Java 2D Game won't work

    Hi there.

    I'm new on java.

    I'm following Zephyr Java 2D Game video tutorials on youtube.

    Problem :

    It should move the screen when i pressing W,A,S,D keys, but won't work. Please have look at the below classes.

    Game.java
    package ca.hamed.game;
     
    import java.awt.BorderLayout;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferStrategy;
    import java.awt.image.BufferedImage;
    import java.awt.image.DataBufferInt;
     
    import javax.swing.JFrame;
     
    import ca.hamed.game.gfx.Screen;
    import ca.hamed.game.gfx.SpriteSheet;
     
    public class Game extends Canvas implements Runnable {
     
    	private static final long serialVersionUID = 1L;
     
    	public static final int WIDTH = 160;
    	public static final int HEIGHT = WIDTH / 12 * 9;
    	public static final int SCALE = 3;
    	public static final String NAME = "Game";
     
    	private JFrame frame;
     
    	public boolean running = false;
    	public int tickCount = 0;
     
    	private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    	private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
     
    	private Screen screen;
     
    	public InputHandler input;
     
    	public Game() {
    		setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
    		setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
    		setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
     
    		frame = new JFrame(NAME);
     
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setLayout(new BorderLayout());
    		frame.add(this, BorderLayout.CENTER);
    		frame.pack();
     
    		frame.setResizable(false);
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
    	}
     
    	public void init() {
    		screen = new Screen(WIDTH, HEIGHT, new SpriteSheet("/sprite_sheet.png"));
    		input = new InputHandler(this);
    	}
     
    	public synchronized void start() {
    		running = true;
    		new Thread(this).start();
    	}
     
    	public synchronized void stop() {
    		running = false;
    	}
     
    	public void tick() {
    		tickCount++;
    		if (input.up.isPressed()) {
    			screen.yOffset--;
    		}
    		if (input.down.isPressed()) {
    			screen.yOffset++;
    		}
    		if (input.left.isPressed()) {
    			screen.xOffset--;
    		}
    		if (input.right.isPressed()) {
    			screen.xOffset++;
    		}
    	}
     
    	public void render() {
    		BufferStrategy bs = getBufferStrategy();
    		if (bs == null) {
    			createBufferStrategy(3);
    			return;
    		}
     
    		screen.render(pixels, 0, WIDTH);
     
    		Graphics g = bs.getDrawGraphics();
    		g.setColor(Color.black);
    		g.drawRect(0, 0, getWidth(), getHeight());
    		g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
    		g.dispose();
     
    		bs.show();
    	}
     
    	public void run() {
    		long lastTime = System.nanoTime();
    		double nsPerTick = 1000000000D / 60D;
     
    		int ticks = 0;
    		int frames = 0;
     
    		long lastTimer = System.currentTimeMillis();
    		double delta = 0;
     
    		init();
     
    		while (running) {
    			long now = System.nanoTime();
    			delta += (now - lastTime) / nsPerTick;
    			lastTime = now;
    			boolean shouldRender = true;
     
    			while (delta >= 1) {
    				ticks++;
    				tick();
    				delta -= 1;
    				shouldRender = true;
    			}
    			try {
    				Thread.sleep(2);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			if (shouldRender) {
    				frames++;
    				render();
    			}
     
    			if (System.currentTimeMillis() - lastTimer >= 1000) {
    				lastTimer += 1000;
    				System.out.println(ticks + " ticks , " + frames + " frames");
    				frames = 0;
    				ticks = 0;
    			}
    		}
    	}
     
    	public static void main(String[] args) {
    		new Game().start();
    	}
     
    }

    SpriteSheet.java
    package ca.hamed.game.gfx;
     
    import java.awt.image.BufferedImage;
    import java.io.IOException;
     
    import javax.imageio.ImageIO;
     
    public class SpriteSheet {
    	public String path;
    	public int width;
    	public int height;
     
    	public int[] pixels;
     
    	public SpriteSheet(String path) {
    		BufferedImage image = null;
    		try {
    			image = ImageIO.read(SpriteSheet.class.getResourceAsStream(path));
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		if (image == null) {
    			return;
    		}
    		this.path = path;
    		this.width = image.getWidth();
    		this.height = image.getHeight();
     
    		pixels = image.getRGB(0, 0, width, height, null, 0, width);
     
    		for (int i = 0; i < pixels.length; i++) {
    			pixels[i] = (pixels[i] & 0xff) / 64;
    		}
    	}
    }

    Screen.java
    package ca.hamed.game.gfx;
     
    public class Screen {
    	public static final int MAP_WIDTH = 64;
    	public static final int MAP_WIDTH_MASK = MAP_WIDTH - 1;
     
    	public int[] tiles = new int[MAP_WIDTH * MAP_WIDTH];
    	public int[] colours = new int[MAP_WIDTH * MAP_WIDTH * 4];
     
    	public int xOffset = 0;
    	public int yOffset = 0;
     
    	public int width;
    	public int height;
     
    	public SpriteSheet sheet;
     
    	public Screen(int width, int height, SpriteSheet sheet) {
    		this.width = width;
    		this.height = height;
    		this.sheet = sheet;
     
    		for (int i = 0; i < MAP_WIDTH * MAP_WIDTH; i++) {
    			colours[i * 4 + 0] = 0xff00ff;
    			colours[i * 4 + 1] = 0x00ffff;
    			colours[i * 4 + 2] = 0x00ffff;
    			colours[i * 4 + 3] = 0xffffff;
    		}
    	}
     
    	public void render(int[] pixels, int offset, int row) {
    		for (int yTile = yOffset >> 3; yTile <= (yOffset + height) >> 3; yTile++) {
    			int yMin = yTile * 8 - yOffset;
    			int yMax = yMin + 8;
     
    			if (yMin < 0) yMin = 0;
    			if (yMax > height) yMax = height;
     
    			for (int xTile = xOffset >> 3; xTile <= (xOffset + width) >> 3; xTile++) {
    				int xMin = xTile * 8 - xOffset;
    				int xMax = xMin + 8;
     
    				if (xMin < 0) xMin = 0;
    				if (xMax > width) xMax = width;
     
    				int tileIndex = (xTile & (MAP_WIDTH_MASK)) + (yTile & (MAP_WIDTH_MASK)) * MAP_WIDTH;
     
    				for (int y = yMin; y < yMax; y++) {
    					int sheetPixel = ((y + yOffset) & 7) * sheet.width + ((xMin + xOffset) & 7);
    					int tilePixel = offset + xMin + y * row;
    					for (int x = xMin; x < xMax; x++) {
    						int colour = tileIndex * 4 + sheet.pixels[sheetPixel++];
    						pixels[tilePixel++] = colours[colour];
    					}
    				}
    			}
    		}
    	}
    }

    InputHandler.java
    package ca.hamed.game;
     
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.ArrayList;
    import java.util.List;
     
    public class InputHandler implements KeyListener {
     
    	public InputHandler(Game game) {
    		game.addKeyListener(this);
    	}
     
    	public class Key {
    		private boolean pressed = false;
     
    		public boolean isPressed() {
    			return pressed;
    		}
     
    		public void toggle(boolean isPressed) {
    			pressed = isPressed;
    		}
    	}
     
    	public List<Key> keys = new ArrayList<Key>();
     
    	public Key up = new Key();
    	public Key down = new Key();
    	public Key left = new Key();
    	public Key right = new Key();
     
    	public void keyPressed(KeyEvent e) {
    		toggleKey(e.getKeyCode(), true);
    	}
     
    	public void keyReleased(KeyEvent e) {
    		toggleKey(e.getKeyCode(), false);
    	}
     
    	public void keyTyped(KeyEvent e) {
     
    	}
     
    	public void toggleKey(int keyCode, boolean isPressed) {
    		if (keyCode == KeyEvent.VK_W) {
    			up.toggle(true);
    		}
    		if (keyCode == KeyEvent.VK_S) {
    			down.toggle(true);
    		}
    		if (keyCode == KeyEvent.VK_A) {
    			left.toggle(true);
    		}
    		if (keyCode == KeyEvent.VK_D) {
    			right.toggle(true);
    		}
    	}
    }

    Any helps would be great awesome.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: My first Java 2D Game won't work

    won't work.
    Have you tried to debug the code to see where the problem is? For example: Add some println statements to the key listeners methods to see if they are being called.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    Kamrava (October 18th, 2013)

  4. #3
    Junior Member
    Join Date
    Jan 2013
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: My first Java 2D Game won't work

    Quote Originally Posted by Norm View Post
    Have you tried to debug the code to see where the problem is? For example: Add some println statements to the key listeners methods to see if they are being called.
    It run successfully. There is a logical problem

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: My first Java 2D Game won't work

    There is an logical problem
    Please explain. What is the problem? Where is the code not doing what you want it to do?
    Continue debugging the code by adding more println statements that print out messages when the values of variables change and when methods are called. The print out will help you see what the code is doing and help you isolate where the problem is.

    It run successfully.
    What does that mean? If the program runs successfully, does that mean there aren't any problems?
    If you don't understand my answer, don't ignore it, ask a question.

  6. #5
    Junior Member
    Join Date
    Jan 2013
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: My first Java 2D Game won't work

    I mean it does not have any syntax errors. It runs without any problems. But when the screen shows up it must move through W,A,S,D keys but won't work.
    I can't explain more...

  7. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: My first Java 2D Game won't work

    So are W, A, S, and D key presses being seen by the key listeners, firing an action? Add some code to the key listener methods to see what is happening or not happening. If you find the key presses aren't being seen and acted upon, trace it back further and keep tracing it back until you find the break in logic. If there is no break in the logic that you can find, then make sure you've implemented the key listening mechanism correctly.

    This is basic debugging stuff you should learn how to do.

  8. The Following User Says Thank You to GregBrannon For This Useful Post:

    Kamrava (October 19th, 2013)

  9. #7
    Junior Member
    Join Date
    Jan 2013
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: My first Java 2D Game won't work

    Thank you. I found it, the problem was right there :
    public void toggleKey(int keyCode, boolean isPressed) {
    		if (keyCode == KeyEvent.VK_W) {
    			up.toggle(true);
    		}
    		if (keyCode == KeyEvent.VK_S) {
    			down.toggle(true);
    		}
    		if (keyCode == KeyEvent.VK_A) {
    			left.toggle(true);
    		}
    		if (keyCode == KeyEvent.VK_D) {
    			right.toggle(true);
    		}
    	}

    Should change to :
    public void toggleKey(int keyCode, boolean isPressed) {
    		if (keyCode == KeyEvent.VK_W) {
    			up.toggle(isPressed);
    		}
    		if (keyCode == KeyEvent.VK_S) {
    			down.toggle(isPressed);
    		}
    		if (keyCode == KeyEvent.VK_A) {
    			left.toggle(isPressed);
    		}
    		if (keyCode == KeyEvent.VK_D) {
    			right.toggle(isPressed);
    		}
    	}

    Cheers

Similar Threads

  1. Image won't work!
    By mkrage in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 26th, 2012, 05:08 PM
  2. Why won't this for loop work?
    By vwillis in forum Loops & Control Statements
    Replies: 1
    Last Post: October 14th, 2011, 12:49 PM
  3. MergeSort won't work
    By joshft91 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: February 7th, 2011, 09:44 PM
  4. begginer wondering why his guessing game won't work
    By Ligawulf in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 8th, 2010, 12:22 AM
  5. Why won't this while loop work?
    By trueblue in forum Loops & Control Statements
    Replies: 2
    Last Post: July 17th, 2009, 09:10 AM