将highscores添加到java游戏-从控制台到JPanel -将highscores保存在加密文本文件中

lyfkaqu1  于 2022-11-20  发布在  Java
关注(0)|答案(2)|浏览(98)

我刚接触Java,每天都在学习新的东西。英语不是我的母语,很抱歉。所以,我正在用Java做一个迷宫游戏,一边写代码一边学习。在我的迷宫游戏中,玩家需要尽快到达迷宫的出口。而他所花的时间,需要保存在一个加密的文本文件中。所以我有一个包Highscores,它结合了几个类。代码或多或少都能工作。它在控制台中输出。现在我需要的是输出在我的迷宫旁边的JPanel上。我在代码中添加了一些额外的信息。下面是我的highscore类:

public class Highscore {
// An arraylist of the type "score" we will use to work with the scores inside the class
private ArrayList<Score> scores;

// The name of the file where the highscores will be saved
private static final String highscorefile = "Resources/scores.dat";

//Initialising an in and outputStream for working with the file
ObjectOutputStream output = null;
ObjectInputStream input = null;

public Highscore() {
    //initialising the scores-arraylist
    scores = new ArrayList<Score>();
}
public ArrayList<Score> getScores() {
    loadScoreFile();
    sort();
    return scores;
}
private void sort() {
    ScoreVergelijken comparator = new ScoreVergelijken();
    Collections.sort(scores, comparator);
}
public void addScore(String name, int score) {
    loadScoreFile();
    scores.add(new Score(name, score));
    updateScoreFile();
}
public void loadScoreFile() {
    try {
        input = new ObjectInputStream(new FileInputStream(highscorefile));
        scores = (ArrayList<Score>) input.readObject();
    } catch (FileNotFoundException e) {
        System.out.println("[Laad] FNF Error: " + e.getMessage());
    } catch (IOException e) {
        System.out.println("[Laad] IO Error: " + e.getMessage());
    } catch (ClassNotFoundException e) {
        System.out.println("[Laad] CNF Error: " + e.getMessage());
    } finally {
        try {
            if (output != null) {
                output.flush();
                output.close();
            }
        } catch (IOException e) {
            System.out.println("[Laad] IO Error: " + e.getMessage());
        }
    }
}
public void updateScoreFile() {
    try {
        output = new ObjectOutputStream(new FileOutputStream(highscorefile));
        output.writeObject(scores);
    } catch (FileNotFoundException e) {
        System.out.println("[Update] FNF Error: " + e.getMessage() + ",the program will try and make a new file");
    } catch (IOException e) {
        System.out.println("[Update] IO Error: " + e.getMessage());
    } finally {
        try {
            if (output != null) {
                output.flush();
                output.close();
            }
        } catch (IOException e) {
            System.out.println("[Update] Error: " + e.getMessage());
        }
    }
}
public String getHighscoreString() {
    String highscoreString = "";
       int max = 10;

    ArrayList<Score> scores;
    scores = getScores();

    int i = 0;
    int x = scores.size();
    if (x > max) {
        x = max;
    }
    while (i < x) {
        highscoreString += (i + 1) + ".\t" + scores.get(i).getNaam() + "\t\t" + scores.get(i).getScore() + "\n";
        i++;
    }
    return highscoreString;
}

}
下面是我的主类:

public class Main {
    public static void main(String[] args) {
    Highscore hm = new Highscore();
    hm.addScore("Bart",240);
    hm.addScore("Marge",300);
    hm.addScore("Maggie",220);
    hm.addScore("Homer",100);
    hm.addScore("Lisa",270);
    hm.addScore(LabyrinthProject.View.MainMenu.username,290);

    System.out.print(hm.getHighscoreString());
} }

分数等级:

public class Score  implements Serializable {
private int score;
private String naam;

public Score() {

}

public int getScore() {
    return score;
}

public String getNaam() {
    return naam;
}

public Score(String naam, int score) {
    this.score = score;
    this.naam = naam;
}

}
分数比较类(表示比较分数)

public class ScoreVergelijken implements Comparator<Score> {
public int compare(Score score1, Score score2) {

    int sc1 = score1.getScore();
    int sc2 = score2.getScore();

    if (sc1 > sc2){
        return -1;                   // -1 means first score is bigger then second score
    }else if (sc1 < sc2){
        return +1;                   // +1 means that score is lower
    }else{
        return 0;                     // 0 means score is equal
    }
}  }

如果有人能给我解释一下该用什么,我将不胜感激!非常感谢!
还有,如何使用那些高分并将它们加密存储在文本文件中。我如何才能做到这一点?
真诚的,一个初学java的学生。

jdgnovmf

jdgnovmf1#

要将数据加密保存在文件中,可以使用CipherIn/OutputStream,如下所示

public static void main(String[] args) throws Exception {
    // got this example from http://www.java2s.com/Tutorial/Java/0490__Security/UsingCipherInputStream.htm
    write();
    read();
}

public static void write() throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(new SecureRandom());
    SecretKey key = kg.generateKey();
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    Class spec = Class.forName("javax.crypto.spec.DESKeySpec");
    DESKeySpec ks = (DESKeySpec) skf.getKeySpec(key, spec);
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("keyfile"));
    oos.writeObject(ks.getKey());

    Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, key);
    CipherOutputStream cos = new CipherOutputStream(new FileOutputStream("ciphertext"), c);
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(cos));
    pw.println("Stand and unfold yourself");
    pw.flush();
    pw.close();
    oos.writeObject(c.getIV());
    oos.close();
}

public static void read() throws Exception {
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("keyfile"));
    DESKeySpec ks = new DESKeySpec((byte[]) ois.readObject());
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    SecretKey key = skf.generateSecret(ks);

    Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
    c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec((byte[]) ois.readObject()));
    CipherInputStream cis = new CipherInputStream(new FileInputStream("ciphertext"), c);
    BufferedReader br = new BufferedReader(new InputStreamReader(cis));
    System.out.println(br.readLine());
}
rta7y2nd

rta7y2nd2#

基本上你问了两个问题,利奥回答了你的第二个问题。
你的第一个问题是...
我需要的是......(高分)......在我的迷宫旁边的JPanel上输出
您没有发布任何GUI代码,但是JTextComponent的子类比JPanel更合适。只需添加一个组件,例如JTextArea,并使用您的 high score string 作为方法参数调用它的setText()方法。

相关问题