SlideShare a Scribd company logo
THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE |
Advanced Programming Lab Notes
Matching Game In Java
1 RESOURCES
• Package java.awt (Container, GridLayout, event package)
o http://docs.oracle.com/javase/8/docs/api/java/awt/package-frame.html
• Package javax.swing (window components and also Timer class)
o http://docs.oracle.com/javase/8/docs/api/javax/swing/package-frame.html
• Package java.util (Vector, Random)
o https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
2 LAB SESSION
2.1 CREATE A NEW PROJECT
• Select File->New->Java Project
• “Under Create a Java Project”
dialog box, for the Project Name
field, type in matchingGame as
project name
2.2 CREATE A CARD CLASS
• Under the “src/model”
package, create Card class
• Add the code snippet shown below to the Card class.
package model;
THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE |
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.Icon;
import javax.swing.JLabel;
import controller.cardController;
public class Card extends JLabel implements MouseListener{
// data fields
Icon faceIcon;
Icon backIcon;
//card is initially face down
boolean faceUp = false;
//card number
int num;
//half the dimensions of the back face icon
int iconWidthHalf, iconHeightHalf;
boolean mousePressedOnMe = false;
cardController controller;
/**
* Constructor
* @param face face of the card, two cards have the same face
* @param back back of the card
* @param num number corresponding to the face icon
*/
public Card(cardController controller, Icon face, Icon back, int num){
super(back); //initially all cards face down
this.controller=controller;
this.faceIcon=face;
this.backIcon=back;
this.num=num;
//catch mouse clicks
this.addMouseListener(this);
//(face or back) dimensions for mouse click testing
this.iconHeightHalf=back.getIconHeight()/2;
this.iconWidthHalf=face.getIconWidth()/2;
}
public int getNum(){return num;}//return the number of the card
/**
* Check the coordinates for mouse click
* @param x
* @param y
* @return
*/
private boolean overIcon(int x, int y){
int distX=Math.abs(x-(this.getWidth()/2));
int distY=Math.abs(y-(this.getHeight()/2));
//outside
if (distX>this.iconWidthHalf||distY>this.iconHeightHalf)
return false;
//inside
return true;
}
/**
THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE |
* turn face up
*/
public void turnUp(){
if (this.faceUp) return;
//this.faceUp=true; controller result checked in here
this.faceUp=this.controller.turnUp(this);
if(this.faceUp) this.setIcon(this.faceIcon);
}
public void turnDown(){
if (!this.faceUp)return;
this.setIcon(this.backIcon);
this.faceUp=false; //card is now down
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
if (overIcon(arg0.getX(), arg0.getY())) this.turnUp();
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
this.mousePressedOnMe=false;
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
if (overIcon(arg0.getX(),arg0.getY()))this.mousePressedOnMe=true;
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
if (this.mousePressedOnMe){
this.mousePressedOnMe=false;
this.mouseClicked(arg0);
}
}
}
2.3 MATCHINGGAME CLASS
• We need to create matchıngGame class to create main window.
• Create new class called matchıngGame under the “src/view” package.
package view;
THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE |
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import controller.cardController;
import model.Card;
public class matchingGame implements ActionListener{
//data fields
private JFrame mainFrame; //main window
private Container mainContentPane;//card holder
private ImageIcon cardIcon[]; //0-7 front side of the card; 8 back side
private static void newMenuItem(String text, JMenu menu, ActionListener listener){
JMenuItem newItem=new JMenuItem(text);
newItem.setActionCommand(text);
newItem.addActionListener(listener);
menu.add(newItem);
}
/**
* Default constructor for the game.
* Makes main windows and allocate the card and images
*/
public matchingGame(){
//main window
this.mainFrame=new JFrame("Matching Game");
this.mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.mainFrame.setSize(400, 500);
this.mainContentPane=this.mainFrame.getContentPane();
this.mainContentPane.setLayout(new
BoxLayout(this.mainContentPane,BoxLayout.PAGE_AXIS));
//Menu Bar
JMenuBar menuBar=new JMenuBar();
this.mainFrame.setJMenuBar(menuBar);
//Game Menu
JMenu gameMenu=new JMenu("Game");
menuBar.add(gameMenu);
newMenuItem("New Game", gameMenu,this);
newMenuItem("Exit",gameMenu,this);
//About Menu
JMenu aboutMenu=new JMenu("About");
menuBar.add(aboutMenu);
newMenuItem("Help etc.", aboutMenu,this);//we need to create generic
//newMenuItem
newMenuItem("About",aboutMenu,this);
THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE |
menuBar.add(aboutMenu);
// we need to load cards
this.cardIcon=loadCardIcons();
}
private ImageIcon[] loadCardIcons(){
// first we need to create resources for the icons
ImageIcon icon[]=new ImageIcon[9];
for (int i=0; i<9;i++){
String fileName="images/default/card"+i+".jpg";
icon[i]=new ImageIcon(fileName);
}
return icon;
}
public JPanel makeCards(){
JPanel panel=new JPanel(new GridLayout(4,4));
//all card have same back side (down)
ImageIcon backIcon=this.cardIcon[8]; //which is the back side
cardController controller=new cardController();
int cardsToAdd[]=new int[16];
for (int i=0;i<8;i++){
cardsToAdd[2*i]=i;
cardsToAdd[2*i+1]=i;
}
//we need to randomize them later
randomizeCardArray(cardsToAdd);
//we need to make card object
for (int i=0;i<cardsToAdd.length;i++){
int num=cardsToAdd[i];
Card newCard=new Card(controller, this.cardIcon[num], backIcon, num);
panel.add(newCard);
}
return panel;
}
private void randomizeCardArray(int[] t) {
// TODO Auto-generated method stub
Random randomizer=new Random();
//
for(int i=0;i<t.length;i++){
int d=randomizer.nextInt(t.length);
//swap
int s=t[d];
t[d]=t[i];
t[i]=s;
}
//so we need to controller that control the card behaviors
}
public void newGame(){
this.mainContentPane.removeAll();
//make a new card set visible
this.mainContentPane.add(makeCards());
//show main window
THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE |
this.mainFrame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getActionCommand().equals("New Game")) newGame();
if (e.getActionCommand().equals("Exit")) System.exit(0);
}
}
2.4 MAIN CLASS
• We need to add Main class for test the what we’ve done.
• First we need to create Main class as a new class under the “src” package
import view.matchingGame;
public class Main {
public static void main (String[] argv){
matchingGame instance=new matchingGame();
instance.newGame();
}
}
2.5 CARDCONTROLLER CLASS
• Create the cardController class under the “src/controller”.
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import model.Card;
import java.util.Vector;
public class cardController implements ActionListener{
//data fields
private Vector turnedCards;
private Timer turnDownTimer;
private final int turnDownDelay=2000;
public cardController(){
this.turnedCards=new Vector(2);
this.turnDownTimer=new Timer(this.turnDownDelay, this);
this.turnDownTimer.setRepeats(false);
}
private boolean doAddCard(Card card){
THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE |
this.turnedCards.add(card);
if (this.turnedCards.size()==2){
Card otherCard=(Card)this.turnedCards.get(0);
if(otherCard.getNum()==card.getNum())
this.turnedCards.clear();
else this.turnDownTimer.start();
}
return true;
}
public boolean turnUp(Card card){
if (this.turnedCards.size()<2)return doAddCard(card);
return false;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
for (int i=0;i< this.turnedCards.size();i++){
Card card=(Card)this.turnedCards.get(i);
card.turnDown();
}
this.turnedCards.clear();
// we need to add this controller to the Card class and also we need to use
// methods in the view class
}
}
2.6 HOMEWORKS
1. Add window components (JTextField, JLabel etc.) to count and show the turn attempts.
2. Make changes in menubar to select different card pictures from menu called "Card Type".
3. Card type menu has submenu item called “Cars”, “Flowers” etc. User can select the different card style to play
the game.
Have fun.
THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE |
2.7 FILE STRUCTURES
3 CONTACT
Dr. Celal Murat KANDEMİR
Eskisehir Osmangazi University
Faculty of Education
kandemir@ogu.edu.tr
twitter.com/cmkandemir

More Related Content

DOCX
Deads Star
DOCX
Valedictory Address - Mapua September 3, 2015
PDF
Bouncing Ball Exercise
PPTX
The Rubaiyat of Omar Khayyam (Complete Analysis)
PPTX
The Cat in the Hat by Dr. Seuss
PDF
Reading Eggs - Turtle, Wombat poems
DOCX
PPTX
Q2 l2 the centipede
Deads Star
Valedictory Address - Mapua September 3, 2015
Bouncing Ball Exercise
The Rubaiyat of Omar Khayyam (Complete Analysis)
The Cat in the Hat by Dr. Seuss
Reading Eggs - Turtle, Wombat poems
Q2 l2 the centipede

What's hot (12)

ZIP
A rose for emily plot
PPTX
Intro to poetry
PDF
Tao Te Ching
PPTX
Is it the kingfisher?
PPT
Transformed By Trouble
PPTX
Lord Randall
PPT
Rapunzel powerpoint
PPTX
The Magnificence (An Analysis)
PPTX
May day eve 21st literature project
DOCX
PPTX
Prince bantugan
PPTX
Orpheus and eurydice
A rose for emily plot
Intro to poetry
Tao Te Ching
Is it the kingfisher?
Transformed By Trouble
Lord Randall
Rapunzel powerpoint
The Magnificence (An Analysis)
May day eve 21st literature project
Prince bantugan
Orpheus and eurydice
Ad

Viewers also liked (15)

PDF
İnternet Tabanlı Programlama Uygulama Notları
PDF
PHP ve MySQL Bağlantısı - Temel İşlemler
PDF
Canvas Öğrenme Yönetim Sistemi Kullanım Kılavuzu Bölüm 2
PDF
Kod Akış Kontrolü - Döngüler, Fonksiyonlar
PDF
openCV and Java - Face Detection
PDF
PHP Temelleri
PDF
JDK and Eclipse Installation and Configuration
PDF
Chapter 6 - Introduction to 8085 Instructions
PDF
Chapter 7 - Programming Techniques with Additional Instructions
PDF
impress.js Framework
PDF
Web Sitesi Geliştirme Adımları
PDF
Threads and Game Programming In Java
PDF
CSS Uygulamaları 1
PDF
Canvas Öğrenme Yönetim Sistemi Kullanım Kılavuzu Bölüm 1
PDF
CSS - Sunum Bileşenleri
İnternet Tabanlı Programlama Uygulama Notları
PHP ve MySQL Bağlantısı - Temel İşlemler
Canvas Öğrenme Yönetim Sistemi Kullanım Kılavuzu Bölüm 2
Kod Akış Kontrolü - Döngüler, Fonksiyonlar
openCV and Java - Face Detection
PHP Temelleri
JDK and Eclipse Installation and Configuration
Chapter 6 - Introduction to 8085 Instructions
Chapter 7 - Programming Techniques with Additional Instructions
impress.js Framework
Web Sitesi Geliştirme Adımları
Threads and Game Programming In Java
CSS Uygulamaları 1
Canvas Öğrenme Yönetim Sistemi Kullanım Kılavuzu Bölüm 1
CSS - Sunum Bileşenleri
Ad

Similar to Matching Game In Java (20)

PDF
Please help!!I wanted to know how to add a high score to this prog.pdf
PDF
This is Java,I am currently stumped on how to add a scoreboard for.pdf
PPT
PDF
Android Best Practices
PDF
Secrets of JavaScript Libraries
TXT
Maze
PDF
Ten useful JavaScript tips & best practices
PPTX
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
PPTX
Async task, threads, pools, and executors oh my!
PDF
I wanted to change the cloudsrectangles into an actuall image it do.pdf
PDF
The 2016 Android Developer Toolbox [MOBILIZATION]
KEY
Android workshop
PDF
Unittests für Dummies
TXT
Settings
PPT
Dojo and Adobe AIR
DOCX
DAOFactory.javaDAOFactory.javapublicclassDAOFactory{ this .docx
PDF
A More Flash Like Web?
PDF
Introduction to CQRS and Event Sourcing
PDF
PPTX
Androidaop 170105090257
Please help!!I wanted to know how to add a high score to this prog.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdf
Android Best Practices
Secrets of JavaScript Libraries
Maze
Ten useful JavaScript tips & best practices
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Async task, threads, pools, and executors oh my!
I wanted to change the cloudsrectangles into an actuall image it do.pdf
The 2016 Android Developer Toolbox [MOBILIZATION]
Android workshop
Unittests für Dummies
Settings
Dojo and Adobe AIR
DAOFactory.javaDAOFactory.javapublicclassDAOFactory{ this .docx
A More Flash Like Web?
Introduction to CQRS and Event Sourcing
Androidaop 170105090257

More from cmkandemir (10)

PDF
Temel HTML Etiketleri ve Kullanım Örnekleri
PDF
Yapay Zeka Nedir?
PDF
Zekayı Anlamak
PDF
PHP - Kullanıcı Girişlerinin İşlenmesi
PDF
Chapter 2-8085 Microprocessor Architecture and Microcomputer Systems
PDF
Chapter 1-Microprocessors, Microcomputers, and Assembly Language
PDF
CSS - Genel Bakış
PDF
Temel HTML Etiketleri - Tablo, Form
PDF
Temel HTML Etiketleri - Text, Image, Link, List, Image
PDF
Vaadin JPAContainer
Temel HTML Etiketleri ve Kullanım Örnekleri
Yapay Zeka Nedir?
Zekayı Anlamak
PHP - Kullanıcı Girişlerinin İşlenmesi
Chapter 2-8085 Microprocessor Architecture and Microcomputer Systems
Chapter 1-Microprocessors, Microcomputers, and Assembly Language
CSS - Genel Bakış
Temel HTML Etiketleri - Tablo, Form
Temel HTML Etiketleri - Text, Image, Link, List, Image
Vaadin JPAContainer

Recently uploaded (20)

PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
master seminar digital applications in india
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
RMMM.pdf make it easy to upload and study
PPTX
Pharma ospi slides which help in ospi learning
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Anesthesia in Laparoscopic Surgery in India
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
master seminar digital applications in india
O7-L3 Supply Chain Operations - ICLT Program
RMMM.pdf make it easy to upload and study
Pharma ospi slides which help in ospi learning
O5-L3 Freight Transport Ops (International) V1.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
FourierSeries-QuestionsWithAnswers(Part-A).pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Renaissance Architecture: A Journey from Faith to Humanism
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
01-Introduction-to-Information-Management.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Microbial diseases, their pathogenesis and prophylaxis
Abdominal Access Techniques with Prof. Dr. R K Mishra
Final Presentation General Medicine 03-08-2024.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Anesthesia in Laparoscopic Surgery in India

Matching Game In Java

  • 1. THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE | Advanced Programming Lab Notes Matching Game In Java 1 RESOURCES • Package java.awt (Container, GridLayout, event package) o http://docs.oracle.com/javase/8/docs/api/java/awt/package-frame.html • Package javax.swing (window components and also Timer class) o http://docs.oracle.com/javase/8/docs/api/javax/swing/package-frame.html • Package java.util (Vector, Random) o https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html 2 LAB SESSION 2.1 CREATE A NEW PROJECT • Select File->New->Java Project • “Under Create a Java Project” dialog box, for the Project Name field, type in matchingGame as project name 2.2 CREATE A CARD CLASS • Under the “src/model” package, create Card class • Add the code snippet shown below to the Card class. package model;
  • 2. THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE | import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.Icon; import javax.swing.JLabel; import controller.cardController; public class Card extends JLabel implements MouseListener{ // data fields Icon faceIcon; Icon backIcon; //card is initially face down boolean faceUp = false; //card number int num; //half the dimensions of the back face icon int iconWidthHalf, iconHeightHalf; boolean mousePressedOnMe = false; cardController controller; /** * Constructor * @param face face of the card, two cards have the same face * @param back back of the card * @param num number corresponding to the face icon */ public Card(cardController controller, Icon face, Icon back, int num){ super(back); //initially all cards face down this.controller=controller; this.faceIcon=face; this.backIcon=back; this.num=num; //catch mouse clicks this.addMouseListener(this); //(face or back) dimensions for mouse click testing this.iconHeightHalf=back.getIconHeight()/2; this.iconWidthHalf=face.getIconWidth()/2; } public int getNum(){return num;}//return the number of the card /** * Check the coordinates for mouse click * @param x * @param y * @return */ private boolean overIcon(int x, int y){ int distX=Math.abs(x-(this.getWidth()/2)); int distY=Math.abs(y-(this.getHeight()/2)); //outside if (distX>this.iconWidthHalf||distY>this.iconHeightHalf) return false; //inside return true; } /**
  • 3. THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE | * turn face up */ public void turnUp(){ if (this.faceUp) return; //this.faceUp=true; controller result checked in here this.faceUp=this.controller.turnUp(this); if(this.faceUp) this.setIcon(this.faceIcon); } public void turnDown(){ if (!this.faceUp)return; this.setIcon(this.backIcon); this.faceUp=false; //card is now down } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub if (overIcon(arg0.getX(), arg0.getY())) this.turnUp(); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub this.mousePressedOnMe=false; } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub if (overIcon(arg0.getX(),arg0.getY()))this.mousePressedOnMe=true; } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub if (this.mousePressedOnMe){ this.mousePressedOnMe=false; this.mouseClicked(arg0); } } } 2.3 MATCHINGGAME CLASS • We need to create matchıngGame class to create main window. • Create new class called matchıngGame under the “src/view” package. package view;
  • 4. THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE | import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import controller.cardController; import model.Card; public class matchingGame implements ActionListener{ //data fields private JFrame mainFrame; //main window private Container mainContentPane;//card holder private ImageIcon cardIcon[]; //0-7 front side of the card; 8 back side private static void newMenuItem(String text, JMenu menu, ActionListener listener){ JMenuItem newItem=new JMenuItem(text); newItem.setActionCommand(text); newItem.addActionListener(listener); menu.add(newItem); } /** * Default constructor for the game. * Makes main windows and allocate the card and images */ public matchingGame(){ //main window this.mainFrame=new JFrame("Matching Game"); this.mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.mainFrame.setSize(400, 500); this.mainContentPane=this.mainFrame.getContentPane(); this.mainContentPane.setLayout(new BoxLayout(this.mainContentPane,BoxLayout.PAGE_AXIS)); //Menu Bar JMenuBar menuBar=new JMenuBar(); this.mainFrame.setJMenuBar(menuBar); //Game Menu JMenu gameMenu=new JMenu("Game"); menuBar.add(gameMenu); newMenuItem("New Game", gameMenu,this); newMenuItem("Exit",gameMenu,this); //About Menu JMenu aboutMenu=new JMenu("About"); menuBar.add(aboutMenu); newMenuItem("Help etc.", aboutMenu,this);//we need to create generic //newMenuItem newMenuItem("About",aboutMenu,this);
  • 5. THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE | menuBar.add(aboutMenu); // we need to load cards this.cardIcon=loadCardIcons(); } private ImageIcon[] loadCardIcons(){ // first we need to create resources for the icons ImageIcon icon[]=new ImageIcon[9]; for (int i=0; i<9;i++){ String fileName="images/default/card"+i+".jpg"; icon[i]=new ImageIcon(fileName); } return icon; } public JPanel makeCards(){ JPanel panel=new JPanel(new GridLayout(4,4)); //all card have same back side (down) ImageIcon backIcon=this.cardIcon[8]; //which is the back side cardController controller=new cardController(); int cardsToAdd[]=new int[16]; for (int i=0;i<8;i++){ cardsToAdd[2*i]=i; cardsToAdd[2*i+1]=i; } //we need to randomize them later randomizeCardArray(cardsToAdd); //we need to make card object for (int i=0;i<cardsToAdd.length;i++){ int num=cardsToAdd[i]; Card newCard=new Card(controller, this.cardIcon[num], backIcon, num); panel.add(newCard); } return panel; } private void randomizeCardArray(int[] t) { // TODO Auto-generated method stub Random randomizer=new Random(); // for(int i=0;i<t.length;i++){ int d=randomizer.nextInt(t.length); //swap int s=t[d]; t[d]=t[i]; t[i]=s; } //so we need to controller that control the card behaviors } public void newGame(){ this.mainContentPane.removeAll(); //make a new card set visible this.mainContentPane.add(makeCards()); //show main window
  • 6. THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE | this.mainFrame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getActionCommand().equals("New Game")) newGame(); if (e.getActionCommand().equals("Exit")) System.exit(0); } } 2.4 MAIN CLASS • We need to add Main class for test the what we’ve done. • First we need to create Main class as a new class under the “src” package import view.matchingGame; public class Main { public static void main (String[] argv){ matchingGame instance=new matchingGame(); instance.newGame(); } } 2.5 CARDCONTROLLER CLASS • Create the cardController class under the “src/controller”. package controller; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; import model.Card; import java.util.Vector; public class cardController implements ActionListener{ //data fields private Vector turnedCards; private Timer turnDownTimer; private final int turnDownDelay=2000; public cardController(){ this.turnedCards=new Vector(2); this.turnDownTimer=new Timer(this.turnDownDelay, this); this.turnDownTimer.setRepeats(false); } private boolean doAddCard(Card card){
  • 7. THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE | this.turnedCards.add(card); if (this.turnedCards.size()==2){ Card otherCard=(Card)this.turnedCards.get(0); if(otherCard.getNum()==card.getNum()) this.turnedCards.clear(); else this.turnDownTimer.start(); } return true; } public boolean turnUp(Card card){ if (this.turnedCards.size()<2)return doAddCard(card); return false; } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub for (int i=0;i< this.turnedCards.size();i++){ Card card=(Card)this.turnedCards.get(i); card.turnDown(); } this.turnedCards.clear(); // we need to add this controller to the Card class and also we need to use // methods in the view class } } 2.6 HOMEWORKS 1. Add window components (JTextField, JLabel etc.) to count and show the turn attempts. 2. Make changes in menubar to select different card pictures from menu called "Card Type". 3. Card type menu has submenu item called “Cars”, “Flowers” etc. User can select the different card style to play the game. Have fun.
  • 8. THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE | 2.7 FILE STRUCTURES 3 CONTACT Dr. Celal Murat KANDEMİR Eskisehir Osmangazi University Faculty of Education kandemir@ogu.edu.tr twitter.com/cmkandemir