"Tag" ma Java - pehea e hoʻomohala ai i kahi pāʻani piha

"Tag" ma Java - pehea e hoʻomohala ai i kahi pāʻani piha

"ʻumikūmālima" a i ʻole "ʻumikūmālima" he laʻana maikaʻi loa ia o kahi pāʻani loiloi maʻalahi i kaulana a puni ka honua. I mea e hoʻoponopono ai i ka puzzle, pono ʻoe e hoʻonohonoho i nā ʻāpana me nā helu i ka hoʻonohonoho, mai ka liʻiliʻi a hiki i ka nui. ʻAʻole maʻalahi, akā hoihoi.

Ma ke kumu aʻo i kēia lā e hōʻike mākou iā ʻoe pehea e hoʻomohala ai i ʻumikumamālima ma Java 8 me Eclipse. No ka hoʻomohala ʻana i ka UI e hoʻohana mākou i ka Swing API.

Hoʻomaopopo mākou iā ʻoe: no ka poʻe heluhelu a pau o "Habr" - kahi ho'ēmi o 10 rubles i ka wā e kākau inoa ai i kekahi papa Skillbox e hoʻohana ana i ka code promotional "Habr".

Manaʻo ʻo Skillbox: Papa hoʻonaʻauao pūnaewele "Ka mea hoʻomohala ʻoihana Java".

Hoʻolālā pāʻani

I kēia pae, pono ʻoe e wehewehe i nā waiwai:

  • Nui - ka nui o ke kahua pāʻani;
  • nbTiles - ka helu o nā hōʻailona ma ke kahua. nbTiles = nui * nui - 1;
  • ʻO nā tile he hōʻailona ia he pūʻulu mana hoʻokahi o nā helu helu. E loaʻa i kēlā me kēia o nā hōʻailona kahi waiwai kūʻokoʻa ma ka laulā [0, nbTiles]. Hōʻike ʻo Zero i kahi huinahā kaʻawale;
  • blankPos - ke kūlana o ka huinahā ʻole.

Loko pāʻani

Pono mākou e wehewehe i kahi ʻano hoʻoponopono i hoʻohana ʻia e hoʻomaka i kahi kūlana pāʻani hou. Ma kēia ala mākou e hoʻonoho ai i kahi waiwai no kēlā me kēia ʻāpana o ka papa inoa. ʻAe, a laila kau mākou i nā blankPos ma ke kūlana hope o ka array.

Pono mākou i kahi ʻano shuffle e shuffle i ka pūʻulu o nā hōʻailona. ʻAʻole mākou e hoʻokomo i ka hōʻailona hakahaka i ke kaʻina shuffling i mea e waiho ai ma ke kūlana like.

No ka mea ʻo ka hapalua wale nō o nā kūlana hoʻomaka o ka puzzle ka hopena, pono ʻoe e nānā i ka hopena shuffle hopena e hōʻoia i ka hiki ke hoʻonā ʻia ka hoʻolālā o kēia manawa. No ka hana ʻana i kēia, wehewehe mākou i ke ʻano isSolvable.

Inā hoʻokomo mua ʻia kekahi hōʻailona me ka waiwai ʻoi aku ka kiʻekiʻe, ua manaʻo ʻia he hoʻohuli. Ke waiho ʻia ka wahi kaʻawale, pono ka nui o nā hoʻololi ʻana i hiki ke hoʻonā ʻia ka puzzle. No laila, helu mākou i ka helu o ka hoʻohuli ʻana a hoʻihoʻi i ka ʻoiaʻiʻo inā like ka helu.

A laila, he mea nui e wehewehe i ke ala isSolved e nānā inā ua hoʻoholo ʻia kā mākou Game Of Fifteen layout. E nana mua kakou i kahi o ka hakahaka. Inā ma ke kūlana mua, he mea hou ka alignment o kēia manawa, ʻaʻole i hoʻoholo mua ʻia. A laila, hoʻololi mākou i nā tile ma ka ʻaoʻao hope, a inā ʻokoʻa ke kumukūʻai o ka hōʻailona mai ka index pili +1, e hoʻihoʻi mākou i ka wahaheʻe. A i ʻole, i ka pau ʻana o ke ala ʻo ia ka manawa e hoʻihoʻi ʻoiaʻiʻo no ka mea ua hoʻoholo ʻia ka puzzle.

ʻO kahi ala ʻē aʻe e pono e wehewehe ʻia ʻo newGame. Pono e hana i kahi mea hou o ka pāʻani. No ka hana ʻana i kēia, hoʻihoʻi mākou i ke kahua pāʻani, a laila hoʻokaʻawale a hoʻomau a hiki i ka hoʻoholo ʻana o ke kūlana pāʻani.

Eia kahi code laʻana me ka loiloi kī o ka tag:

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

ʻO ka hope, pono ʻoe e hoʻolālā i ka neʻe ʻana o nā hōʻailona ma ka array. E kāhea ʻia kēia code ma hope aku ma o ka callback e pane i ka neʻe ʻana o ka cursor. E kākoʻo kā mākou pāʻani i nā neʻe tile he nui i ka manawa like. No laila, ma hope o ko mākou hoʻololi ʻana i ke kūlana i kaomi ʻia ma ka pale i kahi hōʻailona, ​​​​loaʻa iā mākou ke kūlana o ka tag hakahaka a ʻimi i kahi kuhikuhi o ka neʻe ʻana e kākoʻo i kekahi o kāna mau neʻe i ka manawa like.

Eia kekahi laʻana code:

// 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;

Hoʻomohala mākou i ka UI me ka Swing API

ʻO ka manawa kēia e hana ai ma ka interface. Lawe mua mākou i ka papa Jpanel. A laila huki mākou i nā hōʻailona ma ke kahua - e helu i ka nui o kēlā me kēia, e hoʻohana mākou i ka ʻikepili i kuhikuhi ʻia i ka pāʻani constructor parameter:

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

ʻO Margin kekahi ʻāpana i hoʻonohonoho ʻia i ka mea kūkulu pāʻani.

I kēia manawa pono mākou e wehewehe i ke ala drawGrid e huki i ka mākia a me nā kiko ma ka pale. Hoʻopili mākou i ke ʻano o nā hōʻailona a hoʻololi i nā hoʻonohonoho i nā hoʻonohonoho hoʻohana. A laila e kaha kiʻi i kēlā me kēia wahi me ka helu i waena:

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

ʻO ka hope, e hoʻopau i ke ʻano paintComponent, i loaʻa mai ka papa JPane. A laila hoʻohana mākou i ke ala drawGrid, a ukali ʻia e ke ala drawStartMessage e hōʻike i kahi leka e koi ana iā mākou e kaomi e hoʻomaka i ka pāʻani:

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

Ka pane ʻana i nā hana mea hoʻohana ma ka UI

I mea e holo ai ka pāʻani i kāna papa, pono e hana i nā hana mea hoʻohana ma ka UI. No ka hana ʻana i kēia, hoʻohui i ka hoʻokō ʻana o MouseListener ma Jpanel a me ke code no ka neʻe ʻana i nā wahi, i hōʻike ʻia ma luna.

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

Hoʻokomo mākou i ke code i ka mea hana o ka papa GameOfFifteen. I ka hopena hope loa, kāhea mākou i ke ala houGame e hoʻomaka i kahi pāʻani hou.

Pāʻani pāʻani piha

ʻO ka hana hope ma mua o ka ʻike ʻana i ka pāʻani i ka hana, ʻo ia ka hoʻohui ʻana i nā mea code a pau. Eia ka mea e hana nei:

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

ʻO ka hope, e pāʻani kākou!

ʻO ka manawa kēia e hoʻomaka ai i ka pāʻani a hoʻāʻo iā ia i ka hana. Pono ke kahua penei:

"Tag" ma Java - pehea e hoʻomohala ai i kahi pāʻani piha

E ho'āʻo kākou e hoʻonā i ka puzzle. Inā maikaʻi nā mea a pau, loaʻa iā mākou kēia:

"Tag" ma Java - pehea e hoʻomohala ai i kahi pāʻani piha

ʻo ia wale nō. Ua manaʻo hou ʻoe? 🙂

Manaʻo ʻo Skillbox:

Source: www.habr.com

Pākuʻi i ka manaʻo hoʻopuka