Question

I'm doing a snake game, and I want after the game is over, the score is saved in a file I did this, but there's error in the two lines that sends the value to the Testing Class

private boolean isGameOver(int headLocX, int headLocY) {

    for (int i = SNAKE_LENGTH_DEFAULT; i < totalBodyPart - 2; i++) {
        Point partLoc = snakeBodyPart[i].getLocation();
        if (partLoc.equals(new Point(headLocX, headLocY))) {
             Testing test = new Testing(score);
            return true;
        }
    }

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Testing 
{
    public Testing(int score) 
    {

        File file = new File("C:\\Users\\Eng. Mohammed\\Desktop\\Snake 1.0.1\\Snake\\Score.Txt");

        PrintWriter printWriter = null;

        try
        {
            printWriter = new PrintWriter(file);
            printWriter.println(score);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if ( printWriter != null ) 
            {
                printWriter.close();
            }
        }
    }
}
Was it helpful?

Solution

Change this method

private boolean isGameOver(int headLocX, int headLocY) {

    for (int i = SNAKE_LENGTH_DEFAULT; i < totalBodyPart - 2; i++) {
        Point partLoc = snakeBodyPart[i].getLocation();
        if (partLoc.equals(new Point(headLocX, headLocY))) {
            Testing test = new Testing();
            Testing(score);//It is an invalid call no method is defined like this or a class can't be initialized like this.
            return true;
        }
    }

TO

private boolean isGameOver(int headLocX, int headLocY) {

    for (int i = SNAKE_LENGTH_DEFAULT; i < totalBodyPart - 2; i++) {
        Point partLoc = snakeBodyPart[i].getLocation();
        if (partLoc.equals(new Point(headLocX, headLocY))) {
            Testing test = new Testing(score);//This is the correct way to initialize the Testing class.
            return true;
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top