Jump to content
  • Advertisement
Sign in to follow this  
  • entries
    23
  • comments
    31
  • views
    55471

Very Basic Java Game Code

Sign in to follow this  
RLS0812

972 views

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 JPanelimport 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) {}}
Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!