"แท็ก" ใน Java - วิธีพัฒนาเกมที่ครบครัน

"แท็ก" ใน Java - วิธีพัฒนาเกมที่ครบครัน

"สิบห้า" หรือ "สิบห้า" เป็นตัวอย่างที่ยอดเยี่ยมของเกมตรรกะง่ายๆ ที่ได้รับความนิยมไปทั่วโลก ในการแก้ปริศนา คุณจะต้องจัดเรียงสี่เหลี่ยมด้วยตัวเลขตามลำดับจากเล็กที่สุดไปใหญ่ที่สุด มันไม่ง่าย แต่มันก็น่าสนใจ

ในบทช่วยสอนวันนี้ เราจะแสดงวิธีพัฒนา Fifteen ใน Java 8 ด้วย Eclipse ในการพัฒนา UI เราจะใช้ Swing API

เราเตือนคุณ: สำหรับผู้อ่าน "Habr" ทุกคน - ส่วนลด 10 rubles เมื่อลงทะเบียนในหลักสูตร Skillbox ใด ๆ โดยใช้รหัสส่งเสริมการขาย "Habr"

Skillbox แนะนำ: หลักสูตรออนไลน์เพื่อการศึกษา "นักพัฒนาจาวามืออาชีพ".

การออกแบบเกม

ในขั้นตอนนี้ คุณจะต้องกำหนดคุณสมบัติ:

  • ขนาด — ขนาดของสนามเด็กเล่น
  • nbTiles — จำนวนแท็กในช่อง nbTiles = ขนาด*ขนาด - 1;
  • ไทล์เป็นแท็กที่เป็นอาร์เรย์จำนวนเต็มมิติเดียว แต่ละแท็กจะได้รับค่าที่ไม่ซ้ำกันในช่วง [0, nbTiles] ศูนย์หมายถึงสี่เหลี่ยมจัตุรัสว่าง
  • BlankPos — ตำแหน่งของช่องสี่เหลี่ยมว่าง

ตรรกะของเกม

เราจำเป็นต้องกำหนดวิธีการรีเซ็ตที่ใช้ในการเริ่มต้นตำแหน่งเกมใหม่ วิธีนี้เราจะตั้งค่าให้กับแต่ละองค์ประกอบของอาเรย์แท็ก ถ้าอย่างนั้น เราก็วาง BlankPos ไว้ที่ตำแหน่งสุดท้ายของอาร์เรย์

เรายังต้องมีวิธีการสับเปลี่ยนเพื่อสับเปลี่ยนอาร์เรย์ของแท็ก เราไม่ได้รวมแท็กว่างไว้ในกระบวนการสับเปลี่ยนเพื่อปล่อยให้อยู่ในตำแหน่งเดิม

เนื่องจากตำแหน่งเริ่มต้นที่เป็นไปได้ของปริศนามีเพียงครึ่งหนึ่งเท่านั้นที่มีวิธีแก้ปัญหา คุณจึงต้องตรวจสอบผลการสุ่มผลลัพธ์เพื่อให้แน่ใจว่าเค้าโครงปัจจุบันสามารถแก้ไขได้ เมื่อต้องการทำเช่นนี้ เรากำหนดวิธีการ isSolvable

หากแท็กใดแท็กหนึ่งนำหน้าด้วยแท็กที่มีค่าสูงกว่า จะถือว่าเป็นการกลับกัน เมื่อมีจุดว่าง จำนวนการกลับด้านจะต้องเท่ากันจึงจะไขปริศนาได้ ดังนั้นเราจึงนับจำนวนการผกผันและส่งคืนค่าเป็นจริงหากตัวเลขเป็นเลขคู่

สิ่งสำคัญคือต้องกำหนดวิธีการ isSolved เพื่อตรวจสอบว่าเค้าโครง Game Of Fifteen ของเราได้รับการแก้ไขแล้วหรือไม่ ก่อนอื่นเรามาดูกันว่าจุดว่างอยู่ที่ไหน หากอยู่ในตำแหน่งเริ่มต้น แสดงว่าการจัดตำแหน่งปัจจุบันเป็นการจัดตำแหน่งใหม่ ซึ่งไม่ได้ตัดสินใจไว้ก่อนหน้านี้ จากนั้นเราจะวนซ้ำไทล์ต่างๆ ในลำดับย้อนกลับ และหากค่าของแท็กแตกต่างจากดัชนี +1 ที่เกี่ยวข้อง เราจะคืนค่าเท็จ มิฉะนั้น เมื่อสิ้นสุดเมธอดก็ถึงเวลาส่งคืน true เนื่องจากปริศนาได้รับการแก้ไขแล้ว

อีกวิธีหนึ่งที่ต้องกำหนดคือ newGame จำเป็นต้องสร้างอินสแตนซ์ใหม่ของเกม ในการทำเช่นนี้ เราจะรีเซ็ตสนามแข่งขัน จากนั้นสับเปลี่ยนและเล่นต่อไปจนกว่าตำแหน่งการเล่นจะได้รับการแก้ไข

นี่คือโค้ดตัวอย่างที่มีตรรกะที่สำคัญของแท็ก:

private void newGame() {
  do {
    reset(); // reset in initial state
    shuffle(); // shuffle
  } while(!isSolvable()); // make it until grid be solvable
 
  gameOver = false;
}
 
private void reset() {
  for (int i = 0; i < tiles.length; i++) {
    tiles[i] = (i + 1) % tiles.length;
  }
 
  // we set blank cell at the last
  blankPos = tiles.length - 1;
}
 
private void shuffle() {
  // don't include the blank tile in the shuffle, leave in the solved position
  int n = nbTiles;
 
  while (n > 1) {
    int r = RANDOM.nextInt(n--);
    int tmp = tiles[r];
    tiles[r] = tiles[n];
    tiles[n] = tmp;
  }
}
 
// Only half permutations of the puzzle are solvable/
// Whenever a tile is preceded by a tile with higher value it counts
// as an inversion. In our case, with the blank tile in the solved position,
// the number of inversions must be even for the puzzle to be solvable
private boolean isSolvable() {
  int countInversions = 0;
 
  for (int i = 0; i < nbTiles; i++) {
    for (int j = 0; j < i; j++) {
      if (tiles[j] > tiles[i])
        countInversions++;
    }
  }
 
  return countInversions % 2 == 0;
}
 
private boolean isSolved() {
  if (tiles[tiles.length - 1] != 0) // if blank tile is not in the solved position ==> not solved
    return false;
 
  for (int i = nbTiles - 1; i >= 0; i--) {
    if (tiles[i] != i + 1)
      return false;
  }
 
  return true;
}

สุดท้ายนี้ คุณจะต้องตั้งโปรแกรมการเคลื่อนไหวของแท็กในอาร์เรย์ รหัสนี้จะถูกเรียกในภายหลังผ่านการเรียกกลับเพื่อตอบสนองต่อการเคลื่อนไหวของเคอร์เซอร์ เกมของเราจะรองรับการเคลื่อนที่ของไทล์หลายอันในเวลาเดียวกัน ดังนั้น หลังจากที่เราแปลงตำแหน่งที่กดบนหน้าจอเป็นแท็กแล้ว เราจะได้ตำแหน่งของแท็กเปล่าและมองหาทิศทางการเคลื่อนไหวเพื่อรองรับการเคลื่อนไหวหลายอย่างในเวลาเดียวกัน

นี่คือตัวอย่างรหัส:

// get position of the click
int ex = e.getX() - margin;
int ey = e.getY() - margin;
 
// click in the grid ?
if (ex < 0 || ex > gridSize  || ey < 0  || ey > gridSize)
  return;
 
// get position in the grid
int c1 = ex / tileSize;
int r1 = ey / tileSize;
 
// get position of the blank cell
int c2 = blankPos % size;
int r2 = blankPos / size;
 
// we convert in the 1D coord
int clickPos = r1 * size + c1;
 
int dir = 0;
 
// we search direction for multiple tile moves at once
if (c1 == c2  &&  Math.abs(r1 - r2) > 0)
  dir = (r1 - r2) > 0 ? size : -size;
else if (r1 == r2 && Math.abs(c1 - c2) > 0)
  dir = (c1 - c2) > 0 ? 1 : -1;
 
if (dir != 0) {
  // we move tiles in the direction
  do {
    int newBlankPos = blankPos + dir;
    tiles[blankPos] = tiles[newBlankPos];
    blankPos = newBlankPos;
  } while(blankPos != clickPos);
 
tiles[blankPos] = 0;

เราพัฒนา UI โดยใช้ Swing API

ได้เวลาทำงานกับอินเทอร์เฟซแล้ว ก่อนอื่นเรามาเรียนคลาส Jpanel จากนั้นเราจะวาดแท็กบนฟิลด์ - เพื่อคำนวณขนาดของแต่ละแท็ก เราจะใช้ข้อมูลที่ระบุในพารามิเตอร์ตัวสร้างเกม:

gridSize = (dim  -  2 * margin);
tileSize = gridSize / size;

มาร์จิ้นยังเป็นพารามิเตอร์ที่กำหนดในตัวสร้างเกมด้วย

ตอนนี้เราจำเป็นต้องกำหนดวิธี DrawGrid เพื่อวาดตารางและจุดบนหน้าจอ เราวิเคราะห์อาร์เรย์ของแท็กและแปลงพิกัดให้เป็นพิกัดอินเทอร์เฟซผู้ใช้ จากนั้นวาดแต่ละจุดโดยมีตัวเลขตรงกันอยู่ตรงกลาง:

private void drawGrid(Graphics2D g) {
  for (int i = 0; i < tiles.length; i++) {
    // we convert 1D coords to 2D coords given the size of the 2D Array
    int r = i / size;
    int c = i % size;
    // we convert in coords on the UI
    int x = margin + c * tileSize;
    int y = margin + r * tileSize;
 
    // check special case for blank tile
    if(tiles[i] == 0) {
      if (gameOver) {
        g.setColor(FOREGROUND_COLOR);
        drawCenteredString(g, "u2713", x, y);
      }
 
      continue;
    }
 
    // for other tiles
    g.setColor(getForeground());
    g.fillRoundRect(x, y, tileSize, tileSize, 25, 25);
    g.setColor(Color.BLACK);
    g.drawRoundRect(x, y, tileSize, tileSize, 25, 25);
    g.setColor(Color.WHITE);
 
    drawCenteredString(g, String.valueOf(tiles[i]), x , y);
  }
}

สุดท้ายนี้ เรามาแทนที่เมธอด paintComponent ซึ่งได้มาจากคลาส JPane จากนั้นเราใช้วิธี DrawGrid ตามด้วยวิธี DrawStartMessage เพื่อแสดงข้อความแจ้งให้คลิกเพื่อเริ่มเกม:

private void drawStartMessage(Graphics2D g) {
  if (gameOver) {
    g.setFont(getFont().deriveFont(Font.BOLD, 18));
    g.setColor(FOREGROUND_COLOR);
    String s = "Click to start new game";
    g.drawString(s, (getWidth() - g.getFontMetrics().stringWidth(s)) / 2,
        getHeight() - margin);
  }
}
 
private void drawCenteredString(Graphics2D g, String s, int x, int y) {
  // center string s for the given tile (x,y)
  FontMetrics fm = g.getFontMetrics();
  int asc = fm.getAscent();
  int desc = fm.getDescent();
  g.drawString(s,  x + (tileSize - fm.stringWidth(s)) / 2,
      y + (asc + (tileSize - (asc + desc)) / 2));
}
 
@Override
protected void paintComponent(Graphics g) {
  super.paintComponent(g);
  Graphics2D g2D = (Graphics2D) g;
  g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  drawGrid(g2D);
  drawStartMessage(g2D);
}

ตอบสนองต่อการกระทำของผู้ใช้ใน UI

เพื่อให้เกมทำงานได้ จำเป็นต้องประมวลผลการกระทำของผู้ใช้ใน UI ในการดำเนินการนี้ ให้เพิ่มการใช้งาน MouseListener บน Jpanel และโค้ดสำหรับจุดเคลื่อนที่ ดังที่แสดงไว้ด้านบนแล้ว:

addMouseListener(new MouseAdapter() {
  @Override
  public void mousePressed(MouseEvent e) {
    // used to let users to interact on the grid by clicking
    // it's time to implement interaction with users to move tiles to solve the game !
    if (gameOver) {
      newGame();
    } else {
      // get position of the click
      int ex = e.getX() - margin;
      int ey = e.getY() - margin;
 
      // click in the grid ?
      if (ex < 0 || ex > gridSize  || ey < 0  || ey > gridSize)
        return;
 
      // get position in the grid
      int c1 = ex / tileSize;
      int r1 = ey / tileSize;
 
      // get position of the blank cell
      int c2 = blankPos % size;
      int r2 = blankPos / size;
 
      // we convert in the 1D coord
      int clickPos = r1 * size + c1;
 
      int dir = 0;
 
      // we search direction for multiple tile moves at once
      if (c1 == c2  &&  Math.abs(r1 - r2) > 0)
        dir = (r1 - r2) > 0 ? size : -size;
      else if (r1 == r2 && Math.abs(c1 - c2) > 0)
        dir = (c1 - c2) > 0 ? 1 : -1;
 
      if (dir != 0) {
        // we move tiles in the direction
        do {
          int newBlankPos = blankPos + dir;
          tiles[blankPos] = tiles[newBlankPos];
          blankPos = newBlankPos;
        } while(blankPos != clickPos);
 
        tiles[blankPos] = 0;
      }
 
      // we check if game is solved
      gameOver = isSolved();
    }
 
    // we repaint panel
    repaint();
  }
});

เราวางโค้ดไว้ใน Constructor ของคลาส GameOfFifteen ในตอนท้ายสุด เราเรียกเมธอด newGame เพื่อเริ่มเกมใหม่

รหัสเกมเต็ม

ขั้นตอนสุดท้ายก่อนที่จะเริ่มเล่นเกมคือการรวบรวมองค์ประกอบโค้ดทั้งหมดเข้าด้วยกัน นี่คือสิ่งที่เกิดขึ้น:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
 
// We are going to create a Game of 15 Puzzle with Java 8 and Swing
// If you have some questions, feel free to read comments ;)
public class GameOfFifteen extends JPanel { // our grid will be drawn in a dedicated Panel
 
  // Size of our Game of Fifteen instance
  private int size;
  // Number of tiles
  private int nbTiles;
  // Grid UI Dimension
  private int dimension;
  // Foreground Color
  private static final Color FOREGROUND_COLOR = new Color(239, 83, 80); // we use arbitrary color
  // Random object to shuffle tiles
  private static final Random RANDOM = new Random();
  // Storing the tiles in a 1D Array of integers
  private int[] tiles;
  // Size of tile on UI
  private int tileSize;
  // Position of the blank tile
  private int blankPos;
  // Margin for the grid on the frame
  private int margin;
  // Grid UI Size
  private int gridSize;
  private boolean gameOver; // true if game over, false otherwise
 
  public GameOfFifteen(int size, int dim, int mar) {
    this.size = size;
    dimension = dim;
    margin = mar;
    
    // init tiles
    nbTiles = size * size - 1; // -1 because we don't count blank tile
    tiles = new int[size * size];
    
    // calculate grid size and tile size
    gridSize = (dim - 2 * margin);
    tileSize = gridSize / size;
    
    setPreferredSize(new Dimension(dimension, dimension + margin));
    setBackground(Color.WHITE);
    setForeground(FOREGROUND_COLOR);
    setFont(new Font("SansSerif", Font.BOLD, 60));
    
    gameOver = true;
    
    addMouseListener(new MouseAdapter() {
      @Override
      public void mousePressed(MouseEvent e) {
        // used to let users to interact on the grid by clicking
        // it's time to implement interaction with users to move tiles to solve the game !
        if (gameOver) {
          newGame();
        } else {
          // get position of the click
          int ex = e.getX() - margin;
          int ey = e.getY() - margin;
          
          // click in the grid ?
          if (ex < 0 || ex > gridSize  || ey < 0  || ey > gridSize)
            return;
          
          // get position in the grid
          int c1 = ex / tileSize;
          int r1 = ey / tileSize;
          
          // get position of the blank cell
          int c2 = blankPos % size;
          int r2 = blankPos / size;
          
          // we convert in the 1D coord
          int clickPos = r1 * size + c1;
          
          int dir = 0;
          
          // we search direction for multiple tile moves at once
          if (c1 == c2  &&  Math.abs(r1 - r2) > 0)
            dir = (r1 - r2) > 0 ? size : -size;
          else if (r1 == r2 && Math.abs(c1 - c2) > 0)
            dir = (c1 - c2) > 0 ? 1 : -1;
            
          if (dir != 0) {
            // we move tiles in the direction
            do {
              int newBlankPos = blankPos + dir;
              tiles[blankPos] = tiles[newBlankPos];
              blankPos = newBlankPos;
            } while(blankPos != clickPos);
            
            tiles[blankPos] = 0;
          }
          
          // we check if game is solved
          gameOver = isSolved();
        }
        
        // we repaint panel
        repaint();
      }
    });
    
    newGame();
  }
 
  private void newGame() {
    do {
      reset(); // reset in intial state
      shuffle(); // shuffle
    } while(!isSolvable()); // make it until grid be solvable
    
    gameOver = false;
  }
 
  private void reset() {
    for (int i = 0; i < tiles.length; i++) {
      tiles[i] = (i + 1) % tiles.length;
    }
    
    // we set blank cell at the last
    blankPos = tiles.length - 1;
  }
 
  private void shuffle() {
    // don't include the blank tile in the shuffle, leave in the solved position
    int n = nbTiles;
    
    while (n > 1) {
      int r = RANDOM.nextInt(n--);
      int tmp = tiles[r];
      tiles[r] = tiles[n];
      tiles[n] = tmp;
    }
  }
 
  // Only half permutations of the puzzle are solvable.
  // Whenever a tile is preceded by a tile with higher value it counts
  // as an inversion. In our case, with the blank tile in the solved position,
  // the number of inversions must be even for the puzzle to be solvable
  private boolean isSolvable() {
    int countInversions = 0;
    
    for (int i = 0; i < nbTiles; i++) {
      for (int j = 0; j < i; j++) {
        if (tiles[j] > tiles[i])
          countInversions++;
      }
    }
    
    return countInversions % 2 == 0;
  }
 
  private boolean isSolved() {
    if (tiles[tiles.length - 1] != 0) // if blank tile is not in the solved position ==> not solved
      return false;
    
    for (int i = nbTiles - 1; i >= 0; i--) {
      if (tiles[i] != i + 1)
        return false;      
    }
    
    return true;
  }
 
  private void drawGrid(Graphics2D g) {
    for (int i = 0; i < tiles.length; i++) {
      // we convert 1D coords to 2D coords given the size of the 2D Array
      int r = i / size;
      int c = i % size;
      // we convert in coords on the UI
      int x = margin + c * tileSize;
      int y = margin + r * tileSize;
      
      // check special case for blank tile
      if(tiles[i] == 0) {
        if (gameOver) {
          g.setColor(FOREGROUND_COLOR);
          drawCenteredString(g, "u2713", x, y);
        }
        
        continue;
      }
      
      // for other tiles
      g.setColor(getForeground());
      g.fillRoundRect(x, y, tileSize, tileSize, 25, 25);
      g.setColor(Color.BLACK);
      g.drawRoundRect(x, y, tileSize, tileSize, 25, 25);
      g.setColor(Color.WHITE);
      
      drawCenteredString(g, String.valueOf(tiles[i]), x , y);
    }
  }
 
  private void drawStartMessage(Graphics2D g) {
    if (gameOver) {
      g.setFont(getFont().deriveFont(Font.BOLD, 18));
      g.setColor(FOREGROUND_COLOR);
      String s = "Click to start new game";
      g.drawString(s, (getWidth() - g.getFontMetrics().stringWidth(s)) / 2,
          getHeight() - margin);
    }
  }
 
  private void drawCenteredString(Graphics2D g, String s, int x, int y) {
    // center string s for the given tile (x,y)
    FontMetrics fm = g.getFontMetrics();
    int asc = fm.getAscent();
    int desc = fm.getDescent();
    g.drawString(s,  x + (tileSize - fm.stringWidth(s)) / 2,
        y + (asc + (tileSize - (asc + desc)) / 2));
  }
 
  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2D = (Graphics2D) g;
    g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    drawGrid(g2D);
    drawStartMessage(g2D);
  }
 
  public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setTitle("Game of Fifteen");
      frame.setResizable(false);
      frame.add(new GameOfFifteen(4, 550, 30), BorderLayout.CENTER);
      frame.pack();
      // center on the screen
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
    });
  }
 
 
}

ในที่สุดก็มาเล่นกัน!

ถึงเวลาที่จะเปิดตัวเกมและทดสอบการใช้งานจริง ฟิลด์ควรมีลักษณะเช่นนี้:

"แท็ก" ใน Java - วิธีพัฒนาเกมที่ครบครัน

มาลองไขปริศนากัน หากทุกอย่างเป็นไปด้วยดี เราจะได้สิ่งนี้:

"แท็ก" ใน Java - วิธีพัฒนาเกมที่ครบครัน

นั่นคือทั้งหมดที่ คุณคาดหวังมากกว่านี้ไหม? 🙂

Skillbox แนะนำ:

ที่มา: will.com

เพิ่มความคิดเห็น