Hi, I'm trying to program Tetris. The thing is, I can't seem to get the Keylistener to work in the JApplet, and I have no idea why :(
Here's my code:
import java.util.Random;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
/**
* Class Tetris - write a description of the class here
*
* @author (Neil Semmel)
* @version (Nov. 7, 2008)
*/
public class Tetris extends JApplet implements KeyListener
{
Random randy = new Random();
shapes test = new shapes();
public int x_pos = 220;
public int y_pos = 0;
public void init()
{
this.addKeyListener(this);
}
public void paint(Graphics g)
{
getPiece(g);
}
// ----- Key Events -----
public void keyPressed(KeyEvent e)
{
char code = e.getKeyChar();
if(code == 'a')
x_pos = x_pos-20;
if(code == 'd')
x_pos = x_pos+20;
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
// ----- End Key Events -----
public void reDraw(Graphics g)
{
g.setColor(Color.WHITE);
g.fillRect(0,0,500,500);
}
public void sleep(int time)
{
long now = System.currentTimeMillis();
while(now+time > System.currentTimeMillis());
}
public void getPiece(Graphics g)
{
int pieceNum = randy.nextInt(7);
switch(pieceNum)
{
case 0:
test.drawPiece1(g,x_pos,y_pos);
break;
case 1:
test.drawPiece2(g,x_pos,y_pos);
break;
case 2:
test.drawPiece3(g,x_pos,y_pos);
break;
case 3:
test.drawPiece4(g,x_pos,y_pos);
break;
case 4:
test.drawPiece5(g,x_pos,y_pos);
break;
case 5:
test.drawPiece6(g,x_pos,y_pos);
break;
case 6:
test.drawPiece7(g,x_pos,y_pos);
break;
}
}
}