In Tetris, a 2d array (called board in class gamePanel) is initialized, to store idle Tetris pieces. The moving piece (called piece in class GamePanel) is constantly checking collisions: if an idle block or the bottom of the field is underneath, the piece go idle, adds to board array, and a new moving piece is added.
When checking for idle blocks underneath the moving piece, im checking if the block below is ==null in the board array, the moving piece is free to move further down. My problem is, this works fine most of the time, but quite often the program throws an NullPointerException when doing the null check (this happens in the collisionWithBoard() method in GamePanel). The Exception is thrown at complete random! Sometimes the program run for 20 seconds, others for 0. All source code is attached.
It looks like the block variable is what is null. You initialize it in the paint() method, which is probably what contributes to the problem seeming to be at random. Try initializing somewhere else other than paint().
Removing the block Object, and just calling the method piece.getPiece.get(i) directly in the code. It worked, thanks!
I can't figure out why, though. I only initialize block == null in the paint() method. In the collision method I reinitialize it to a Block value, which means it should not be able to throw an NullPointerException. Unless Java can run the paint() method in-between my Collision method, or theres some Stream delay or whatnot. Its weird, cause the program ran fine most of the time before, the Exception was only thrown sometimes.
A method like paint() gets called by code that is not under your control so it's best not to make any assumptions about when it will be called. Adding threads into the mix also complicates things and adds to the non-deterministic nature of your program flow. I would avoid using null as a boundary check altogether and find some other way to determine those conditions.