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

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

Thread ללוגיקה ול-render, עם סנכרוןA thread for logic and rendering, with sync

מפרידים את הלוגיקה מהציור ל-threads נפרדים, משתפים מצב בבטחה, ומשווים ל-Swing Timer.

Separating logic from drawing into their own threads, sharing state safely, and comparing with a Swing Timer.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • תמונת מצב: עותק בלתי משתנה של העולם (record עם List.copyOf).snapshot: An immutable copy of the world (a record with List.copyOf).
  • צעד זמן קבוע: צוברים את זמן הפריימים, ומריצים עדכון של, נניח, 20ms בכל פעם שהצטבר מספיק.fixed timestep: Accumulate frame time, and run an update of, say, 20ms each time enough has built up.
  • ה-thread של הלוגיקה בונה רשימת אויבים חדשה בכל טיק, ומפרסם תמונת מצב בלתי משתנה במשתנה volatile.The logic thread builds a new enemy list each tick, and publishes an immutable snapshot in a volatile variable.
  • ה-render קורא את ההפניה פעם אחת ומצייר ממנה, ולכן אף פעם לא רואה עולם חצי מעודכן.The renderer reads the reference once and draws from it, so it never sees a half-updated world.
  • scheduleAtFixedRate מריץ טיק כל 10ms על thread אחד.scheduleAtFixedRate runs a tick every 10ms on one thread.
  • ב-Swing, javax.swing.Timer עושה אותו דבר על ה-EDT, ואז אין שני threads ואין מה לסנכרן.In Swing, javax.swing.Timer does the same on the EDT, so there aren't two threads and nothing to synchronize.
  • java.util.ConcurrentModificationException:java.util.ConcurrentModificationException:
  • משחק 5: עולם עם הרבה אויביםGame 5: a world with many enemies

מונחיםTerms

  • תמונת מצבsnapshot: עותק בלתי משתנה של העולם (record עם List.copyOf). ה-thread של הלוגיקה בונה חדש בכל טיק ומפרסם דרך volatile; ה-render תמיד רואה עולם שלם, אף פעם לא חצי.An immutable copy of the world (a record with List.copyOf). The logic thread builds a new one each tick and publishes it through volatile; the renderer always sees a whole world, never half of one.
  • צעד זמן קבועfixed timestep: צוברים את זמן הפריימים, ומריצים עדכון של, נניח, 20ms בכל פעם שהצטבר מספיק. הפיזיקה יציבה וזהה בכל מחשב.Accumulate frame time, and run an update of, say, 20ms each time enough has built up. Physics stays stable and identical on every computer.
  • double bufferingdouble buffering: שני חוצצים: מציירים על האחורי, ואז מחליפים. המסך לא מראה אף פעם פריים חצי מצויר.Two buffers: draw on the back one, then swap. The screen never shows a half-drawn frame.
  • Event Dispatch ThreadEvent Dispatch Thread: ה-thread היחיד שמותר לו לגעת ברכיבי Swing. javax.swing.Timer רץ עליו, ולכן משחק פשוט עם Timer לא צריך סנכרון בכלל.The only thread allowed to touch Swing components. javax.swing.Timer runs on it, so a simple game with a Timer needs no synchronization at all.
  • תמונת מצבsnapshot: עותק בלתי משתנה של העולם (record עם List.copyOf). ה-thread של הלוגיקה בונה חדש בכל טיק ומפרסם דרך volatile; ה-render תמיד רואה עולם שלם, אף פעם לא חצי.An immutable copy of the world (a record with List.copyOf). The logic thread builds a new one each tick and publishes it through volatile; the renderer always sees a whole world, never half of one.
  • צעד זמן קבועfixed timestep: צוברים את זמן הפריימים, ומריצים עדכון של, נניח, 20ms בכל פעם שהצטבר מספיק. הפיזיקה יציבה וזהה בכל מחשב.Accumulate frame time, and run an update of, say, 20ms each time enough has built up. Physics stays stable and identical on every computer.
  • double bufferingdouble buffering: שני חוצצים: מציירים על האחורי, ואז מחליפים. המסך לא מראה אף פעם פריים חצי מצויר.Two buffers: draw on the back one, then swap. The screen never shows a half-drawn frame.
  • Event Dispatch ThreadEvent Dispatch Thread: ה-thread היחיד שמותר לו לגעת ברכיבי Swing. javax.swing.Timer רץ עליו, ולכן משחק פשוט עם Timer לא צריך סנכרון בכלל.The only thread allowed to touch Swing components. javax.swing.Timer runs on it, so a simple game with a Timer needs no synchronization at all.

Cheatsheet

לוגיקה ו-render, עם תמונת מצבLogic and render, with a snapshot
Thread logic = new Thread(() -> {
    List<Enemy> world = new ArrayList<>(List.of(new Enemy(0, 0), new Enemy(10, 5)));
    for (int tick = 1; tick <= 100; tick++) {
        List<Enemy> next = new ArrayList<>();
        for (Enemy e : world) {
            next.add(new Enemy(e.x() + 1, e.y()));
        }
        world = next;
        latest = new Snapshot(tick, List.copyOf(world));
    }
טיימר במקום threadA timer instead of a thread
ScheduledExecutorService loop = Executors.newSingleThreadScheduledExecutor();
List<Integer> ticks = new ArrayList<>();
loop.scheduleAtFixedRate(() -> ticks.add(ticks.size() + 1), 0, 10, TimeUnit.MILLISECONDS);
Thread.sleep(105);
loop.shutdown();
loop.awaitTermination(1, TimeUnit.SECONDS);
System.out.println("about 10 ticks: " + (ticks.size() >= 8 && ticks.size() <= 12));

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
ConcurrentModificationExceptionצייד באגים: אויב נולד באמצע לולאהBug hunter: an enemy born mid-loopjava.util.ConcurrentModificationException: מוסיפים לרשימה בזמן שה-for-each עובר עליה. ב-thread אחר זה היה קורה גם בלי להוסיף בתוך הלולאה.java.util.ConcurrentModificationException: adding to the list while the for-each walks it. On another thread it would happen even without adding inside the loop.

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