/*
Canvas Sample
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
class CanvasSample extends Canvas
{
private static final int FRAME_WIDTH = 800;
private static final int FRAME_HEIGHT = 600;
private static final int FRAME_X_ORIGIN = 50;
private static final int FRAME_Y_ORIGIN = 50;
private BufferedImage bi;
public BufferStrategy bs;
public int iPosX, iPosY;
public boolean up, down, left, right, endGame;
public CanvasSample( )
{
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setLocation(0,0);
addKeyListener(new KeyStroke());
}
public static void main(String[] args)
{
JFrame j = new JFrame();
Container contentPane = j.getContentPane();
j.setTitle ("JButtonEvents");
j.setSize (FRAME_WIDTH, FRAME_HEIGHT);
j.setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
j.setResizable(false);
j.setVisible(true);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CanvasSample c = new CanvasSample();
contentPane.add(c);
c.init();
c.gameLoop();
}
public void init()
{
createBufferStrategy(2);
bs = getBufferStrategy();
try
{
bi = ImageIO.read(new File("strat.png"));
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null, "error");
}
}
public void gameLogic()
{
if(up)
{
iPosY = iPosY - 1;
}
if(down)
{
iPosY = iPosY + 1;
}
if(left)
{
iPosX = iPosX - 1;
}
if(right)
{
iPosX = iPosX + 1;
}
if (iPosX > 100 && iPosY > 100)
{
JOptionPane.showMessageDialog(null, "Its a hit!");
}
}
public void gameLoop()
{
while(!endGame)
{
gameLogic();
//put this at the top for clearing screen
Graphics g = bs.getDrawGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,FRAME_WIDTH,FRAME_HEIGHT);
g.setColor(Color.BLACK);
g.fillRect(0,0,50,100);
g.drawImage(bi,iPosX,iPosY,bi.getWidth(),bi.getHeight(),null);
try
{
Thread.sleep(10);
}
catch(Exception e)
{
}
finally
{
// put this at the bottom for showing
bs.show();
}
}
JOptionPane.showMessageDialog(null, "The Game has ended");
}
class KeyStroke implements KeyListener
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode()==KeyEvent.VK_ESCAPE)
{
endGame = true;
}
if (e.getKeyCode()==KeyEvent.VK_UP)
{
up = true;
}
if (e.getKeyCode()==KeyEvent.VK_DOWN)
{
down = true;
}
if (e.getKeyCode()==KeyEvent.VK_LEFT)
{
left = true;
}
if (e.getKeyCode()==KeyEvent.VK_RIGHT)
{
right = true;
}
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode()==KeyEvent.VK_UP)
{
up = false;
}
if (e.getKeyCode()==KeyEvent.VK_DOWN)
{
down = false;
}
if (e.getKeyCode()==KeyEvent.VK_LEFT)
{
left = false;
}
if (e.getKeyCode()==KeyEvent.VK_RIGHT)
{
right = false;
}
}
public void keyTyped(KeyEvent e)
{
}
}
}