2014-06-17 5 views
-1

저는 Java 초보자이며 프로젝트 용 게임을 제작 중입니다. Swing을 사용하여 MasterMind 버전을 만들고 있습니다.스윙을 사용하여 Java에서 MasterMind 만들기

이것은 내가 지금까지있어 무엇 :

package GUI; 

import java.awt.GridLayout; 
import java.awt.event.*; 
import javax.swing.*; 


public class GUIMasterMind implements ActionListener { 
JFrame frame; 
JPanel contentPane; 
JLabel label, prompt, show, blackPegs, whitePegs; 
JButton step, newGame; 
JTextField guessBox; 
private String[] args; 
int guess; 

public GUIMasterMind() { 

    //frame created 
    frame = new JFrame("MasterMind:"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    // content pane 
    contentPane = new JPanel();  
    contentPane.setLayout(new GridLayout(0, 2, 10, 5)); 
    contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); 


    prompt = new JLabel("Enter a guess: "); 
    contentPane.add(prompt); 

    guessBox = new JTextField(); 
    guessBox.addActionListener(this); 
    contentPane.add(guessBox); 

    newGame = new JButton("New Game"); 
    newGame.setActionCommand("New Game"); 
    newGame.addActionListener(this); 
    contentPane.add(newGame); 

    step = new JButton("Compare"); 
    step.setActionCommand("Compare"); 
    step.addActionListener(this); 
    contentPane.add(step); 

    show = new JLabel("Results"); 
    contentPane.add(show); 

    blackPegs = new JLabel("Black Pegs: "); 
    contentPane.add(blackPegs); 

    whitePegs = new JLabel("White Pegs: "); 
    contentPane.add(whitePegs); 

    frame.setContentPane(contentPane); 

    frame.pack(); 
    frame.setVisible(true); 


} 

public void actionPerformed(ActionEvent event){ 
    String eventName = event.getActionCommand(); 

    String g1 = guessBox.getText(); 

    if(eventName.equals("New Game")){ 
     GUIMasterMind.main(args); 
    } 
    else if(eventName.equals("Compare")){ 


     String[] guess = new String[4]; 

     for (int i = 0; i < guess.length; i++) { 
      guess[i] = g1.substring(i, i+1); 
      System.out.println(guess[i]); 
     } 

     MMCode MM = new MMCode(guess); 
     show.setText("This was your guess: "+ MM.toHTML()); 

     if(MM.compareTo() == 1){ 
      System.out.println("If you would like to start a new game press the button!"); 
     } 
     else if(MM.compareTo() == 0){ 
      prompt.setText("Guesses remaining: "); 
     } 
     else { 
      prompt.setText("Error"); 
     } 
     guessBox.setText(""); 
     System.out.println("done"); 
     } 
} 


public static void main(String[] args) { 
    javax.swing.SwingUtilities.invokeLater(new Runnable(){ 
     public void run(){ 
      GUIMasterMind game = new GUIMasterMind(); 
     } 
    }); 
} 
} 

현재 내 게임 실행 나는 사용자가 코드를 입력해야하고 그 코드가 컴퓨터의 자체 생성 된 코드와 비교 될 때. 그러나 내 문제는 actionPerformed() 메서드에 있습니다. 그 코드 세그먼트가 완전히 새로운 암호를 만들 필요없이 재실행 할 수 있기를 바랍니다. 나는 성공하기 위해 여러 가지 루프를 시도했다. 어떤 도움을 주시면 감사하겠습니다.

또한 흰색/검은 색 페그 코드를 무시할 수 있습니다. 나중에 해결할 것입니다. 난 그냥 내 프로그램이 올바르게 먼저 실행 싶습니다. 여기 다른 클래스가 있습니다. 이 클래스의 목적은 2 개의 배열, 추측과 비밀을 비교하는 것입니다. 그래서 추측을 필요로하지 않는 MMCode의 생성자를 변경하여

package GUI; 


public class MMCode { 
String[] guess = new String[4]; 
String[] secret = new String[4]; 
int num; 

public MMCode(String[] guessess){ 
    for (int i = 0; i < guess.length; i++) { 
     this.guess[i] = guessess[i]; 
    } 

    setSecret(); 

} 

public void setSecret(){ 
    for (int i = 0; i < secret.length; i++) { 
     num = ((int)(Math.random()*6+1)); 
     secret[i] = Integer.toString(num); 
    } 
} 

public String getSecret(){ 
    return ("The secret code is: "+secret[0]+secret[1]+secret[2]+secret[3]); 
} 

public void setGuess(){ 

} 

public String getGuess(){ 
    return ("Your guess is:  "+guess); 
} 

public int compareTo(){ 

    if(guess[0].equals(secret[0]) && guess[1].equals(secret[1]) && guess[2].equals(secret[2]) && guess[3].equals(secret[3])){ 
     System.out.println("Congratulations you've guessed the computer's code!"); 
     return 1; 
    } else if (!(guess[0].equals(secret[0]) && guess[1].equals(secret[1]) && guess[2].equals(secret[2]) && guess[3].equals(secret[3]))){ 
     return 0; 
    } 
    return -1; 
} 

public String toHTML(){ 
    String html = ""; 


    html += guess[0].toString(); 
    html += guess[1].toString(); 
    html += guess[2].toString(); 
    html += guess[3].toString(); 
    return html; 
} 

} 
+1

- 당신은'setSecret'에 대해 말을하는거야? 'MMCode'가 추측의 한 세트를 나타내는데, 그들이 추측을 할 때마다 "비밀"을 입력해야하는 것을 원하지 않는다면, 당신은 비밀 물건이'MMCode '에있는 것을 원하지 않을 것입니다. 다른 클래스로 이동하십시오. 두 가지 전혀 관련이없는 개념 ("추측"과 "암호")을 처리하는 클래스를 갖는 것은 어쨌든 열악한 디자인이므로 문제는 왜 가난한 지 보여주는 좋은 예입니다. – ajb

답변

2

시작 ...

public MMCode(){ 
    setSecret(); 
} 

은 ... 예를 들어, setGuess라는 새로운 방법을 추가

public void setGuess(String[] guessess){ 
    for (int i = 0; i < guess.length; i++) { 
     this.guess[i] = guessess[i]; 
    } 
} 

actionPeformed 메서드에서 MMCode MM = new MMCode(guess);을 가져 와서 인스턴스 변수로 만듭니다.

public class GUIMasterMind implements ActionListener { 
    //... 
    private MMCode mmCode; 
    //... 
    public GUIMasterMind() { 
     //... 
     mmCode = new MMCode(); 
     //... 

다음 actionPerformed 방법, 당신은 단순히 MMCode의 인스턴스를 갱신 할 필요가 ... 난 당신의 코드에있는 "암호"를 참조하지 않는

public void actionPerformed(ActionEvent event){ 
    //... 
    else if(eventName.equals("Compare")){ 
     String[] guess = new String[4]; 

     for (int i = 0; i < guess.length; i++) { 
      guess[i] = g1.substring(i, i+1); 
      System.out.println(guess[i]); 
     } 

     mmCode.setGuess(guess); 
     //... 
+0

응답 해 주셔서 감사합니다. 나는 당신의 아이디어에서 약간의 도움으로 나의 문제를 해결했습니다! 그러나 내 프로그램에서 한 구성 요소가 누락되었습니다. 추측이 이루어질 때마다 카운터가 감소하고 싶습니다. 플레이어는 자신이 할 수있는 추측 된 양을 가지고 있다는 것을 의미합니다. 현재 초보자 시도는 다음과 같습니다 : – user3750380

+0

그래서'actionPerformed'에서 어떤 종류의'counter '값을 증가시켜야합니다. 그러면 화면에서'JLabel'을 업데이트 할 수 있습니다. '카운터'가 허용 된 추측 횟수를 초과하면 게임 오버 ... – MadProgrammer