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

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

מצבי משחק: תפריט, משחק ו-Game OverGame states: menu, play & game over

מכונת מצבים עם enum, מסכים, שמירת שיא, וקול.

A state machine with an enum, screens, a saved high score, and sound.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.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

מעבריםTransitions

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

עם Game מהתזכורת הריצו את האירועים HIT, ENTER, HIT, ENTER, HIT, HIT והדפיסו את המצב והחיים אחרי כל אחד. HIT בתפריט ו-ENTER באמצע משחק לא עושים כלום.

With Game from the refresher run the events HIT, ENTER, HIT, ENTER, HIT, HIT and print the state and lives after each. HIT in the menu and ENTER mid-game do nothing.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.util.List;

public class Main {
    public static void main(String[] args) {
        Game g = new Game();
        for (String key : List.of("HIT", "ENTER", "HIT", "ENTER", "HIT", "HIT")) {
            g.on(key);
            System.out.println(key + " -> " + g.state + " lives=" + g.lives);
        }
    }
}

enum State {
    MENU, PLAYING, GAME_OVER
}

class Game {
    State state = State.MENU;
    int lives = 3;

    void on(String key) {
        switch (state) {
            case MENU -> {
                if (key.equals("ENTER")) {
                    state = State.PLAYING;
                    lives = 3;
                }
            }
            case PLAYING -> {
                if (key.equals("HIT") && --lives == 0) {
                    state = State.GAME_OVER;
                }
            }
            case GAME_OVER -> {
                if (key.equals("ENTER")) {
                    state = State.MENU;
                }
            }
        }
    }
}
פלטOutput
HIT -> MENU lives=3
ENTER -> PLAYING lives=3
HIT -> PLAYING lives=2
ENTER -> PLAYING lives=2
HIT -> PLAYING lives=1
HIT -> GAME_OVER lives=0

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

תרגילExercise 2

מסכיםScreens

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

screen(state, score) עם switch בחצים מחזיר את הטקסט של כל מסך. הדפיסו לכל המצבים עם ניקוד 120.

screen(state, score) with an arrow switch returns each screen's text. Print for every state with a score of 120.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 screen(State s, int score) {
        return switch (s) {
            case MENU -> "PRESS ENTER TO START";
            case PLAYING -> "score " + score;
            case GAME_OVER -> "GAME OVER - final score " + score;
        };
    }

    public static void main(String[] args) {
        for (State s : State.values()) {
            System.out.println(screen(s, 120));
        }
    }
}

enum State {
    MENU, PLAYING, GAME_OVER
}
פלטOutput
PRESS ENTER TO START
score 120
GAME OVER - final score 120

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

תרגילExercise 3

שיא בקובץA high score in a file

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

loadBest() קוראת את best.txt (או 0), ו-saveBest(score) כותבת רק אם יותר גבוה. אחרי משחקים של 40, 120 ו-90 הדפיסו played 40, best 40, played 120, best 120, played 90, best 120.

loadBest() reads best.txt (or 0), and saveBest(score) writes only if it's higher. After games of 40, 120 and 90 print played 40, best 40, played 120, best 120, played 90, best 120.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.nio.file.Files;
import java.nio.file.Path;

public class Main {
    static final Path FILE = Path.of("best.txt");

    static int loadBest() throws IOException {
        return Files.exists(FILE) ? Integer.parseInt(Files.readString(FILE).trim()) : 0;
    }

    static void saveBest(int score) throws IOException {
        if (score > loadBest()) {
            Files.writeString(FILE, String.valueOf(score));
        }
    }

    public static void main(String[] args) throws IOException {
        Files.deleteIfExists(FILE);
        for (int score : new int[]{40, 120, 90}) {
            saveBest(score);
            System.out.println("played " + score + ", best " + loadBest());
        }
    }
}
פלטOutput
played 40, best 40
played 120, best 120
played 90, best 120

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

תרגילExercise 4

צייד באגים: מצב שנשכחBug hunter: a forgotten state

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

music(state) לא מכסה את GAME_OVER, ו-javac עוצר. הוסיפו sad.wav למצב החסר.

music(state) doesn't cover GAME_OVER, and javac stops. Add sad.wav for the missing state.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

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

מסך הפלטOutput screen

צפו בהרצה צעד אחר צעד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 music(State s) {
        return switch (s) {
            case MENU -> "calm.wav";
            case PLAYING -> "action.wav";
            case GAME_OVER -> "sad.wav";
        };
    }

    public static void main(String[] args) {
        System.out.println(music(State.GAME_OVER));
    }
}

enum State {
    MENU, PLAYING, GAME_OVER
}
פלטOutput
sad.wav

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

תרגילExercise 5

משחק 4: משחק עם תפריט ושיאGame 4: a game with a menu and a high score

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

הוסיפו ניקוד: STAR נותן 10, ושלוש פגיעות מסיימות את המשחק ומעדכנות את best. אחרי התסריט (שני משחקים: 30 נקודות ואז 10) הדפיסו GAME_OVER score=10 best=30.

Add scoring: STAR gives 10, and three hits end the game and update best. After the script (two games: 30 points then 10) print GAME_OVER score=10 best=30.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.util.List;

public class Main {
    public static void main(String[] args) {
        Game g = new Game();
        List<String> script = List.of("ENTER", "STAR", "STAR", "HIT", "STAR", "HIT", "HIT", "ENTER", "ENTER", "STAR", "HIT", "HIT", "HIT");
        for (String e : script) {
            g.on(e);
        }
        System.out.println(g.state + " score=" + g.score + " best=" + g.best);
    }
}

enum State {
    MENU, PLAYING, GAME_OVER
}

class Game {
    State state = State.MENU;
    int lives, score, best;

    void on(String e) {
        switch (state) {
            case MENU -> {
                if (e.equals("ENTER")) {
                    state = State.PLAYING;
                    lives = 3;
                    score = 0;
                }
            }
            case PLAYING -> {
                if (e.equals("STAR")) {
                    score += 10;
                } else if (e.equals("HIT") && --lives == 0) {
                    best = Math.max(best, score);
                    state = State.GAME_OVER;
                }
            }
            case GAME_OVER -> {
                if (e.equals("ENTER")) {
                    state = State.MENU;
                }
            }
        }
    }
}
פלטOutput
GAME_OVER score=10 best=30

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

אתגרChallenge 1

מחסנית מסכיםA stack of screens

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

משחק → השהיה → הגדרות: כל מסך חדש נדחף על המחסנית, ו-"חזרה" מוציא. הדפיסו top: SETTINGS ואחרי שתי חזרות back to: PLAYING, depth 1.

Game → pause → settings: each new screen is pushed onto the stack, and "back" pops. Print top: SETTINGS and after two backs back to: PLAYING, depth 1.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        Deque<String> screens = new ArrayDeque<>();
        screens.push("PLAYING");
        screens.push("PAUSED");
        screens.push("SETTINGS");
        System.out.println("top: " + screens.peek());
        screens.pop();
        screens.pop();
        System.out.println("back to: " + screens.peek() + ", depth " + screens.size());
    }
}
פלטOutput
top: SETTINGS
back to: PLAYING, depth 1

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

אתגרChallenge 2

צלילים לפי אירועיםSounds by events

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

SoundQueue.on(event) מוסיפה צליל לכל אירוע (ding, bump, game-over), ואחרי Game Over מתעלמת מהכול. הדפיסו [ding, ding, bump, game-over]. (במחשב שלכם: javax.sound.sampled.Clip מנגן את הקבצים.)

SoundQueue.on(event) adds a sound per event (ding, bump, game-over), and after game over ignores everything. Print [ding, ding, bump, game-over]. (On your computer: javax.sound.sampled.Clip plays the files.)

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        SoundQueue sounds = new SoundQueue();
        for (String e : new String[]{"STAR", "STAR", "HIT", "GAME_OVER", "STAR"}) {
            sounds.on(e);
        }
        System.out.println(sounds.played);
    }
}

class SoundQueue {
    final List<String> played = new ArrayList<>();
    private boolean over = false;

    void on(String event) {
        if (over) {
            return;
        }
        switch (event) {
            case "STAR" -> played.add("ding");
            case "HIT" -> played.add("bump");
            case "GAME_OVER" -> {
                played.add("game-over");
                over = true;
            }
            default -> {
            }
        }
    }
}
פלטOutput
[ding, ding, bump, game-over]

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

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