I am making myself a tetris clone in java, as a learning project. However I am now stuck at the part of getting the input for moving the piece left and right. I am not sure if the problem is in my methods, or is in the keyPressed method not being called I didn't have success in debugging as it ignored the method. Here is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.*;
public class MainClass implements KeyListener{
public static Painter painter = new Painter();
public static LShape tetr = new LShape(150,0);
public static void main(String[] args) throws InterruptedException {
JFrame window = new JFrame("Tetris");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(300, 560);
window.setBackground(Color.BLUE);
window.getContentPane().add(painter);
window.setVisible(true);
ArrayList<Block> blocks = new ArrayList<Block>();
ArrayList<Block> staticBlocks = new ArrayList<Block>();
while(true){
tetr = new LShape(150, 0);
for (int i = 0; i < tetr.iterations; i++) {
blocks = new ArrayList<Block>(Arrays.asList(tetr.getBlocks()));
blocks.addAll(staticBlocks);
painter.setBlocks(blocks);
tetr.changeY(5);
Thread.sleep(35);
painter.repaint();
}
staticBlocks.addAll(blocks);
}
}
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) { //I am not sure if this is even called
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT:
tetr.changeX(20);
break;
case KeyEvent.VK_LEFT:
tetr.changeX(-20);
}
}
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}