Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
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

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