Jump to content

  • Log In with Google      Sign In   
  • Create Account

Interested in a FREE copy of HTML5 game maker Construct 2?

We'll be giving away three Personal Edition licences in next Tuesday's GDNet Direct email newsletter!

Sign up from the right-hand sidebar on our homepage and read Tuesday's newsletter for details!






Very Basic Java Game Code

Posted by Shippou, in Java 02 March 2014 · 341 views

Java
Here is the working code for a very basic Java game were you move an oval around the screen.
This is to demonstrate the basics of paint(), KeyListener, JFrame and JPanel
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel implements KeyListener{
private int x = 5, y = 5;   
private int speed = 5;
private Dimension dimension = new Dimension(500,400);

    public Main(){
        setSize(dimension);
        setPreferredSize(dimension);
        setFocusable(true);
        addKeyListener(this);
        }
   
    @Override
    public void update (Graphics g){
        paint(g);
    }
   
    public void paint(Graphics g){
        g.setColor(Color.black);
        g.fillRect(0, 0, getWidth(), getHeight());
       
        g.setColor(Color.white);
        g.fillOval(x,y,20,20);
        repaint();
    }
   
    public static void main (String[] args){
        Main game = new Main();
        JFrame frame = new JFrame();
        frame.setTitle("Game");
        frame.add(game);
        frame.pack();
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        }
   
    @Override
    public void keyPressed(KeyEvent e) {
        int c = e.getKeyCode();
        if ( c == KeyEvent.VK_W){ y -= speed;}
        if ( c == KeyEvent.VK_S){ y += speed;}
        if ( c == KeyEvent.VK_A){ x -= speed;}
        if ( c == KeyEvent.VK_D){ x += speed;}
        }
   
    @Override
    public void keyReleased(KeyEvent e) {}

    @Override
    public void keyTyped(KeyEvent e) {}
}





PARTNERS