lundi 31 juillet 2023

Cant get rand int back

so im trying to build a snake game, and for somehow, while generating a new apple, im always getting the same results (cords are 0,0) Any idea? Im using VSCode btw.

import java.awt.event.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.util.Random;

public class GamePanel extends JPanel implements ActionListener {
    static final int SCREEN_WIDTH = 600;
    static final int SCREEN_HEIGHT = 600;
    static final int UNIT_SIZE = 25;
    static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE;
    static final int DELAY = 75;
    final int x[] = new int[GAME_UNITS];
    final int y[] = new int[GAME_UNITS];
    int bodyParts = 6;
    int applesEaten;
    public int appleX;
    public int appleY;
    char direction = 'R';
    boolean running = false;
    Timer timer;
    Random random;

    GamePanel() {
        random = new Random();
        this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
        this.setBackground(Color.BLACK);
        this.setFocusable(true);
        this.addKeyListener(new MyKeyAdapter());
        this.requestFocusInWindow(); // Request focus for the GamePanel
    }
    

    public void startGame() {
        newApple();
        running = true;
        timer = new Timer(DELAY,this);
        timer.start();
    }
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        draw(g);

    }
    public void draw(Graphics g) {

        /*for(int i=0;i<SCREEN_HEIGHT/UNIT_SIZE;i++) {
            g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
            g.drawLine(0,i*UNIT_SIZE ,SCREEN_WIDTH, i*UNIT_SIZE);
        }*/
        g.setColor(Color.red);
        g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
    }
    public void newApple() {
        // Generate random coordinates within the game grid
        appleX = random.nextInt((SCREEN_WIDTH / UNIT_SIZE)) * UNIT_SIZE;
        appleY = random.nextInt((SCREEN_HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
    }    

    public void move() {

    }
    public void checkApple() {

    }
    public void checkCollisions() {
        
    }
    public void gameOver() {

    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // Call move() and checkCollisions() methods here if needed
        repaint(); // This will trigger a repaint of the panel
    }    

    public class MyKeyAdapter extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {

        }
    }   
}

I tried to get randint, between like 0-600, and im always getting 0. I tried to set the value of appleX to an static int (appleX = 152;), and got the same result.




Aucun commentaire:

Enregistrer un commentaire