JavaGaming.org

September 02, 2010, 10:09:20 am *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
News:
Advanced search  
Pages: [1]   Go Down
Print
Author Topic: Basic Game  (Read 6827 times)
0 Members and 1 Guest are viewing this topic.
Gudradain
Full Member
***
Offline Offline

Posts: 158



View Profile
« on: February 05, 2010, 08:01:53 pm »

Let's start with basic.

You want to do a game and don't know where to start?

A game is usually compose of the following elements :

- Frame : The window of the game
- Canvas : The rendering surface
- GameLoop : Call the rendering and update methods
- Rendering method : All your drawing here
- Update method : All your game logic here
- Mouse and Key input : Add KeyListener, MouseListener and MouseMotionListener to the canvas

Here is a template that I use for my games. To make your own game, you just have to add your code in the render(Graphics2D g) and update(int deltaTime) methods.

I add a little test so you can run this code directly to see what it does.
Code:
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class Game implements Runnable{

final int WIDTH = 1000;
final int HEIGHT = 700;

JFrame frame;
Canvas canvas;
BufferStrategy bufferStrategy;

public Game(){
frame = new JFrame("Basic Game");

JPanel panel = (JPanel) frame.getContentPane();
panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
panel.setLayout(null);

canvas = new Canvas();
canvas.setBounds(0, 0, WIDTH, HEIGHT);
canvas.setIgnoreRepaint(true);

panel.add(canvas);

canvas.addMouseListener(new MouseControl());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);

canvas.createBufferStrategy(2);
bufferStrategy = canvas.getBufferStrategy();

canvas.requestFocus();
}

private class MouseControl extends MouseAdapter{

}

long desiredFPS = 60;
    long desiredDeltaLoop = (1000*1000*1000)/desiredFPS;
   
boolean running = true;

public void run(){

long beginLoopTime;
long endLoopTime;
long currentUpdateTime = System.nanoTime();
long lastUpdateTime;
long deltaLoop;

while(running){
beginLoopTime = System.nanoTime();

render();

lastUpdateTime = currentUpdateTime;
currentUpdateTime = System.nanoTime();
update((int) ((currentUpdateTime - lastUpdateTime)/(1000*1000)));

endLoopTime = System.nanoTime();
deltaLoop = endLoopTime - beginLoopTime;
       
        if(deltaLoop > desiredDeltaLoop){
            //Do nothing. We are already late.
        }else{
            try{
                Thread.sleep((desiredDeltaLoop - deltaLoop)/(1000*1000));
            }catch(InterruptedException e){
                //Do nothing
            }
        }
}
}

private void render() {
Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
g.clearRect(0, 0, WIDTH, HEIGHT);
render(g);
g.dispose();
bufferStrategy.show();
}

//TESTING
private double x = 0;

/**
* Overwrite this method in subclass
*/
protected void update(int deltaTime){
x += deltaTime * 0.2;
while(x > 500){
x -= 500;
}
}

/**
* Overwrite this method in subclass
*/
protected void render(Graphics2D g){
g.fillRect((int)x, 0, 200, 200);
}

public static void main(String [] args){
Game ex = new Game();
new Thread(ex).start();
}

}

Here is a game that I made with this code : http://www.gudradain.byethost12.com/geomwar.html

NOTE : If you run the code, you probably realize that the square in the animation glitter a little bit. You can remove that effect by increasing the frame rate of the game (change the variable desiredFPS).

WARNING : If you set a too high FPS (frame per second), you might have problem with the game logic.
Logged
Xyle
Full Member
***
Offline Offline

Gender: Male
Posts: 117



View Profile WWW
« Reply #1 on: February 05, 2010, 09:36:49 pm »

I will have to say that that is absolutely BEAUTIFUL!!

Very nice tutorial and awesome game to boot!!
Thank you very much for your contribution!!
Logged

Life is just a game, learn to play!
------------------------------------------
╬-YellzBellz Games!-╬ Cheesy
markfarrell
JGO n00b
*
Offline Offline

Posts: 7


View Profile
« Reply #2 on: February 07, 2010, 07:38:24 am »

I got a score over 800,000! Tongue
It just goes to show how to optimize a simple game engine with a dash of creativity and effort.  Grin
Logged
Dreamcatchermatt
Full Member
***
Offline Offline

Posts: 107


View Profile
« Reply #3 on: March 31, 2010, 03:04:08 pm »

EDIT: Ok, I think I have found a good solution. Thanks anyway Smiley

Hi, Gudradain,

I'm new on the forums here, and found the place from a google serch that got me to this tutorial.

I have been playing around with the code for your game loop, and have started working on a basic space RTS where you pilot a space ship around a solar system. At the moment its only a very rudimentary graphics and physics engine based around your code.

I have been up all night implimenting a 2D camera class using AffineTransform that alows zooming and scrolling the map. This works fine programaticaly (i can lock the camera to a moving object in the game world) but i cannot for the life of me figure out how to get mouse input to work (for manual click and drag/wheel zooming).

I muss confess, i'm new to the Java game scene, having come from a few years experience with XNA/C# game programing, and am a little uncerten how all the mouse event listening works in Java.

I would be verry greatfull if you could explain what the MouseControl class is sposed to do, and how to use this to detect dragging and wheel events, and maybe keyPresses?

Thankyou very much for an already fantastic tutorial!

Once i have something close to ready i'll post screenshots and a demo.

Matt Taylor

« Last Edit: March 31, 2010, 09:42:04 pm by Dreamcatchermatt » Logged
Pages: [1]   Go Up
Print
 
Jump to: