Gra Ping Pong i problem z NullPointerException...

0

Cześć, jak w tytule na 3 - 4 uruchomienia na 5 wyrzuca mi null pointer exception.
Bez tytułu.jpg
Próbowałem jakoś debugerem zlokalizować problem, ale nie bardzo ogarniam jego obsługę... :/ Wyjątek wyrzuca mi albo na ball.move(); albo na player.move(); (linie 188 i 189 ostatnia klasa) Ktoś z was może widzi problem?

Piłka:

import java.awt.*;
import java.util.Random;

public class Ball implements BallInterface {

    private static final Random random = new Random();
    private static int initialSpeed = 2;

    public int ballHorizontalVelocity;
    public int ballVerticalVelocity;

    private Rectangle rectangle;

    public Ball(int xPosition, int yPosition, int xSize, int ySize) {
        this.rectangle = new Rectangle(xPosition, yPosition, xSize, ySize);
        initBall();
    }

    @Override
    public void initBall() {
        int randomXDirection = random.nextInt(2);
        int randomYDirection = random.nextInt(2);
        if (randomXDirection == 0) {
            randomXDirection--;
        }

        setXDirection(randomXDirection * initialSpeed);

        if (randomYDirection == 0) {
            randomYDirection--;
        }

        setYDirection(randomYDirection * initialSpeed);
    }

    @Override
    public void setXDirection(int randomXDirection) {
        ballHorizontalVelocity = randomXDirection;
    }

    @Override
    public void setYDirection(int randomYDirection) {
        ballVerticalVelocity = randomYDirection;
    }

    @Override
    public void move() {
        rectangle.x += ballHorizontalVelocity;
        rectangle.y += ballVerticalVelocity;
    }

    @Override
    public void draw(Graphics g) {
        g.setColor(new Color(241, 144, 39));
        g.fillOval(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
    }

    public boolean intersects(Rectangle rectangle) {
        return this.rectangle.intersects(rectangle);
    }

    public int getVerticalPos() {
        return rectangle.y;
    }

    public int getHorizontalPos() {
        return rectangle.x;
    }

    public int getYVelocity() {
        return ballVerticalVelocity;
    }

    public int getXVelocity() {
        return ballHorizontalVelocity;
    }
}

Gracz (paletka):


import java.awt.*;
import java.awt.event.KeyEvent;

public class Paddle implements PaddleInterface {

    private Rectangle rectangle;
    public int paddleVerticalVelocity;
    private static final int ballSpeed = 10;

    public Paddle(int xPosition, int yPosition, int PADDLE_WIDTH, int PADDLE_HEIGHT) {
        rectangle = new Rectangle(xPosition, yPosition, PADDLE_WIDTH, PADDLE_HEIGHT);
    }

    @Override
    public void setYDirection(int yDirection) {
        paddleVerticalVelocity = yDirection;
    }

    @Override
    public void movePaddle(KeyEvent key) {

        if (key.getKeyCode() == KeyEvent.VK_W) {
            setYDirection(-ballSpeed);
        }

        if (key.getKeyCode() == KeyEvent.VK_S) {
            setYDirection(ballSpeed);
        }

        if (key.getKeyCode() == KeyEvent.VK_UP) {
            setYDirection(-ballSpeed);
        }

        if (key.getKeyCode() == KeyEvent.VK_DOWN) {
            setYDirection(ballSpeed);
        }
    }

    @Override
    public void stopPaddle(KeyEvent key) {

        if (key.getKeyCode() == KeyEvent.VK_W) {
            setYDirection(0);
        }

        if (key.getKeyCode() == KeyEvent.VK_S) {
            setYDirection(0);
        }

        if (key.getKeyCode() == KeyEvent.VK_UP) {
            setYDirection(0);
        }

        if (key.getKeyCode() == KeyEvent.VK_DOWN) {
            setYDirection(0);
        }
    }

    @Override
    public void move() {
        rectangle.y = rectangle.y + paddleVerticalVelocity;
    }

    @Override
    public void draw(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(rectangle.x, rectangle.y ,rectangle.width, rectangle.height);
    }

    public Rectangle getRectangle() {
        return rectangle;
    }

    public int getVerticalPos() {
        return rectangle.y;
    }

    public void setVerticalPos(int pos) {
        this.rectangle.y = pos;
    }
}

Rozgrywka:


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Skirmish extends GUIState implements SkirmishInterface {

    private static final int PADDLE_WIDTH = 25;
    private static final int PADDLE_HEIGHT = 100;
    private static final int BALL_DIAMETER = 20;
    private static final int MAX_POINTS = 11;
    private static final int FIELD_HEIGHT = 124;
    private static final int FIELD_WIDTH = 1;
    private static final int speedUpBallWhenDificultyIsHeigherThen55 = 55;
    private static final List<Integer> ballVerticalYPosition = new ArrayList<>();
    private static final File backgroundFile = new File("src/main/resources/static/pongTable.jpg");
    private static final Random random = new Random();
    private static final Field field = new Field((GameEngine.WIDTH / 4) * 3 - 20, GameEngine.HEIGHT / 2 - FIELD_HEIGHT / 2, FIELD_WIDTH, FIELD_HEIGHT);

    private int ballTouchPaddle;
    private int randomEnemyMistakeSecondStrategy;
    private int randomEnemyMistake;
    private int randomDificultStrategy;
    private BufferedImage backgroundImage;
    private Paddle player;
    private Enemy enemy;
    private Ball ball;
    private Scores scores;

    public Skirmish(GUIStateManager GUIStateManager) {
        this.GUIStateManager = GUIStateManager;
        this.scores = new Scores();
    }

    @Override
    public void newPaddles() {
        randomEnemyMistake = random.nextInt(100) + 1;
        randomDificultStrategy = random.nextInt(3) + 1;
        randomEnemyMistakeSecondStrategy = random.nextInt(3) + 5;
        player = new Paddle(0, (GameEngine.HEIGHT / 2) - (PADDLE_HEIGHT / 2), PADDLE_WIDTH, PADDLE_HEIGHT);
        enemy = new Enemy(GameEngine.WIDTH - PADDLE_WIDTH, (GameEngine.HEIGHT / 2) - PADDLE_HEIGHT / 2, PADDLE_WIDTH, PADDLE_HEIGHT);
    }

    @Override
    public void newBall() {
        ball = new Ball((GameEngine.WIDTH / 2) - (BALL_DIAMETER / 2), (GameEngine.HEIGHT / 2 - BALL_DIAMETER / 2), BALL_DIAMETER, BALL_DIAMETER);
        ballTouchPaddle = 0;
        clearBallVerticalPositionForDificultStrategyWithFail();
    }

    @Override
    public boolean setRoundDificulty(int enemyMistake, int setedDificulty) {
        if (enemyMistake < setedDificulty) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void enemyStrategy() {

        if (setRoundDificulty(randomEnemyMistake, DificultyMenu.dificultyPercent)) {
            if (randomDificultStrategy == EnemyStrategy.HARD_STRATEGY_WITHOUT_FAIL.getStrategyCase()) {
                enemyDificultStrategyWithoutFail();
            } else if (randomDificultStrategy == EnemyStrategy.HARD_STRATEGY_WITH_FAIL.getStrategyCase()) {
                enemyDificultStrategyWithFail();
            } else if (randomDificultStrategy == EnemyStrategy.MEDIUM_STRATEGY.getStrategyCase()) {
                enemyMediumStrategy();
            }
        } else {
            enemyEasyStrategy();
        }
    }

    @Override
    public void init() {
        newPaddles();
        newBall();
        try {
            backgroundImage = ImageIO.read(backgroundFile);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void checkBallPaddleCollision() {
        checkPlayerCollision();
        checkEnemyCollision();
    }

    @Override
    public void checkBallCollisionWithFrame() {
        if (ball.getVerticalPos() <= 0) {
            ball.setYDirection(-ball.ballVerticalVelocity);
        }

        if (ball.getVerticalPos() >= GameEngine.HEIGHT - BALL_DIAMETER) {
            ball.setYDirection(-ball.ballVerticalVelocity);
        }
    }

    @Override
    public void checkPaddleCollisionWithFrame() {
        if (player.getVerticalPos() <= 0) {
            player.setVerticalPos(0);
        }

        if (player.getVerticalPos() >= GameEngine.HEIGHT - PADDLE_HEIGHT) {
            player.setVerticalPos(GameEngine.HEIGHT - PADDLE_HEIGHT);
        }
    }

    @Override
    public void givePlayerPoint() {
        if (ball.getHorizontalPos() > GameEngine.WIDTH) {
            newBall();
            newPaddles();
            scores.scorePlayer1++;
            if (scores.scorePlayer1 == MAX_POINTS) {
                checkSetWinner();
                scores.scorePlayer1 = 0;
                scores.scorePlayer2 = 0;
            }
        }
    }

    @Override
    public void giveEnemyPoint() {
        if (ball.getHorizontalPos() + BALL_DIAMETER < 0) {
            newBall();
            newPaddles();
            scores.scorePlayer2++;
            if (scores.scorePlayer2 == MAX_POINTS) {
                checkSetWinner();
                scores.scorePlayer1 = 0;
                scores.scorePlayer2 = 0;
            }
        }
    }

    @Override
    public void addPlayer1Score() {
        Scores.player1Scores.add(scores.scorePlayer1);
    }

    @Override
    public void addPlayer2Score() {
        Scores.player2Scores.add(scores.scorePlayer2);
    }

    @Override
    public void checkSetWinner() {
        if (scores.scorePlayer1 == MAX_POINTS) {
            addPlayer1Score();
            addPlayer2Score();
            Scores.setWinPlayer1++;
        }

        if (scores.scorePlayer2 == MAX_POINTS) {
            addPlayer1Score();
            addPlayer2Score();
            Scores.setWinPlayer2++;
        }
    }

    @Override
    public void checkwhoWinSkirmish() {
        if (Scores.setWinPlayer1 == Sets.TWO_WINS.getSetWins() && Scores.setWinPlayer2 == Sets.ZERO_WINS.getSetWins()) {
            GUIStateManager.setStates(GUIStateManager.STATISTICS);
        } else if (Scores.setWinPlayer2 == Sets.TWO_WINS.getSetWins() && Scores.setWinPlayer1 == Sets.ZERO_WINS.getSetWins()) {
            GUIStateManager.setStates(GUIStateManager.STATISTICS);
        } else if (Scores.setWinPlayer1 == Sets.TWO_WINS.getSetWins() && Scores.setWinPlayer2 == Sets.ONE_WIN.getSetWins()) {
            GUIStateManager.setStates(GUIStateManager.STATISTICS);
        } else if (Scores.setWinPlayer2 == Sets.TWO_WINS.getSetWins() && Scores.setWinPlayer1 == Sets.ONE_WIN.getSetWins()) {
            GUIStateManager.setStates(GUIStateManager.STATISTICS);
        }
    }

    @Override
    public void update() {
        player.move();
        ball.move();
        enemyStrategy();
        checkBallCollisionWithFrame();
        checkPaddleCollisionWithFrame();
        checkBallPaddleCollision();
        givePlayerPoint();
        giveEnemyPoint();
        checkSetWinner();
        checkwhoWinSkirmish();
    }

    @Override
    public void draw(Graphics g) {
        g.drawImage(backgroundImage, 0, 0, null);
        field.draw(g);
        player.draw(g);
        enemy.draw(g);
        ball.draw(g);
        scores.draw(g);
    }

    @Override
    public void onKeyPressed(KeyEvent key) {
        player.movePaddle(key);
    }

    public int whenEnemyIntersectsUpperEdgeOfFrame() {
        return PADDLE_HEIGHT / 2 - BALL_DIAMETER / 2 - 1;
    }

    public int whenEnemyIntersectsLowerEdgeOfFrame() {
        return GameEngine.HEIGHT - PADDLE_HEIGHT / 2 - BALL_DIAMETER / 2  + 2;
    }

    @Override
    public void onKeyReleased(KeyEvent key) {
        player.stopPaddle(key);
    }

    private void checkEnemyCollision() {
        if (ball.intersects(enemy.getRectangle())) {
            ball.ballHorizontalVelocity = Math.abs(ball.getXVelocity());
            if (DificultyMenu.dificultyPercent >= speedUpBallWhenDificultyIsHeigherThen55) {
                ball.ballHorizontalVelocity++;
                if (ball.getYVelocity() > 0) {
                    ball.ballVerticalVelocity++;
                } else {
                    ball.ballVerticalVelocity--;
                }
            }
            ball.setXDirection(-ball.getXVelocity());
            ball.setYDirection(ball.getYVelocity());
        }
    }

    private void checkPlayerCollision() {
        if (ball.intersects(player.getRectangle())) {
            ball.ballHorizontalVelocity = Math.abs(ball.getXVelocity());
            if (DificultyMenu.dificultyPercent >= speedUpBallWhenDificultyIsHeigherThen55) {
                ball.ballHorizontalVelocity++;
                if (ball.getYVelocity() > 0) {
                    ball.ballVerticalVelocity++;
                } else {
                    ball.ballVerticalVelocity--;
                }
            }
            ball.setXDirection(ball.getXVelocity());
            ball.setYDirection(ball.getYVelocity());
        }
    }

    private void enemyEasyStrategy() {
        //Algorytm, który robi błąd (łatwy poziom)
        enemy.setVerticalPos(enemy.moveStrategyEasy());
        if (enemy.getVerticalPos() <= 0) {
            enemy.setYDirection(-enemy.getVelocity());
        }
        if (enemy.getVerticalPos() >= GameEngine.HEIGHT - PADDLE_HEIGHT) {
            enemy.setYDirection(-enemy.getVelocity());
        }
    }

    private void enemyMediumStrategy() {
        //Algorytm o średnim poziomie trudności
        enemy.setVerticalPos(enemy.moveStrategyMedium());
        if (enemy.getVerticalPos() <= 0) {
            enemy.setYDirection(-enemy.getVelocity());
        }
        if (enemy.getVerticalPos() >= GameEngine.HEIGHT - PADDLE_HEIGHT) {
            enemy.setYDirection(-enemy.getVelocity());
        }
    }

    private void enemyDificultStrategyWithFail() {
        if (DificultyMenu.dificultyPercent >= speedUpBallWhenDificultyIsHeigherThen55) {
            if (ball.getVerticalPos() <= whenEnemyIntersectsUpperEdgeOfFrame() || ball.getVerticalPos() >= whenEnemyIntersectsLowerEdgeOfFrame()) {
                enemy.setYDirection(0);
            } else {
                enemy.setVerticalPos(enemyVerticalPositionForDificultStrategyWithFail());

                if (ball.intersects(player.getRectangle())) {
                    ballTouchPaddle++;
                }

                if (ballTouchPaddle >= randomEnemyMistakeSecondStrategy && ball.intersects(field.getRectangle())) {
                    ballVerticalYPosition.add(ball.getVerticalPos());
                }
            }


            if (ball.getHorizontalPos() >= stopEnemyLine() && !ballVerticalYPosition.isEmpty()) {
                enemy.setVerticalPos(enemyStopPosition(0));
            }

            if (ball.getHorizontalPos() < stopEnemyLine()) {
            clearBallVerticalPositionForDificultStrategyWithFail();

            }

            if (ball.getHorizontalPos() >= stopEnemyLine()) {
                field.setHorizontalPos(temporaryFieldPosition());
            } else {
                field.setHorizontalPos(basiclyFieldPostion());
            }

        } else {
            enemyMediumStrategy();
        }
    }

    private void enemyDificultStrategyWithoutFail() {
        //Algorytm, który nie robi błędu
        if (ball.getVerticalPos() <= whenEnemyIntersectsUpperEdgeOfFrame() || ball.getVerticalPos() >= whenEnemyIntersectsLowerEdgeOfFrame()) {
            enemy.setYDirection(0);
        } else {
            enemy.setVerticalPos(enemyVerticalPositionForDificultStrategyWithFail());
        }
    }

    private int enemyVerticalPositionForDificultStrategyWithFail() {
        return ball.getVerticalPos() - (PADDLE_HEIGHT / 2) + (BALL_DIAMETER / 2);
    }

    private void clearBallVerticalPositionForDificultStrategyWithFail() {
        ballVerticalYPosition.clear();
    }

    private int temporaryFieldPosition() {
        return GameEngine.WIDTH / 2 + 10;
    }

    private int basiclyFieldPostion() {
        return (GameEngine.WIDTH / 4) * 3 - 20;
    }

    private int stopEnemyLine() {
        return (GameEngine.WIDTH / 4 * 3) - 40;
    }

    private int enemyStopPosition(int index) {
        return ballVerticalYPosition.get(index) - PADDLE_HEIGHT / 2 + BALL_DIAMETER / 2;
    }
}
0

https://kodilla.com/pl to jakaś kolejna no-name'owa platforma do testowania programistów bootcamp. Czyżbyś próbował robić jakieś zadanie rekrutacyjne/zaliczeniowe?

0

@0xmarcin: Staram się dokończyć pierwszy projekt na bootcamp i tylko to zostało mi do zrobienia.

2

Raczej wiele Ci nie uradzimy. ball jest nullem, a chyba nie powinien. Wygląda na to, że jedyne miejsce, gdzie to pole się wypełnia to newBall. To się wywołuje?

0

@szatkus: Problem rozwiązany. :)

    public Skirmish(GUIStateManager GUIStateManager) {
        this.GUIStateManager = GUIStateManager;
        this.scores = new Scores();
        this.player = new Paddle(0, (GameEngine.HEIGHT / 2) - (PADDLE_HEIGHT / 2), PADDLE_WIDTH, PADDLE_HEIGHT);
        this.ball = new Ball((GameEngine.WIDTH / 2) - (BALL_DIAMETER / 2), (GameEngine.HEIGHT / 2 - BALL_DIAMETER / 2), BALL_DIAMETER, BALL_DIAMETER);
        this.enemy = new Enemy(GameEngine.WIDTH - PADDLE_WIDTH, (GameEngine.HEIGHT / 2) - PADDLE_HEIGHT / 2, PADDLE_WIDTH, PADDLE_HEIGHT);
    }
0

Poza tym, co złapałeś, jest bardzo dziwne traktowanie pól klas zamiast zmiennych, co się łączy z nadmiarem void. Coś poprawiłeś, wyskoczą następne.

Niby się chwali opisowe nazwy zmiennych, ale tu są przesadne. A to mojej ocenie to wynika ze słabej strukturyzacji (np brak wydzielenia konfiguracji, ale nie tylko).

Mam wrażenie, nie panujesz nad dzieleniem całkowitoliczbowym (drobiazg przy reszcie problemów)

Jak nie byłbym absolutnym przeciwnikiem np programowania projektu szkolnego w Swingu, choć nie ma na to etatów, ale za zaletę bym widział (przy dobrym użyciu Swinga) nauczenie sie fajnych wzroców - TU TO NIE ZACHODZI - ten projekt nie uczy za bardzo niczego. Jebutne klasy stąd do podłogi, dalekie od porządnego OOP.

0

@AnyKtokolwiek: OK, czyli co dokładnie poprawić (na pewno nazwy metod)? I mam jeszcze jedno pytanie, jak zrobić, żeby przycisk plusa działał (linia 25)?

@Override
    public void onKeyPressed(KeyEvent key) {
        if (key.getKeyCode() == KeyEvent.VK_ENTER) {
            selectMenuOption();
        }
        if (key.getKeyCode() == KeyEvent.VK_UP || key.getKeyCode() == KeyEvent.VK_W) {
            currentChoiceMenu--;
            if (currentChoiceMenu == -1) {
                currentChoiceMenu = menuOptions.length - 1;
            }
        }
        if (key.getKeyCode() == KeyEvent.VK_DOWN || key.getKeyCode() == KeyEvent.VK_S) {
            currentChoiceMenu++;
            if (currentChoiceMenu == menuOptions.length) {
                currentChoiceMenu = 0;
            }
        }
        
        if (key.getKeyCode() == KeyEvent.VK_LEFT|| key.getKeyCode() == KeyEvent.VK_MINUS) {
            difficultyPercent--;
            if (difficultyPercent <= MIN_PERCENT) {
                difficultyPercent = GUI_MIN_PERCENT;
            }
        }
        if (key.getKeyCode() == KeyEvent.VK_RIGHT || key.getKeyCode() == KeyEvent.VK_PLUS) {
            difficultyPercent++;
            if (difficultyPercent == MAX_PERCENT) {
                difficultyPercent = GUI_MAX_PERCENT;
            }
        }
    }
0

@Ukulelemelelele:

Nazwy mogą być problemem samoistnym, ale częściej wskazują na problem koncepcyjny.
Pokrętny projekt podziału na metody właśnie z tym się łączy: trudno dać dobrą nazwę.
I na odwrót: jak projekt jest jasny i klarowny, w szczególności metoda robi jedną i wyrazistą rzecz, nazwa pojawia się naturalnie.

Strategia: twoja strategia gry by z chęcią była zaimplementowana ... strasznie trudno zgadnąć ... wzorcem strategia.
https://www.google.com/search?client=firefox-b-d&q=wzorzec+strategia

@RequiredNickname
Wybaczył bym przestarzałą technologię w projekcie edukacyjnym, bo jest przestarzała (choć moje serduszko by było mile ujęte Swingiem zamiast AWT) - gdyby delikwent oprócz tego fajnie to projektował w OOP. Dobrze projektować da się w każdym języku, nawet w C ;)
Więc @Ukulelemelelele nie przepisuj tego na inną technologię, ale zadbaj o dobre OOP.

1 użytkowników online, w tym zalogowanych: 0, gości: 1