Tutorials / Index / Prev /
Ever wanted constant updating on your canvas but be able to catch events. If so then threads are what you need. Threads are needed for almost all games. They allow you to get the current system time, and delay a specified number of miliseconds, so that your frames will be in sync.

UP : W, DOWN : S. If CAN'T MOVE, CLICK IN AREA.

THIS IS THE CODE FOR THE THREAD:

// Dy Derek Jones 2000

//-----------------------------------------------------------------------------
// Import Files
//-----------------------------------------------------------------------------

import java.awt.*;
import java.applet.Applet;

//-----------------------------------------------------------------------------
// BufferedThread
//-----------------------------------------------------------------------------

public class Pong extends Applet implements Runnable
{	
	//-------------------------------------------------------------------------
	// Variables
	//-------------------------------------------------------------------------
	
	// Thread
	Thread myThread;
	
	// Font
	Font font = new Font("ARIAL", Font.BOLD, 20);
	
	// Buffered Graphics
	Dimension offDimension;
	Image offImage;
	Graphics offGraphics;
	
	// Game objects
	Paddle p1;
	Paddle p2;
	Ball ball;
	
	///////////////////////////////////////////////////////////
	// Name: init()
	// Desc: Sets up Applet
	///////////////////////////////////////////////////////////

	public void init()
	{
		// Get the focus
		requestFocus();
		
		// Setup game objects
		Dimension d = size();
		p1 = new Paddle(d);
		p2 = new Paddle(d);
		p2.x = d.width - p2.w;
		ball = new Ball(d);
	}
	
	//-------------------------------------------------------------------------
	// Thread
	//-------------------------------------------------------------------------

	///////////////////////////////////////////////////////////
	// Name: start()
	// Desc: Starts the Applet
	///////////////////////////////////////////////////////////
	
	public void start()
	{
		if (myThread == null)
		{
			myThread = new Thread(this);
			myThread.start();
		}
	}

	///////////////////////////////////////////////////////////
	// Name: stop()
	// Desc: stops the Applet
	///////////////////////////////////////////////////////////
	
	public void stop()
	{
		if (myThread != null)
		{
			myThread.stop();
			myThread = null;
		}
	}

	///////////////////////////////////////////////////////////
	// Name: run()
	// Desc: Main method
	///////////////////////////////////////////////////////////
	
	public void run()
	{
		long lastTime;
		int delay = 50;
		
		// Lower this thread's priority and get the current time.
		Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
		
		// This is the main loop.
		while (Thread.currentThread() == myThread)
		{
			// Get the time
			lastTime = System.currentTimeMillis();
			
			// Update and Paint.
			update();
			paint();
			
			// Sleep for delay in milliseconds minus what time it took to update and paint
			// while sleeping catch any event
			try
			{
				lastTime += delay;
				Thread.sleep(Math.max(0, lastTime - System.currentTimeMillis()));
			}
			catch(InterruptedException e) // get keydowns, mousemove, etc.
			{
				break;
			}
		}
	}
	
	//-------------------------------------------------------------------------
	// Program
	//-------------------------------------------------------------------------
	
	///////////////////////////////////////////////////////////
	// Name: update()
	// Desc: Updates objects
	///////////////////////////////////////////////////////////
	
	void update()
	{
		// Update game objects
		for(int i = 0; i < 3; i++)
		{
			ball.move();
			
			p1.update();
			
			if(i != 0)
			{
				if(p2.y > ball.y + ball.h/2 - p2.h/2) p2.y--;
				else if(p2.y < ball.y + ball.h/2 - p2.h/2) p2.y++;
			}
			
			p2.update();
			
			if(ball.hitPaddle(p1))
			{
				ball.bounceX();
				ball.x = p1.x+p1.w;
			}
			else if(ball.hitPaddle(p2))
			{
				ball.bounceX();
				ball.x = p2.x - ball.w;
			}	
			
			ball.update();
		}
	}
	
	///////////////////////////////////////////////////////////
	// Name: paint()
	// Desc: paints objects and other info using buffer
	///////////////////////////////////////////////////////////
	
	void paint()
	{
		// Get the Graphics of the screen and the size
		Graphics g = getGraphics();
		Dimension d = size();
		
		// Create the offscreen graphics context, if no good one exists
		if (offGraphics == null || d.width != offDimension.width || d.height != offDimension.height)
		{
			offDimension = d;
			offImage = createImage(d.width,d.height);
			offGraphics = offImage.getGraphics();
		}
		
		//Clear screen
		offGraphics.setColor(Color.lightGray);
		offGraphics.fillRect(0,0,d.width,d.height);
		
		// Draw game objects
		offGraphics.setFont(font);
		offGraphics.setColor(Color.black);
		offGraphics.drawString("" + ball.scoreLeft,20,d.height-2);
		offGraphics.drawString("" + ball.scoreRight,d.width - 32,d.height-2);
		p1.paint(offGraphics);
		p2.paint(offGraphics);
		ball.paint(offGraphics);
		
		// Copy the off screen buffer to the screen.
		g.drawImage(offImage, 0, 0 , this);
	}
	
	//-------------------------------------------------------------------------
	// Events
	//-------------------------------------------------------------------------
	
	///////////////////////////////////////////////////////////
	// Name: keyDown()
	// Desc: if keys are pressed
	///////////////////////////////////////////////////////////
	
	public boolean keyDown(Event e, int key)
	{
		switch(key)
		{
			case 'w':
			case 'W':
				p1.y-=5;
				break;
			case 's':
			case 'S':
				p1.y+=5;
				break;	
		}
		return true;
	}
}

//-------------------------------------------------------------------------
// Paddle
//-------------------------------------------------------------------------
	
class Paddle
{
	Dimension screen;
	
	int x;
	int y;
	int w;
	int h;
	
	Paddle(Dimension d)
	{
		screen = d;
		x = 0;
		y = 0;
		w = 10;
		h = 30;
	}
	
	void update()
	{
		if(y < 0) y = 0;
		if(y+h > screen.height) y = screen.height-h; 
	}
	
	void paint(Graphics g)
	{
		g.setColor(Color.blue);
		g.fillRect(x,y,w,h);
	}
}

//-------------------------------------------------------------------------
// Ball
//-------------------------------------------------------------------------

class Ball
{
	Dimension screen;
	
	int scoreLeft;
	int scoreRight;
	
	int x;
	int y;
	int w;
	int h;
	
	int speedX;
	int speedY;
	
	Ball(Dimension d)
	{
		screen = d;
		x = 10;
		y = 10;
		w = 10;
		h = 10;
		speedX = 4;
		speedY = 1;
		scoreLeft = 0;
		scoreRight = 0;
	}
	
	void bounceX()
	{
		speedX = -speedX;
	}
	
	void bounceY()
	{
		speedY = -speedY;
	}
	
	void move()
	{
		x+=speedX;
		y+=speedY;
	}
		
	boolean hitPaddle(Paddle pad)
	{
		if((x < (pad.x+pad.w) && (x+w) > pad.x) && (y < (pad.y+pad.h) && (y+h) > pad.y)) return true;
		return false;
	}
		
	void update()
	{
		// bounce
		if(y <= 0)
		{
			y = 0;
			bounceY();
			
		}	
		else if(y+h >= screen.height)
		{
			y = screen.height-h;
			bounceY();
		}
		
		// if hits sides star of in middle
		if(x <= 0)
		{
			bounceX();
			scoreLeft++;
		}	
		else if(x+w >= screen.width)
		{
			bounceX();
			scoreRight++;
		}
		
		if(scoreRight >= 7 || scoreLeft >= 7)
		{
			scoreLeft = 0;
			scoreRight = 0;
		}
	}
	
	void paint(Graphics g)
	{
		g.setColor(Color.red);
		g.fillOval(x,y,w,h);
	}
}
Hosted by www.Geocities.ws

1