Unable to make loop work properly+ActionEvent

31 Views Asked by At

Very very new to coding trying to make/copy a simple snake game to mess around with. there is a part of the code to make the snake move across the pannel, but for some reason my snake will only move one block then stop, and only if I set the move(); method to run on its own without input. I want to be able to press a key to begin movement with ActionEvent e, but it for some reason is not working project consists of 3 classes (this is my firs time on this site very sorry if im doing this wrong).

this is the move method '''

 public void move() { 
    System.out.println(" running"); 

    for (int i = bodyParts;i>0; i--) {
        x[i] = x[i-1];
        y[i] = y[i-1];
    }
    switch(direction) {
    case 'U': 
        y[0] = y[0] - unitSize;
        break;
    case 'D':
        y[0] = y[0] + unitSize;
        break;
    case 'L':
        x[0] = x[0] - unitSize;
        break;
    case 'R':
        x[0] = x[0] + unitSize;
        break;
        
    }
    
}

'''

               @Override 
 public void actionPerformed(ActionEvent e) {

    if (running) {
    System.out.print("action working");
    move();
    checkApple();
    checkCollisions();
        
    } else {
    repaint();
    }
    
    
}

'''

'''
public class GamePanel extends JPanel implements ActionListener{

static final int sWidth = 700;
static final int sHeight = 700;
static final int unitSize = 25;
static final int gameUnits = (sWidth*sHeight)/unitSize;
static final int Delay = 100;
final int x[] = new int[gameUnits];
final int y[] = new int[gameUnits];
int bodyParts = 6;
int applesEaten;
int appleX;
int appleY;
int gameON;
char direction = 'R';
boolean running = false;
Timer timer; 
Random random;



GamePanel(){
    random = new Random();
    this.setPreferredSize(new Dimension(sWidth,sHeight));
    this.setBackground(Color.black);
    this.setFocusable(true);
    this.addKeyListener(new MyKeyAdapter());
    this.
    startGame();
    move();
    System.out.print("running = " +running);
    
     
    
    
    
    
    
}


public void startGame() {
    newApple();
    running = true;
    gameON = 1 ;
    //timer = new Timer(Delay,timer);
    //timer.start();
    
}

'''

Blue and green dots are the snake

0

There are 0 best solutions below