ஜாவாவில் "பதினைந்து" - ஒரு முழு அளவிலான விளையாட்டை எவ்வாறு உருவாக்குவது

ஜாவாவில் "பதினைந்து" - ஒரு முழு அளவிலான விளையாட்டை எவ்வாறு உருவாக்குவது

"பதினைந்து", அல்லது "பதினைந்து" உலகம் முழுவதும் பிரபலமான ஒரு எளிய லாஜிக் விளையாட்டின் சிறந்த எடுத்துக்காட்டு. புதிரைத் தீர்க்க, சிறியது முதல் பெரியது வரை வரிசையாக எண்களுடன் சதுரங்களை அமைக்க வேண்டும். இது எளிதானது அல்ல, ஆனால் சுவாரஸ்யமானது.

இன்றைய டுடோரியலில், எக்லிப்ஸுடன் ஜாவா 8 இல் பதினைந்தனை எவ்வாறு உருவாக்குவது என்பதை நாங்கள் உங்களுக்குக் காட்டுகிறோம். UI ஐ உருவாக்க, ஸ்விங் API ஐப் பயன்படுத்துவோம்.

நாங்கள் நினைவூட்டுகிறோம்: "Habr" இன் அனைத்து வாசகர்களுக்கும் - "Habr" விளம்பரக் குறியீட்டைப் பயன்படுத்தி எந்த Skillbox படிப்பிலும் சேரும்போது 10 ரூபிள் தள்ளுபடி.

Skillbox பரிந்துரைக்கிறது: கல்வி ஆன்லைன் படிப்பு "தொழில் ஜாவா டெவலப்பர்".

விளையாட்டு வடிவமைப்பு

இந்த கட்டத்தில், நீங்கள் பண்புகளை வரையறுக்க வேண்டும்:

  • அளவு - ஆடுகளத்தின் அளவு;
  • nbTiles - புலத்தில் உள்ள குறிச்சொற்களின் எண்ணிக்கை. nbTiles = அளவு*அளவு - 1;
  • டைல்ஸ் என்பது ஒரு குறிச்சொல், இது முழு எண்களின் ஒரு பரிமாண வரிசையாகும். குறிச்சொற்கள் ஒவ்வொன்றும் [0, nbTiles] வரம்பில் தனிப்பட்ட மதிப்பைப் பெறும். பூஜ்யம் வெற்று சதுரத்தைக் குறிக்கிறது;
  • blankPos - வெற்று சதுரத்தின் நிலை.

விளையாட்டு தர்க்கம்

புதிய கேம் நிலையை துவக்குவதற்கு பயன்படுத்தப்படும் மீட்டமைப்பு முறையை நாம் வரையறுக்க வேண்டும். இப்படித்தான் டேக் அரேயின் ஒவ்வொரு உறுப்புக்கும் ஒரு மதிப்பை அமைக்கிறோம். சரி, நாம் அணிவரிசையின் கடைசி நிலையில் blankPos ஐ வைக்கிறோம்.

குறிச்சொற்களின் வரிசையை மாற்றுவதற்கு நமக்கு ஒரு கலக்கல் முறையும் தேவை. அதன் அசல் நிலையில் அதை விட்டுவிட, மாற்றும் செயல்பாட்டில் வெற்று குறிச்சொல்லை நாங்கள் சேர்க்கவில்லை.

புதிரின் சாத்தியமான தொடக்க நிலைகளில் பாதி மட்டுமே ஒரு தீர்வைக் கொண்டிருப்பதால், தற்போதைய தளவமைப்பு பொதுவாக தீர்க்கக்கூடியதா என்பதை உறுதிப்படுத்த, கலக்கலின் முடிவைச் சரிபார்க்க வேண்டும். இதைச் செய்ய, isSolvable முறையை வரையறுக்கிறோம்.

ஒரு குறிப்பிட்ட புள்ளிக்கு முன்னால் அதிக மதிப்பு கொண்ட புள்ளி இருந்தால், அது தலைகீழாகக் கருதப்படுகிறது. வெற்று குறிச்சொல் இருக்கும் போது, ​​புதிர் தீர்க்கக்கூடியதாக இருக்க, தலைகீழ் எண்ணிக்கை சமமாக இருக்க வேண்டும். எனவே நாம் தலைகீழ் எண்ணிக்கையை எண்ணி, எண் சமமாக இருந்தால் உண்மை என்பதைத் தருகிறோம்.

அடுத்து, எங்கள் பதினைந்து கைகளின் விளையாட்டு தீர்க்கப்பட்டதா என்பதைச் சரிபார்க்க isSolved முறையை வரையறுப்பது முக்கியம். முதலில் வெற்று குறிச்சொல் எங்கு உள்ளது என்பதைப் பார்க்கிறோம். ஆரம்ப நிலையில் இருந்தால், தற்போதைய தளவமைப்பு புதியது, முன்பு தீர்க்கப்படவில்லை. பின் நாம் டைல்ஸ் மூலம் தலைகீழ் வரிசையில் லூப் செய்கிறோம். இல்லையெனில், புதிர் ஏற்கனவே தீர்க்கப்பட்டதால், முறையின் முடிவில் உண்மைக்குத் திரும்புவதற்கான நேரம் இது.

வரையறுக்கப்பட வேண்டிய மற்றொரு முறை புதிய விளையாட்டு. விளையாட்டின் புதிய நிகழ்வை உருவாக்க இது தேவைப்படுகிறது. இதைச் செய்ய, நாங்கள் கேம் போர்டை மீட்டமைத்து, பின்னர் அதை மாற்றி, கேம் நிலை தீர்க்கப்படும் வரை தொடரவும்.

குறிச்சொற்களின் முக்கிய தர்க்கத்துடன் குறியீட்டின் எடுத்துக்காட்டு இங்கே:

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;

ஸ்விங் API உடன் UI ஐ உருவாக்குதல்

இது இடைமுகத்திற்கான நேரம். முதலில் நாம் 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);
  }
}

இறுதியாக, JPane வகுப்பிலிருந்து பெறப்பட்ட பெயிண்ட்காம்பொனென்ட் முறையை மேலெழுதுவோம். நாங்கள் டிராக்ரிட் முறையைப் பயன்படுத்துகிறோம், பின்னர் விளையாட்டைத் தொடங்க கிளிக் செய்யும்படி ஒரு செய்தியைக் காண்பிக்க டிராஸ்டார்ட்மெசேஜ் முறையைப் பயன்படுத்துகிறோம்:

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 இல் பயனர் செயல்களைச் செயல்படுத்துவது அவசியம். இதைச் செய்ய, Jpanel இல் MouseListener இன் செயல்படுத்தல் மற்றும் குறிச்சொற்களை நகர்த்துவதற்கான குறியீடு, ஏற்கனவே மேலே காட்டப்பட்டுள்ளது:

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();
  }
});

கேம்ஆஃப் பதினைந்து வகுப்பின் கட்டமைப்பாளரில் குறியீடு வைக்கப்பட்டுள்ளது. இறுதியில், புதிய கேமைத் தொடங்க புதிய கேம் முறையை அழைக்கிறோம்.

முழு விளையாட்டு குறியீடு

விளையாட்டை செயலில் பார்ப்பதற்கு முன் கடைசி படியாக அனைத்து குறியீடு துண்டுகளையும் ஒன்றாக இணைக்க வேண்டும். என்ன நடக்கிறது என்பது இங்கே:

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);
    });
  }
 
 
}

இறுதியாக, விளையாடுவோம்!

விளையாட்டைத் துவக்கி அதைச் செயலில் சோதிக்க வேண்டிய நேரம் இது. புலம் இப்படி இருக்க வேண்டும்:

ஜாவாவில் "பதினைந்து" - ஒரு முழு அளவிலான விளையாட்டை எவ்வாறு உருவாக்குவது

புதிரைத் தீர்க்க முயற்சிப்போம். எல்லாம் சரியாக நடந்தால், நாங்கள் இதைப் பெறுகிறோம்:

ஜாவாவில் "பதினைந்து" - ஒரு முழு அளவிலான விளையாட்டை எவ்வாறு உருவாக்குவது

அவ்வளவுதான். அதிகமாக எதிர்பார்த்தீர்களா? 🙂

Skillbox பரிந்துரைக்கிறது:

ஆதாரம்: www.habr.com

கருத்தைச் சேர்