חלון ראשון: Swing, ציור ו-game loopFirst window: Swing, drawing & the game loop
JFrame ו-JPanel, ציור עם Graphics2D, וה-game loop: עדכון, ציור, המתנה.
JFrame and JPanel, drawing with Graphics2D, and the game loop: update, draw, wait.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- JFrame ו-JPanel:
JFrameהוא החלון;JPanelהוא משטח בתוכו. דורסים ב-JPanel אתpaintComponent(Graphics g)כדי לצייר.JFrame and JPanel:JFrameis the window;JPanelis a surface inside it. Override the JPanel'spaintComponent(Graphics g)to draw. - Graphics2D: "מכחול" של Java:
setColor,fillRect,fillOval,drawString. ראשית הצירים בפינה השמאלית העליונה, ו-y גדל כלפי מטה.Graphics2D: Java's "brush":setColor,fillRect,fillOval,drawString. The origin is the top-left corner, and y grows downward. - לולאת משחק: הלב של כל משחק: שוב ושוב, בערך 60 פעמים בשנייה, מעדכנים את העולם (
update) ומציירים אותו (repaint). ב-Swing הכי פשוט עםjavax.swing.Timer.game loop: The heart of every game: over and over, about 60 times a second, update the world (update) and draw it (repaint). In Swing the simplest is ajavax.swing.Timer. - לוגיקת משחק: המצב והכללים של המשחק (מיקום, מהירות, התנגשויות), בלי שום ציור. כשהם במחלקה נפרדת אפשר להריץ ולבדוק אותם בלי חלון.game logic: The game's state and rules (position, speed, collisions), with no drawing at all. In a separate class you can run and test them with no window.
- headless: הרצה בלי מסך. Java יכולה לצייר על
BufferedImageולשמור PNG גם בלי חלון: כך נוצרו התמונות באתר.headless: Running with no screen. Java can draw on aBufferedImageand save a PNG with no window: that's how the pictures on the site were made.
02חלון עם כדור קופץA window with a bouncing ball
Timer של Swing קורא כל 16ms (בערך 60 פעמים בשנייה) ל-update ול-repaint. Swing קורא ל-paintComponent, שמצייר את הכדור במקום החדש. זו לולאת המשחק.
A Swing Timer calls update and repaint every 16ms (about 60 times a second). Swing calls paintComponent, which draws the ball in its new place. That's the game loop.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
public class Main extends JPanel {
static final int W = 400, H = 240;
double x = 60, y = 50, vx = 3, vy = 2;
Main() {
setPreferredSize(new Dimension(W, H));
setBackground(new Color(0xF4F1EA));
new Timer(16, e -> {
update();
repaint();
}).start();
}
void update() {
x += vx;
y += vy;
if (x < 15 || x > W - 15) {
vx = -vx;
}
if (y < 15 || y > H - 15) {
vy = -vy;
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(new Color(0xC4410E));
g2.fillOval((int) x - 15, (int) y - 15, 30, 30);
}
public static void main(String[] args) {
JFrame f = new JFrame("Bouncing ball");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Main());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}להרצה במחשב שלכם: זה חלון אמיתי, ולכן צריך מסך. ב-IntelliJ מריצים את Main ורואים כדור קופץ. בתזכורת הבאה אותו ציור רץ כאן בלי מסך.
Run it on your computer: it's a real window, so it needs a screen. In IntelliJ run Main and watch a bouncing ball. In the next refresher the same drawing runs here with no screen.
03אותו ציור, על תמונהThe same drawing, on an image
Graphics2D מצייר גם על BufferedImage. התוכנית רצה באמת בזמן בניית האתר (headless), ושמרה את התמונה שאתם רואים מתחת לפלט.
Graphics2D draws on a BufferedImage too. The program really ran while building the site (headless), and saved the picture you see below the output.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Main {
public static void main(String[] args) throws Exception {
BufferedImage img = new BufferedImage(400, 200, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(0xF4F1EA));
g.fillRect(0, 0, 400, 200);
g.setColor(new Color(0x2D5BD0));
g.setStroke(new BasicStroke(4));
g.drawRect(10, 10, 380, 180);
int[][] balls = {{80, 60, 0xC4410E}, {200, 120, 0x0E9F8E}, {310, 70, 0x8A3FFC}};
for (int[] b : balls) {
g.setColor(new Color(b[2]));
g.fillOval(b[0] - 18, b[1] - 18, 36, 36);
}
g.setColor(new Color(0x1B1F2A));
g.drawString("frame 1: three balls", 20, 185);
g.dispose();
ImageIO.write(img, "png", new File("frame.png"));
System.out.println("saved frame.png " + img.getWidth() + "x" + img.getHeight());
}
}saved frame.png 400x200
04הלוגיקה לבדThe logic alone
בלי חלון ובלי ציור: רק Ball.update. כך רואים בסימולציה בדיוק מה קורה בכל טיק: x עולה, עובר את הקיר, ו-vx מתהפך.
No window and no drawing: just Ball.update. That way the simulation shows exactly what happens on each tick: x grows, passes the wall, and vx flips.
public class Main {
public static void main(String[] args) {
Ball b = new Ball(10, 20, 30, 0);
for (int tick = 1; tick <= 4; tick++) {
b.update(100);
System.out.println("tick " + tick + ": x=" + b.x + " vx=" + b.vx);
}
}
}
class Ball {
int x, y, vx, vy;
Ball(int x, int y, int vx, int vy) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
}
void update(int width) {
x += vx;
y += vy;
if (x < 0 || x > width) {
vx = -vx;
}
}
}tick 1: x=40 vx=30 tick 2: x=70 vx=30 tick 3: x=100 vx=30 tick 4: x=130 vx=-30
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05הצעד של היום בפרויקט מדףToday's step in the Shelf project
שלושה כדורים במשטח 100x100. update מחזירה true כשהכדור נגע בקיר. אחרי 10 טיקים הדפיסו את מספר ההתנגשויות ואת המיקום של כל כדור. זו הלוגיקה של המשחק; במחשב שלכם חברו אותה לחלון מהתזכורת הראשונה.
Three balls on a 100x100 field. update returns true when the ball hit a wall. After 10 ticks print the number of bounces and each ball's position. This is the game's logic; on your computer, connect it to the window from the first refresher.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
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.