2013-08-18 3 views
0

좋아, 지금이 잠시 동안 자바에서이 메모리 게임 애플릿을 작업 해왔다. 그리고 나는 모든 정렬과 매칭 알고리즘을 알아 냈다. 나는 단지 비참한 시간을 갖기 위해 노력했다. 내 GUI가 제대로 작동합니다. "뒤집기"를하기 위해 "카드"중 하나를 클릭 할 때마다 나는 커서가있는 곳까지 올라갈 때까지 뒤쪽의 카드가 카드 아래에있는 동안 만들어지는 카드의 열로 끝납니다. 왜 이런 일이 일어나고 있는지, 어떻게 멈추는 지 잘 모르겠다면 매우 실망 스럽습니다.메모리 게임 애플릿에서 겹치는 배경 그래픽

import java.awt.Color; 
import java.awt.Component; 
import java.awt.Dimension; 
import java.awt.Font; 
import java.awt.Graphics; 
import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import java.awt.Polygon; 
import java.awt.Rectangle; 
import java.awt.event.MouseEvent; 
import java.awt.event.MouseListener; 
import java.util.ArrayList; 

import javax.swing.*; 

public class Display extends JPanel implements MouseListener { 

private String[] Colors = Card.validColors(); 
private String[] Shapes = Card.validShapes(); 
private Component[] place; 
private JButton[][] buttonGrid= new JButton[6][6]; 
private Rectangle[][] triggers = new Rectangle[6][6]; 
private Board game; 
private Polygon star = new Polygon(); 
private Card pick; 
private boolean turnPhase2 = false; 
private Font serifNames = new Font(Font.SERIF, Font.PLAIN, 18); 
private Font serifCards = new Font(Font.SERIF, Font.ROMAN_BASELINE, 36); 
private JPanel panel = new JPanel(); 

public Display() { 
    this.setBackground(Color.BLACK); 
    this.setLayout(new GridBagLayout()); 
    panel.setSize(590, 410); 
    panel.setLayout(new GridLayout(6, 6, 10, 10)); 
    panel.setOpaque(false); 

    generateStar(); 
    buildBoard(); 
    fillButtonArray(); 

    this.addMouseListener(this); 
    this.add(panel); 
    System.out.println(getFontMetrics(serifCards)); 
    System.out.println(getFontMetrics(serifNames)); 
} 



public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    place = panel.getComponents(); 
    for (int i = 0; i < place.length; i++) { 
     paintBack(g, place[i].getX() + 25, place[i].getY() + 35); 
    } 
    displayNames(g); 
    displayTurn(g); 
    if (game.flippedCard() != null) { 
     int[] xy = game.flippedCardLocation(); 
     paintCard(g, game.flippedCard(), xy[0], xy[1]); 
    } 
} 

/** 
* This method builds the game board. 
* 
* 
*/ 
private void buildBoard() { 
    game = new Board(buildDeck()); 
} 

/** 
* This method creates a "deck" of cards with which we can create the game board. 
* 
* @return deck Returns the deck of Card objects in the form of an ArrayList. 
*/ 
private ArrayList<Card> buildDeck() { 
    ArrayList<Card> deck = new ArrayList<Card>(); 

    for (int i = 0; i < Colors.length; i++) { 
     for (int s = 0; s < Shapes.length; s++) { 
      Card first = new Card(Shapes[s], Colors[i]); 
      Card second = new Card(Shapes[s], Colors[i]); 
      deck.add(first); 
      deck.add(second); 
     } 
    } 
    System.out.println(deck.size()); 
    return deck; 
} 

private void fillButtonArray() { 
    for (int i = 0; i < 6; i++) { 
     for (int n = 0; n < 6; n++) { 
      JButton button = new JButton(); 
      button.setPreferredSize(new Dimension(90, 60)); 
      button.addMouseListener(this); 
      button.setOpaque(false); 
      button.setContentAreaFilled(false); 
      button.setBorderPainted(false); 

      buttonGrid[i][n] = button; 
     } 
    } 
    fillGrid(); 
} 

private void fillGrid() { 
    panel.setBounds(25, 35, panel.getSize().width, panel.getSize().height); 
    int count = 0; 
    for (int i = 0; i < 6; i++) { 
     for (int s = 0; s < 6; s++) { 
      panel.add(buttonGrid[i][s]); 
      place = panel.getComponents(); 
      int x = panel.getComponent(count).getBounds().x; 
      int y = panel.getComponent(count).getBounds().y; 
      Rectangle rect = new Rectangle(x, y, 90, 60); 
      triggers[i][s] = rect; 
     } 
    } 

} 

private void paintBack(Graphics g, int x, int y) { 
    g.setColor(Color.WHITE); 
    g.drawRoundRect(x, y, 90, 60, 2, 4); 
    g.fillRoundRect(x, y, 90, 60, 2, 4); 
    g.setColor(Color.BLACK); 
    g.setFont(serifCards); 
    g.drawString("M", x + 28, y + 42); 
} 

private void paintCard(Graphics g, Card card, int x, int y) { 
    g.setColor(Color.GRAY); 
    g.drawRoundRect(x, y, 90, 60, 2, 4); 
    g.fillRoundRect(x, y, 90, 60, 2, 4); 
    String color = card.getColor(); 
    String shape = card.getShape(); 

    if (shape.equals("Star")) { 
     g.setColor(pickColor(color)); 
     star.translate(x + 25, y + 10); 
     g.drawPolygon(star); 
     g.fillPolygon(star); 

    } 
    else if (shape.equals("Circle")) { 
     g.setColor(pickColor(color)); 
     g.drawOval(x + 25, y + 10, 40, 40); 
     g.fillOval(x + 25, y + 10, 40, 40); 
    } 
    else if (shape.equals("Square")) { 
     g.setColor(pickColor(color)); 
     g.drawRect(x + 25, y + 10, 40, 40); 
     g.fillRect(x + 25, y + 10, 40, 40); 
    } 
} 



private void displayNames(Graphics g) { 
    g.setFont(serifNames); 
    int[] scores = game.getCurrentScores(); 

    for (int i = 0; i < scores.length; i++) { 
     if (i == 0) { 
      g.setColor(Color.CYAN); 
      g.drawString("Cyan: " + scores[i], 10, 24); 
     } 
     else if (i == 1) { 
      g.setColor(Color.ORANGE); 
      g.drawString("Orange: " + scores[i], 560, 24); 
     } 
     else if (i == 2) { 
      g.setColor(Color.MAGENTA); 
      g.drawString("Magenta: " + scores[i], 10, 470); 
     } 
     else { 
      g.setColor(Color.WHITE); 
      g.drawString("White: " + scores[i], 569, 470); 
     } 
    } 
} 

private void displayTurn(Graphics g) { 
    int player = game.getCurrentPlayer(); 

    if (player == 0) { 
     g.setColor(Color.CYAN); 
     String str = "Cyan's Turn"; 
     g.drawString(str, 640/2 - 48, 24); 
     //System.out.println(getFontMetrics(serifNames).stringWidth(str)/2 + " Cyan"); 
    } 
    else if (player == 1) { 
     g.setColor(Color.ORANGE); 
     String str = "Orange's Turn"; 
     g.drawString(str, 640/2 - 52, 24); 
     //System.out.println(getFontMetrics(serifNames).stringWidth(str)/2 + " Orange"); 
    } 
    else if (player == 2) { 
     g.setColor(Color.MAGENTA); 
     String str = "Magenta's Turn"; 
     g.drawString(str, 640/2 - 57, 24); 
     //System.out.println(getFontMetrics(serifNames).stringWidth(str)/2 + " Magenta"); 
    } 
    else { 
     g.setColor(Color.WHITE); 
     String str = "White's Turn"; 
     g.drawString(str, 640/2 - 47, 24); 
     //System.out.println(getFontMetrics(serifNames).stringWidth(str)/2 + " White"); 
    } 
} 

private void findTrigger(int x, int y) { 
    for (int i = 0; i < 6; i++) { 
     if() { 

     } 
     for (int s = 0; s < 6; s++) { 
      Rectangle rectTest = triggers[i][s]; 
      if (x >= rectTest.getMinX() && 
        x <= rectTest.getMaxX() && 
        y >= rectTest.getMinY() && 
        y <= rectTest.getMaxY()) { 
       Graphics g = getGraphics(); 
       paintCard(g, game.flip(i,s), buttonGrid[i][s].getBounds().x, buttonGrid[i][s].getBounds().y); 
       break; 
      } 
     } 
    } 
} 

private void generateStar() { 
    star.addPoint(20, 0); 
    star.addPoint(25, 15); 
    star.addPoint(40, 15); 
    star.addPoint(28, 24); 
    star.addPoint(32, 40); 
    star.addPoint(20, 30); 
    star.addPoint(8, 40); 
    star.addPoint(12, 24); 
    star.addPoint(0, 15); 
    star.addPoint(15, 15); 
} 

private Color pickColor(String color) { 
    if (color.equals("Black")) { 
     return Color.BLACK; 
    } 
    if (color.equals("Yellow")) { 
     return Color.YELLOW; 
    } 
    if (color.equals("Green")) { 
     return Color.GREEN; 
    } 
    if (color.equals("Blue")) { 
     return Color.BLUE; 
    } 
    if (color.equals("Red")) { 
     return Color.RED; 
    } 
    if (color.equals("Purple")) { 
     return new Color(128, 0, 255); 
    } 
    return null; 
} 

@Override 
public void mouseClicked(MouseEvent e) { 
    System.out.println("Mouse Clicked"); 
    int x = e.getX(); 
    System.out.println(x + " is x"); 
    int y = e.getY(); 
    System.out.println(y + " is Y"); 
    System.out.println(panel.getWidth() + 25); 
    System.out.println(panel.getHeight() + 35); 

    System.out.println("Finding the trigger rectangle"); 
    findTrigger(x, y); 
} 

@Override 
public void mouseEntered(MouseEvent e) { 
    //System.out.println("Mouse Entered"); 
} 

@Override 
public void mouseExited(MouseEvent e) { 
    //System.out.println("Mouse Exited"); 
} 

@Override 
public void mousePressed(MouseEvent e) { 
    System.out.println("Mouse Pressed"); 
} 

@Override 
public void mouseReleased(MouseEvent e) { 
    System.out.println("Mouse Released"); 
} 

}

일부 측면 노트는 실제 게임 보드 객체가 취급되어 있으며 모든 멀티 메모리 게임을 만들고 실행하는 데 필요한 방법과 카드 개체가 있습니다 : 여기 내 디스플레이 클래스 게임에서 일치시킬 모양과 색상의 문자열 두 개만 포함합니다. 마지막으로 마지막 클래스는 내가 제공 할 Memory 클래스입니다.

import java.awt.Color; 
import java.awt.event.ActionEvent; 

import javax.swing.AbstractAction; 
import javax.swing.Action; 
import javax.swing.JApplet; 

public class Memory extends JApplet { 
private Display _theDisplay; 
final int width = 640; 
final int height = 480; 

private Action reDraw = new AbstractAction() { 
    public void actionPerformed(ActionEvent e) { 
     repaint(); 
    } 
}; 

public Memory() { 
    _theDisplay = new Display(); 
} 

public void init() { 
    setSize(width, height); 
    setBackground(Color.BLACK); 
    this.add(_theDisplay); 
} 

} 

팁을 보내 주시면 감사하겠습니다. 미리 감사드립니다.

답변

4

그래픽이 엉망으로 보입니다. 따라서 엉망 수 또는이 될 수있는 NPE의 원인이

  • 당신은 그것의 그래픽 컨텍스트와 그릴,하지만 그래픽이 지속되지 않습니다이 방법으로 얻은 객체 양해 바랍니다에 구성 요소에 getGraphics()를 호출 : 문제는 내가 볼 던져.
  • paintComponent(...) 메서드를 통해 모든 수동 그래픽을 만드는 것이 좋습니다. 미리 만들어진 드로잉이 필요한 경우 BufferedImages에서이 작업을 수행하고 JComponent의 paintComponent(...) 메서드에서 BufferedImages를 그립니다.
  • 디스플레이 JPanel에서 카드와 뒷면의 모든 페인팅을 수행하는 대신, 각 카드가 자체 상태를 가진 별도의 객체가되어 그 상태에 따라 올바르게 그려지는 것이 좋습니다. JComponent를 확장하거나 디스플레이 JPanel에 의해 그려지는 논리적 엔티티가되도록 할 수도 있지만, 코딩과 디버깅을 단순화하기 위해 디스플레이와 로직을 구분할 수 있습니다.
  • 큰 문제는 사용자의 findTrigger(...) 방법에있는 것처럼 보이므로 여기에 집중해야합니다. 위에 표시된대로 논리적 인 카드의 상태를 변경하려면 mouseClick을 사용해야합니다. 그러면 카드가 paintComponent(...)에 그려진 경우을 디스플레이 JPanel (this)에 호출해야합니다.
  • 카드를 페인트하면 JLabels로 간주하고 간단히 ImageIcon을 교체하면 가장 쉽게 카드를 뒤집을 수 있습니다.
  • 주요 문제는 프로그램의 잘못된 동작입니다. 나는 당신의 코드에 대한 간단한 개요를 보지 못했고 디버거 또는 println 문을 사용하여 문제를 격리하려고 시도했다.
+0

문제점이 무엇인지 알아 냈습니다. JButtons의 전체 2d 배열을 수용하는 보이지 않는 JPanel 패널이 있습니다. 버튼에는 자체 청취자가 있으므로 누군가가 버튼을 클릭 할 때마다 MouseClicker의 X 및 Y가 자신의 다른 패널 전체로 간주되기 때문에 if 문이 올바른 것으로 즉시 입증됩니다. 너는 나를 올바른 방향의 동료로 확실히 가리켰다. 건배! – Dusquad

+0

@Dusquad : 다행스럽게도 올바른 방향으로 가고 있습니다! –