JAVA 프로그래밍

문제

16장의 카드에서 같은 색을 가진 카드 짝을 찾는 문제입니다 이를 해결하는 다음 프로그램을 해석하세요 
 

알고리즘

 카드 클래스 
   카드 선택시 카드 앞면(색) 제시
   카드 해제시 카드 뒤면(흰색) 제시

카드 맞추기 보드 클래스
   16장의 카드를 보드에 배치
   카드 클릭
      기존 두 장의 카드 색이 같으면 선택 유지하고, 다르면 선택 해제
         새로운 카드 두 장을 선택할 수 있도록 준비
      첫번째 카드 선택
      두번째 카드 선택


  카드 색 배치

 

  클래스 다이어그램
 

  초기화 과정

 

  버튼 클릭시 처리 과정

 
 

프로그램 코드

E001	// 이벤트 대기중
E002	// 첫번째 카드 (2,2) 선택
E003	// 두번째 카드 (3,2) 선택
E004	// 세번째 카드 (1,1) 선택
E005	// 네번째 카드 (2,4) 선택
E006	// 다섯번째 카드 (2,1) 선택
	 
	// 파일명 : ./Chapter13/CardMatchingGameMain.java
	import javax.swing.*;
		 
	public class CardMatchingGameMain
	{
1		public static void main(String [] args)
		{
			final int[][] color = { { 0, 1, 2, 7 },
			                        { 3, 5, 6, 0 },
			                        { 2, 4, 6, 3 },
			                        { 4, 5, 1, 7 } };
	 
			// 틀에 판을 끼우고 실행 준비 완료
			JFrame frame = new JFrame ( "같은 색깔 찾기" );
2			frame.getContentPane().add( new CardMatchingPanel( color ) );
			frame.pack();
			frame.setVisible(true);
			frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
3		}
	}
	 
	// 파일명 : ./Chapter13/CardMatchingPanel.java
	import java.awt.*;
	import java.awt.event.*;
	import javax.swing.*;
		 
	// 카드 맞추기 보드 클래스  
	public class CardMatchingPanel extends JPanel {
		protected Card card1, card2;
	 
		// 16장의 카드를 보드에 배치     
P1b		public CardMatchingPanel( int[][] color ) {
			card1 = null;
			card2 = null;
			setLayout( new GridLayout( color.length, color[0].length ) );
			setPreferredSize( new Dimension( 400, 400 ) );
			setFocusable( true );
			requestFocus();
			 
			Card[][] card = new Card[color.length][color[0].length];
			ClickListener click = new ClickListener();
			Color[] palette = { Color.pink, Color.red, Color.orange, Color.yellow, Color.green, Color.blue, Color.cyan, Color.gray };
			for( int y=0; y < card.length; y++ ){
				for( int x=0; x < card[0].length; x++ ){
P11					card[y][x] =
P12					             new Card( palette[ color[y][x] ] );
					card[y][x].addActionListener( click );
					add( card[y][x] );
				}
			}
P1e		}
	 
		// 카드 클릭      
		private class ClickListener implements ActionListener {
L1b			public void actionPerformed( ActionEvent event ) {
				// 기존 두 장의 카드 색이 같으면 선택 유지하고, 다르면 선택 해제 
				if ( ( card1 != null ) && ( card2 != null ) ) {
					if ( !card1.color().equals( card2.color() ) ) {
L11						card1.unselected();
L12						card2.unselected();
					}
	 
					// 새로운 카드 두 장을 선택할 수 있도록 준비      
					card1 = null;
					card2 = null;
				}
	 
				// 첫번째 카드 선택  
				if ( card1 == null  ) {
					card1 = (Card)event.getSource();
L13					card1.selected();
				}
				// 두번째 카드 선택  
				else if ( card2 == null  ) {
					card2 = (Card)event.getSource();
L14					card2.selected();
				}
L1e			}
		}
	}
	 
	// 파일명 : ./Chapter13/Card.java
	import java.awt.*;
	import javax.swing.*;
		 
	// 카드 클래스 
	public class Card extends JButton {
		private Color color;
		 
		// 카드 초기화
C1b		public Card( Color color ) {
			super();
			this.color = color;
			this.setBackground( Color.white );
C1e		}
		 
		// 카드 선택시 카드 앞면(색) 제시    
C2b		public void selected() {
			this.setEnabled( false );
			this.setBackground( this.color );
C2e		}
		 
		// 카드 해제시 카드 뒤면(흰색) 제시    
C3b		public void unselected() {
			this.setEnabled( true );
			this.setBackground( Color.white );
C3e		}
		 
		// 카드 색
		public Color color() {
			return this.color;
		}
	}

실행 순서

 
 					※ 실행순서 및 메모리상태는 A키(이전) 및 D키(다음)를 눌러도 확인할 수 있습니다