"Tag" i Java - me pehea te whakawhanake i tetahi keemu tino

"Tag" i Java - me pehea te whakawhanake i tetahi keemu tino

"Tekau ma rima" ranei "Tekau ma rima" he tauira pai o te keemu arorau ngawari e rongonui ana puta noa i te ao. Hei whakaoti i te panga, me whakaraupapa nga tapawha me nga tau kia raupapa, mai i te iti ki te rahi. Ehara i te mea ngawari, engari he mea whakamere.

I roto i nga akoranga o tenei ra ka whakaatu matou ki a koe me pehea te whakawhanake i te tekau ma rima ki Java 8 me Eclipse. Hei whakawhanake i te UI ka whakamahia e matou te Swing API.

Ka whakamahara matou: mo nga kaipānui katoa o "Habr" - he utu mo te 10 rubles i te wa e whakauru ana ki tetahi akoranga Skillbox ma te whakamahi i te waehere whakatairanga "Habr".

Ka tūtohu a Skillbox: Matauranga ipurangi "Whakawhanake Mahi Java".

Hoahoa Kēmu

I tenei waahanga me tautuhi koe i nga ahuatanga:

  • Rahi — te rahi o te papa takaro;
  • nbTiles — te maha o nga tohu kei te mara. nbTiles = rahi*rahi - 1;
  • Ko nga taera he tohu he huinga ahua kotahi o nga tauoti. Ka whiwhi ia o nga tohu he uara ahurei i roto i te awhe [0, nbTiles]. Ko te tohu he tapawha kau;
  • blankPos — te tuunga o te tapawha kau.

arorau kēmu

Me tautuhi he tikanga tautuhi hei arawhiti i tetahi tuunga keemu hou. Ma tenei ka whakarite uara mo ia huānga o te huānga tūtohu. Ana, ka waiho e matou te blankPos ki te tuunga whakamutunga o te huinga.

Me whai tikanga riwhi hei riwhi i te huinga tohu. Kaore matou e whakauru i te tohu putua ki roto i te mahi riiwhi kia waiho ai kia rite tonu te tuunga.

I te mea ko te haurua anake o nga tuunga timatanga ka taea te panga o te panga he otinga, me tirotiro koe i te hua riwhi kia mohio ai ka taea te whakatau i te whakatakotoranga o naianei. Hei mahi i tenei, ka tautuhia e matou te tikanga isSolvable.

Mena kei mua i tetahi tohu he tohu he nui ake te uara, ka kiia he hurihanga. I te wa e noho ana te waahi kore, me rite te maha o nga hurihanga mo te panga kia wetekina. Na ka tatauhia te maha o nga hurihanga ka whakahoki pono mena he rite te tau.

He mea nui ki te tautuhi i te tikanga isSolved ki te tirotiro mena kua whakatauhia ta maatau Tahora Tahora O Te Tekau Ma rima. Tuatahi ka tirohia kei hea te waahi kau. Mena kei te tuunga tuatahi, he mea hou te rarangi o naianei, kaore i whakatauhia i mua. Ka huri ano tatou i roto i nga taera i roto i te raupapa whakamuri, a ki te rereke te uara o te tohu ki te taurangi e rite ana +1, ka whakahoki teka tatou. Ki te kore, i te mutunga o te tikanga kua tae ki te wa ki te hoki pono na te mea kua oti te panga.

Ko tetahi atu tikanga me tautuhi ko newGame. Me hanga he tauira hou o te keemu. Ki te mahi i tenei, ka tautuhi ano i te papa takaro, ka riwhi ka haere tonu kia taea ra ano te waahi takaro.

Anei he tauira waehere me te arorau matua o te tūtohu:

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

Ka mutu, me whakarite e koe te nekehanga o nga tohu i roto i te rarangi. Ka karangahia tenei waehere i muri mai ma te waea hoki hei whakautu ki te nekehanga pehu. Ka tautokohia e ta maatau keemu nga nekehanga taera maha i te wa kotahi. No reira, i muri i ta tatou huri i te waahi kua pehia ki runga i te mata hei tohu, ka whiwhi tatou i te waahi o te tohu karekau me te rapu huarahi mo te neke hei tautoko i te maha o ana nekehanga i te wa kotahi.

Anei he tauira waehere:

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

Ka whakawhanakehia e matou he UI ma te whakamahi i te Swing API

Kua tae ki te wa ki te mahi i runga i te atanga. Tuatahi ka tango tatou i te akomanga Jpanel. Na ka tuhia e matou nga tohu ki runga i te mara - ki te tatau i nga rahi o ia waahanga, ka whakamahia e matou nga raraunga kua tohua i roto i te tawhā hanga keemu:

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

Ko te tawhē hoki he tawhā kua whakaritea i roto i te kaihanga kēmu.

Inaianei me tautuhi i te tikanga drawGrid ki te tuhi i te matiti me nga waahi ki te mata. Ka tātarihia e matou te huinga o nga tohu ka huri i nga taunga ki nga taunga atanga kaiwhakamahi. Na ka tuhia ia waahi me te tau e rite ana ki waenganui:

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

Ka mutu, me whakakorehia te tikanga paintComponent, i ahu mai i te akomanga JPane. Ka whakamahi matou i te tikanga drawGrid, ka whai i te tikanga drawStartMessage hei whakaatu i tetahi karere e akiaki ana kia paato matou ki te timata i te keemu:

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

Te urupare ki nga mahi a nga kaiwhakamahi i te UI

Kia taea ai e te keemu te whakahaere i tana akoranga, me whakahaere nga mahi a nga kaiwhakamahi i roto i te UI. Hei mahi i tenei, taapirihia te whakatinanatanga o MouseListener ki Jpanel me te waehere mo nga waahi neke, kua whakaatuhia i runga ake nei:

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

Ka tuuhia te waehere ki te kaihanga o te akomanga GameOfFifteen. I te mutunga, ka karangahia e matou te tikanga houGame ki te timata i tetahi keemu hou.

Waehere kēmu katoa

Ko te mahi whakamutunga i mua i te kitenga o te keemu e mahi ana ko te whakakotahi i nga huānga waehere katoa. Anei te mea ka tupu:

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

Ka mutu, kia takaro tatou!

Kua tae ki te wa ki te whakarewa i te keemu me te whakamatau i te mahi. Me penei te ahua o te mara:

"Tag" i Java - me pehea te whakawhanake i tetahi keemu tino

Kia tamata tatou ki te whakaoti i te panga. Mena i pai nga mea katoa, ka whiwhi tatou i tenei:

"Tag" i Java - me pehea te whakawhanake i tetahi keemu tino

Heoi ano. I tumanako atu koe? 🙂

Ka tūtohu a Skillbox:

Source: will.com

Tāpiri i te kōrero