JAVA 프로그래밍

문제

16장의 카드에서 같은 색을 가진 카드 짝을 찾는 문제입니다 실행순서를 클릭하세요 
 

프로그램 코드

E001	// 이벤트 대기중
E002	// 첫번째 카드 (2,2) 선택
E003	// 두번째 카드 (3,2) 선택
E004	// 세번째 카드 (1,1) 선택
E005	// 네번째 카드 (2,4) 선택
E006	// 다섯번째 카드 (2,1) 선택

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

	import java.awt.*;
	import java.awt.event.*;
	import javax.swing.*;
		
	public class CardMatchingPanel extends JPanel {
		protected Card card1, card2;

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

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








 
실행 순서