נבנה על ידי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.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • מכונת מצבים: המשחק תמיד נמצא במצב אחד מתוך רשימה סגורה (enum State). כל אירוע מועבר לפי המצב, וחלק מהאירועים מעבירים למצב אחר.state machine: The game is always in one state from a closed list (enum State). Each event is handled by the state, and some events move to another state.
  • מעבר: שינוי ממצב למצב בעקבות אירוע: MENU + ENTER → PLAYING. כדאי לצייר אותם כחצים לפני שכותבים קוד.transition: A change from state to state after an event: MENU + ENTER → PLAYING. Worth drawing as arrows before writing code.
  • שיא: הניקוד הגבוה ביותר, שנשמר בקובץ כדי שיישאר אחרי שסוגרים את המשחק. שומרים רק אם התוצאה החדשה גבוהה יותר.high score: The highest score, saved in a file so it stays after the game closes. Save only if the new result is higher.

02מכונת מצביםA state machine

Game.on(key) מחליט לפי state: בתפריט ENTER מתחיל, במשחק HIT מוריד חיים, וב-Game Over ENTER חוזר לתפריט. מקש שלא מתאים למצב פשוט לא עושה כלום (ESC כאן).

Game.on(key) decides by state: in the menu ENTER starts, in play HIT takes a life, and in game over ENTER returns to the menu. A key that doesn't fit the state just does nothing (ESC here).

Main.java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Game g = new Game();
        for (String key : List.of("ENTER", "HIT", "HIT", "HIT", "ENTER", "ESC")) {
            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
ENTER -> PLAYING lives=3
HIT -> PLAYING lives=2
HIT -> PLAYING lives=1
HIT -> GAME_OVER lives=0
ENTER -> MENU lives=0
ESC -> MENU lives=0
צפו בהרצה צעד אחר צעד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

03מסך לפי מצבA screen per state

switch שמחזיר ערך על enum חייב לכסות כל מצב. אם תוסיפו PAUSED ל-enum, javac יראה לכם כל מקום שצריך לעדכן.

A value-returning switch on an enum must cover every state. If you add PAUSED to the enum, javac shows you every place to update.

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
צפו בהרצה צעד אחר צעד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

04טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.

These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.

טעות נפוצהCommon mistake

צייד באגים: מצב שנשכח

Bug hunter: a forgotten state

Main.java
public class Main {
    static String music(State s) {
        return switch (s) {
            case MENU -> "calm.wav";
            case PLAYING -> "action.wav";
        };
    }

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

enum State {
    MENU, PLAYING, GAME_OVER
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:3: error: the switch expression does not cover all possible input values
        return switch (s) {
               ^
1 error
בעברית פשוטה: In plain words: the switch expression does not cover all possible input values: לכל מצב צריך תשובה.the switch expression does not cover all possible input values: every state needs an answer.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

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

מסך הפלטOutput screen

05הצעד של היום בפרויקט מדףToday's step in the Shelf project

הוסיפו ניקוד: 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.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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