נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
48
חלקPart 8: משחקים ב-JavaGames in Java כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

משחק שלם ואריזה ל-jar ו-jpackageA full game, packed with jar & jpackage

מחברים הכול למשחק שלם, אורזים ל-jar שרץ בלחיצה כפולה, ויוצרים מתקין עם jpackage.

Putting it all into a full game, packing a jar that runs on double-click, and making an installer with jpackage.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

manifestA manifest

תזכורת: מה ביקשוReminder: the task

manifest(mainClass, version) בונה את הטקסט של MANIFEST.MF: Manifest-Version: 1.0, Main-Class: Main, Implementation-Version: 1.0.0. הדפיסו אותו.

manifest(mainClass, version) builds the text of MANIFEST.MF: Manifest-Version: 1.0, Main-Class: Main, Implementation-Version: 1.0.0. Print it.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static String manifest(String mainClass, String version) {
        return "Manifest-Version: 1.0\n" + "Main-Class: " + mainClass + "\n" + "Implementation-Version: " + version + "\n";
    }

    public static void main(String[] args) {
        System.out.print(manifest("Main", "1.0.0"));
    }
}
פלטOutput
Manifest-Version: 1.0
Main-Class: Main
Implementation-Version: 1.0.0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

הגדרות מקובץSettings from a file

תזכורת: מה ביקשוReminder: the task

Properties קורא קובץ key=value (ומדלג על הערות #). טענו מתוך מחרוזת (בפרויקט: מקובץ ליד ה-jar), והדפיסו Star Catcher 400x300 sound=on fps=60 (fps חסר, ברירת מחדל 60).

Properties reads a key=value file (skipping # comments). Load from a string (in the project: from a file next to the jar), and print Star Catcher 400x300 sound=on fps=60 (fps is missing, default 60).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;

public class Main {
    public static void main(String[] args) throws IOException {
        String file = "title=Star Catcher\nwidth=400\nheight=300\n# comment\nsound=on\n";
        Properties p = new Properties();
        p.load(new StringReader(file));
        int w = Integer.parseInt(p.getProperty("width"));
        int h = Integer.parseInt(p.getProperty("height"));
        System.out.println(p.getProperty("title") + " " + w + "x" + h + " sound=" + p.getProperty("sound") + " fps=" + p.getProperty("fps", "60"));
    }
}
פלטOutput
Star Catcher 400x300 sound=on fps=60

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

משחק 6: המשחק השלםGame 6: the full game

תזכורת: מה ביקשוReminder: the task

כתבו את Game מהתזכורת: מצבים, קלט, משוט מוגבל למסך, כוכב חדש כל 0.6 שנייה (עם Random(seed)), נפילה, תפיסה (10 נקודות) ופספוס (חיים). הריצו עם seed 42 ושחקן אוטומטי עד Game Over, והדפיסו את התוצאה. בבית: חברו ל-JPanel מהמפגשים הקודמים.

Write Game from the refresher: states, input, a paddle kept on screen, a new star every 0.6 seconds (with Random(seed)), falling, catching (10 points) and missing (lives). Run with seed 42 and an automatic player until game over, and print the result. At home: connect it to the JPanel from earlier sessions.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Game g = new Game(42);
        g.start();
        for (int tick = 0; tick < 400 && g.state == State.PLAYING; tick++) {
            g.input.left = tick % 40 < 20;
            g.input.right = !g.input.left;
            g.update(0.05);
        }
        System.out.println(g.state + " score=" + g.score + " lives=" + g.lives);
    }
}

enum State {
    MENU, PLAYING, GAME_OVER
}

class Input {
    boolean left, right;
}

class Game {
    final Input input = new Input();
    final java.util.Random rnd;
    State state = State.MENU;
    double paddleX = 200;
    final List<double[]> stars = new ArrayList<>();
    int score, lives;
    double spawn = 0;

    Game(long seed) {
        rnd = new java.util.Random(seed);
    }

    void start() {
        state = State.PLAYING;
        score = 0;
        lives = 3;
        stars.clear();
    }

    void update(double dt) {
        if (state != State.PLAYING) {
            return;
        }
        if (input.left) {
            paddleX -= 200 * dt;
        }
        if (input.right) {
            paddleX += 200 * dt;
        }
        paddleX = Math.max(0, Math.min(360, paddleX));
        spawn -= dt;
        if (spawn <= 0) {
            stars.add(new double[]{rnd.nextInt(390), 0});
            spawn = 0.6;
        }
        for (int i = stars.size() - 1; i >= 0; i--) {
            double[] s = stars.get(i);
            s[1] += 120 * dt;
            boolean caught = s[1] >= 270 && s[1] <= 290 && s[0] + 10 > paddleX && s[0] < paddleX + 40;
            if (caught) {
                score += 10;
                stars.remove(i);
            } else if (s[1] > 300) {
                stars.remove(i);
                if (--lives == 0) {
                    state = State.GAME_OVER;
                }
            }
        }
    }
}
פלטOutput
GAME_OVER score=30 lives=0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

השוואת גרסאותComparing versions

תזכורת: מה ביקשוReminder: the task

compare(a, b) משווה גרסאות major.minor.patch כמספרים (לא כטקסט: 1.10 אחרי 1.2). הדפיסו -1 1 0.

compare(a, b) compares major.minor.patch versions as numbers (not as text: 1.10 after 1.2). Print -1 1 0.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static int compare(String a, String b) {
        String[] x = a.split("\\.");
        String[] y = b.split("\\.");
        for (int i = 0; i < 3; i++) {
            int c = Integer.compare(Integer.parseInt(x[i]), Integer.parseInt(y[i]));
            if (c != 0) {
                return c;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        System.out.println(compare("1.2.0", "1.10.0") + " " + compare("2.0.0", "1.9.9") + " " + compare("1.0.1", "1.0.1"));
    }
}
פלטOutput
-1 1 0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

לארוז ולהריץPack and run

תזכורת: מה ביקשוReminder: the task

במחשב שלכם, בתיקיית המשחק: הדרו ל-out, צרו stars.jar עם Main כמחלקה הראשית, הריצו עם java -jar, ואז צרו תוכנה עם jpackage.

On your computer, in the game folder: compile into out, create stars.jar with Main as the main class, run it with java -jar, then make an app with jpackage.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
Terminal
javac -d out src/*.java
jar --create --file stars.jar --main-class Main -C out .
java -jar stars.jar
jpackage --input . --main-jar stars.jar --name StarCatcher --type app-image

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

seed אחר, משחק אחרAnother seed, another game

תזכורת: מה ביקשוReminder: the task

הריצו את Game עם seed 7 ועם seed 42 (אותו שחקן אוטומטי), והדפיסו את שתי התוצאות. הן כנראה שונות, אבל כל אחת קבועה בכל הרצה. זה מה שמאפשר לבדוק משחק עם אקראיות.

Run Game with seed 7 and with seed 42 (the same automatic player), and print both results. They're probably different, but each is fixed on every run. That's what makes a game with randomness testable.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;

public class Main {
    static String play(long seed) {
        Game g = new Game(seed);
        g.start();
        for (int tick = 0; tick < 400 && g.state == State.PLAYING; tick++) {
            g.input.left = tick % 40 < 20;
            g.input.right = !g.input.left;
            g.update(0.05);
        }
        return g.state + " score=" + g.score;
    }

    public static void main(String[] args) {
        System.out.println("seed 7: " + play(7));
        System.out.println("seed 42: " + play(42));
    }
}

enum State {
    MENU, PLAYING, GAME_OVER
}

class Input {
    boolean left, right;
}

class Game {
    final Input input = new Input();
    final java.util.Random rnd;
    State state = State.MENU;
    double paddleX = 200;
    final List<double[]> stars = new ArrayList<>();
    int score, lives;
    double spawn = 0;

    Game(long seed) {
        rnd = new java.util.Random(seed);
    }

    void start() {
        state = State.PLAYING;
        score = 0;
        lives = 3;
        stars.clear();
    }

    void update(double dt) {
        if (state != State.PLAYING) {
            return;
        }
        if (input.left) {
            paddleX -= 200 * dt;
        }
        if (input.right) {
            paddleX += 200 * dt;
        }
        paddleX = Math.max(0, Math.min(360, paddleX));
        spawn -= dt;
        if (spawn <= 0) {
            stars.add(new double[]{rnd.nextInt(390), 0});
            spawn = 0.6;
        }
        for (int i = stars.size() - 1; i >= 0; i--) {
            double[] s = stars.get(i);
            s[1] += 120 * dt;
            boolean caught = s[1] >= 270 && s[1] <= 290 && s[0] + 10 > paddleX && s[0] < paddleX + 40;
            if (caught) {
                score += 10;
                stars.remove(i);
            } else if (s[1] > 300) {
                stars.remove(i);
                if (--lives == 0) {
                    state = State.GAME_OVER;
                }
            }
        }
    }
}
פלטOutput
seed 7: GAME_OVER score=0
seed 42: GAME_OVER score=30

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

ה-jar מבפניםInside the jar

תזכורת: מה ביקשוReminder: the task

הסתכלו בתוך ה-jar: רשימת הקבצים, ותוכן ה-manifest. אחר כך הוסיפו תמונה לתיקיית resources וודאו שהיא נכנסת.

Look inside the jar: the list of files, and the manifest's content. Then add a picture to a resources folder and make sure it goes in.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
Terminal
jar --list --file stars.jar
unzip -p stars.jar META-INF/MANIFEST.MF
cp star.png out/
jar --create --file stars.jar --main-class Main -C out .
jar --list --file stars.jar

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich