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

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

קלט מקלדת ועכברKeyboard & mouse input

KeyListener, מצב מקשים לתנועה חלקה, עכבר, ומהירות שלא תלויה במחשב (delta time).

KeyListener, key state for smooth movement, the mouse, and speed that doesn't depend on the computer (delta time).

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

שמאלה ולמטהLeft and down

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

עם Input ו-Ship מהתזכורת: שלושה טיקים של חצי שנייה שמאלה, ואז טיק אחד למטה, במהירות 120 מ-(100, 100). הדפיסו -80.0, 160.0.

With Input and Ship from the refresher: three half-second ticks to the left, then one tick down, at speed 120 from (100, 100). Print -80.0, 160.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 {
    public static void main(String[] args) {
        Input in = new Input();
        Ship s = new Ship(100, 100, 120);
        in.left = true;
        for (int i = 0; i < 3; i++) {
            s.update(in, 0.5);
        }
        in.left = false;
        in.down = true;
        s.update(in, 0.5);
        System.out.println(s.x + ", " + s.y);
    }
}

class Input {
    boolean left, right, up, down, fire;
}

class Ship {
    double x, y;
    final double speed;

    Ship(double x, double y, double speed) {
        this.x = x;
        this.y = y;
        this.speed = speed;
    }

    void update(Input in, double dt) {
        if (in.left) {
            x -= speed * dt;
        }
        if (in.right) {
            x += speed * dt;
        }
        if (in.up) {
            y -= speed * dt;
        }
        if (in.down) {
            y += speed * dt;
        }
    }
}
פלטOutput
-80.0, 160.0

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

תרגילExercise 2

אותו מרחקThe same distance

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

travel(fps, speed, seconds) מזיזה עם speed * dt בכל פריים. שתי שניות במהירות 200: ב-60 fps וב-20 fps. הדפיסו 60 fps: 400.0, 20 fps: 400.0.

travel(fps, speed, seconds) moves by speed * dt each frame. Two seconds at speed 200: at 60 fps and at 20 fps. Print 60 fps: 400.0, 20 fps: 400.0.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static double travel(int fps, double speed, double seconds) {
        double x = 0;
        double dt = 1.0 / fps;
        int frames = (int) Math.round(seconds * fps);
        for (int i = 0; i < frames; i++) {
            x += speed * dt;
        }
        return Math.round(x * 100) / 100.0;
    }

    public static void main(String[] args) {
        System.out.println("60 fps: " + travel(60, 200, 2) + ", 20 fps: " + travel(20, 200, 2));
    }
}
פלטOutput
60 fps: 400.0, 20 fps: 400.0

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

תרגילExercise 3

לא לצאת מהמסךDon't leave the screen

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

clamp(v, min, max) משאירה ערך בתוך טווח. חללית ב-380 זזה ימינה במהירות 200, טיקים של 0.1. אחרי כל טיק מגבילים ל-0..400. הדפיסו 400 400 400 400 400.

clamp(v, min, max) keeps a value within a range. A ship at 380 moves right at speed 200, ticks of 0.1. After each tick clamp to 0..400. Print 400 400 400 400 400.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 double clamp(double v, double min, double max) {
        return Math.max(min, Math.min(max, v));
    }

    public static void main(String[] args) {
        Input in = new Input();
        Ship s = new Ship(380, 100, 200);
        in.right = true;
        for (int i = 0; i < 5; i++) {
            s.update(in, 0.1);
            s.x = clamp(s.x, 0, 400);
            System.out.print(Math.round(s.x) + " ");
        }
        System.out.println();
    }
}

class Input {
    boolean left, right, up, down, fire;
}

class Ship {
    double x, y;
    final double speed;

    Ship(double x, double y, double speed) {
        this.x = x;
        this.y = y;
        this.speed = speed;
    }

    void update(Input in, double dt) {
        if (in.left) {
            x -= speed * dt;
        }
        if (in.right) {
            x += speed * dt;
        }
        if (in.up) {
            y -= speed * dt;
        }
        if (in.down) {
            y += speed * dt;
        }
    }
}
פלטOutput
400 400 400 400 400 

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

תרגילExercise 4

צייד באגים: תנועה רק בלחיצהBug hunter: moving only on press

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

התוכנית מזיזה רק ברגע הלחיצה, ולכן שלושה טיקים עם מקש לחוץ נותנים רק 10. תקנו עם מצב מקש (right): לחיצה ועזיבה רק משנות את המצב, וכל tick זז אם המקש לחוץ. הפלט: x = 30.0.

The program moves only at the moment of the press, so three ticks with the key down give only 10. Fix it with key state (right): press and release only change the state, and each tick moves if the key is down. The output: x = 30.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
import java.util.List;

public class Main {
    public static void main(String[] args) {
        double x = 0;
        boolean right = false;
        List<String> events = List.of("press RIGHT", "tick", "tick", "tick", "release RIGHT", "tick");
        for (String e : events) {
            if (e.equals("press RIGHT")) {
                right = true;
            } else if (e.equals("release RIGHT")) {
                right = false;
            } else if (right) {
                x += 10;
            }
        }
        System.out.println("x = " + x);
    }
}
פלטOutput
x = 30.0

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

תרגילExercise 5

משחק 2: חללית שיורהGame 2: a ship that shoots

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

Gun עם cooldown של 0.3 שניות: כל עוד fire לחוץ, יורה כדור מהמיקום של החללית כשה-cooldown נגמר, וכל כדור עולה 400 לשנייה. החללית זזה ימינה ב-150. אחרי 10 פריימים של 0.1: ship x=350, bullets=4 ו-first bullet y=-80.

Gun with a 0.3-second cooldown: while fire is down, it shoots a bullet from the ship's position when the cooldown is over, and each bullet rises 400 per second. The ship moves right at 150. After 10 frames of 0.1: ship x=350, bullets=4 and first bullet y=-80.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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) {
        Input in = new Input();
        Ship ship = new Ship(200, 280, 150);
        Gun gun = new Gun(0.3);
        in.fire = true;
        in.right = true;
        double t = 0;
        for (int frame = 0; frame < 10; frame++) {
            double dt = 0.1;
            t += dt;
            ship.update(in, dt);
            gun.update(in, ship, dt);
        }
        System.out.println("ship x=" + Math.round(ship.x) + ", bullets=" + gun.bullets.size());
        System.out.println("first bullet y=" + Math.round(gun.bullets.get(0)[1]));
    }
}

class Gun {
    final List<double[]> bullets = new ArrayList<>();
    final double cooldown;
    double wait = 0;

    Gun(double cooldown) {
        this.cooldown = cooldown;
    }

    void update(Input in, Ship s, double dt) {
        for (double[] b : bullets) {
            b[1] -= 400 * dt;
        }
        wait -= dt;
        if (in.fire && wait <= 0) {
            bullets.add(new double[]{s.x, s.y});
            wait = cooldown;
        }
    }
}

class Input {
    boolean left, right, up, down, fire;
}

class Ship {
    double x, y;
    final double speed;

    Ship(double x, double y, double speed) {
        this.x = x;
        this.y = y;
        this.speed = speed;
    }

    void update(Input in, double dt) {
        if (in.left) {
            x -= speed * dt;
        }
        if (in.right) {
            x += speed * dt;
        }
        if (in.up) {
            y -= speed * dt;
        }
        if (in.down) {
            y += speed * dt;
        }
    }
}
פלטOutput
ship x=350, bullets=4
first bullet y=-80

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

אתגרChallenge 1

לנוע לעבר הקליקMoving toward the click

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

הקלקה ב-(30, 40). בכל טיק זזים 10 לכיוונה (וקטור מנורמל), ועוצרים כשמגיעים. הדפיסו 6 מיקומים (6,8, 12,16... עד 30,40) ואת הזווית angle 53 (atan2).

A click at (30, 40). Each tick move 10 toward it (a normalised vector), stopping on arrival. Print 6 positions (6,8, 12,16... up to 30,40) and the angle angle 53 (atan2).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 {
    public static void main(String[] args) {
        double x = 0, y = 0;
        double tx = 30, ty = 40;
        double speed = 10;
        for (int i = 0; i < 6; i++) {
            double dx = tx - x, dy = ty - y;
            double dist = Math.hypot(dx, dy);
            if (dist <= speed) {
                x = tx;
                y = ty;
            } else {
                x += dx / dist * speed;
                y += dy / dist * speed;
            }
            System.out.println(Math.round(x) + "," + Math.round(y));
        }
        System.out.println("angle " + Math.round(Math.toDegrees(Math.atan2(ty, tx))));
    }
}
פלטOutput
6,8
12,16
18,24
24,32
30,40
30,40
angle 53

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

אתגרChallenge 2

אלכסון לא מהיר יותרA diagonal isn't faster

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

בלי נרמול, ימינה ולמטה יחד זז 141 במקום 100. move(right, down, speed) מנרמלת את הכיוון. הדפיסו 100 100.

Without normalising, right and down together move 141 instead of 100. move(right, down, speed) normalises the direction. Print 100 100.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 double[] move(boolean right, boolean down, double speed) {
        double dx = (right ? 1 : 0), dy = (down ? 1 : 0);
        double len = Math.hypot(dx, dy);
        if (len > 0) {
            dx = dx / len * speed;
            dy = dy / len * speed;
        }
        return new double[]{dx, dy};
    }

    public static void main(String[] args) {
        double[] straight = move(true, false, 100);
        double[] diagonal = move(true, true, 100);
        System.out.println(Math.round(Math.hypot(straight[0], straight[1])) + " " + Math.round(Math.hypot(diagonal[0], diagonal[1])));
    }
}
פלטOutput
100 100

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

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