I am a bit inexperienced when it comes to using timers, especially in graphical programs.
I am trying to code a simple Tunnel game where the player is moving through a randomly generated tunnel and has to move left and right to avoid touching the walls.
Here is my code:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Tunnel extends JFrame{ public static final boolean empty = true; public static final boolean full = false; public static boolean [][] board = new boolean[400][400]; public Tunnel(){ add(new DrawTunnel()); setTitle("Tunnel"); setLocation(300,100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().setSize(410,425); setSize(417,440); } public static void main (String[] args){ Tunnel frame = new Tunnel(); frame.setVisible(true); } static class DrawTunnel extends JPanel{ Timer timer; int middle = 200; int width = 100; public DrawTunnel(){ //create timer timer = new Timer (5, new TimerListener()); timer.start(); emptyBoard(); } public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.black); for (int row= 0; row<board.length; row++){ for (int col=0; col<board[row].length; col++){ if (!board[row][col]) drawSquare(g, row,col); } } } public void drawSquare(Graphics g, int x, int y){ g.drawRect(x, y, 1, 1); } public void emptyBoard(){ for (int r=0; r<board.length; r++){ for (int c=0; c<board[r].length; c++){ board[r][c] = true; } } } class TimerListener implements ActionListener{ public void actionPerformed(ActionEvent e){ for (int r = board.length-2;r>=0;r--){ setRow(r,r+1); } drawTopLine(middle, width, 0); repaint(); validate(); } public void setRow(int rowOverwritten, int rowBeingCopied){ for (int c=0; c<board[rowBeingCopied].length; c++){ board[rowOverwritten][c] = board[rowBeingCopied][c]; } } public void setRow(boolean[][] board, int rowNum, boolean [] row){ for (int c=0; c<board[rowNum].length; c++){ board[rowNum][c] = row[rowNum]; } } public void drawTopLine(int gapMiddle, int gapWidth, int row){ for (int c=0; c<board[row].length; c++){ board[c][row] = false; } //forming gap for (int c = gapMiddle - (gapWidth/2); c<gapMiddle + (gapWidth/2); c++){ board[c][row] = true; } } } } }
When I run the program, only 1 row of pixelated "tunnel" appears at the top of the screen. Since I am not quite familiar with the Timer class and uses it for repetition, I guessed that I was misusing the timer. Where do I put the code to move all "tunnel walls" down and generate a new random one at the top?