🔒 Closed Memory Game for Java (GUI) - Beginner Friendly Code

Status
Not open for further replies.

jisoo69

Forum Guru

Share ko lang programming project namin noon AY: 2016-2017

SIMPLE MEMORY GAME

for Java Swing
basic lang yung main code na naka method, even beginners can understand and learn from this:

02.PNG
03.PNG
05.PNG

COPY PASTE THIS CODE DIRECTLY TO YOUR JAVA IDE and RUN:


[CODE lang="java" title="Java Code GUI"]


/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mem;

import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.BevelBorder;

/**
*
* @author user
*/
public class buttonarray extends javax.swing.JFrame {

JButton[] buttons;
int[] array;
int count = 0;
int mem = 0;
JButton membt = null;
final int[] lev = {10, 50, 150, 500, 1000};

int fin = 0;
int click = 0;
private boolean reset = false;
int gamelevel = 0;
int gridsize;

/**
* Creates new form buttonarray
*/
public buttonarray() {
initComponents();
setLocationRelativeTo(null);
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

rootpanel = new javax.swing.JPanel();
levelpanel = new javax.swing.JPanel();
jSlider1 = new javax.swing.JSlider();
jButton1 = new javax.swing.JButton();
level_txt = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
gamepanel = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
score1 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMaximumSize(new java.awt.Dimension(400, 400));
setMinimumSize(new java.awt.Dimension(400, 400));
setPreferredSize(new java.awt.Dimension(400, 400));
setResizable(false);
getContentPane().setLayout(new java.awt.CardLayout());

rootpanel.setLayout(new java.awt.CardLayout());

levelpanel.setBackground(new java.awt.Color(255, 255, 255));
levelpanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jSlider1.setBackground(new java.awt.Color(255, 255, 255));
jSlider1.setMaximum(4);
jSlider1.setValue(0);
jSlider1.setFocusable(false);
jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSlider1StateChanged(evt);
}
});
levelpanel.add(jSlider1, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 220, -1, -1));

jButton1.setText("START");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
levelpanel.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 260, -1, -1));

level_txt.setFont(new java.awt.Font("Corbel", 1, 24)); // NOI18N
level_txt.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
level_txt.setText("1");
levelpanel.add(level_txt, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 160, 400, -1));

jLabel2.setFont(new java.awt.Font("Corbel", 1, 36)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("LEVEL");
levelpanel.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 120, 400, -1));

rootpanel.add(levelpanel, "card3");

gamepanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jPanel1.setLayout(new java.awt.GridLayout());
gamepanel.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, 320, 260));

score1.setFont(new java.awt.Font("Corbel", 1, 36)); // NOI18N
score1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
score1.setText("RESTART");
score1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
score1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
score1MouseClicked(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
score1MousePressed(evt);
}
});
score1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
score1KeyPressed(evt);
}
});
gamepanel.add(score1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 320, 400, 40));

rootpanel.add(gamepanel, "card4");

getContentPane().add(rootpanel, "card4");

pack();
}// </editor-fold>

private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
level_txt.setText("" + (jSlider1.getValue() + 1));
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
gamelevel = (jSlider1.getValue() + 1) * 2;
gridsize = gamelevel * gamelevel;
initArray();
initButtons();
switchPanel(rootpanel, gamepanel);
}

private void score1KeyPressed(java.awt.event.KeyEvent evt) {

}

private void score1MouseClicked(java.awt.event.MouseEvent evt) {
dispose();
new buttonarray().setVisible(true);
}

private void score1MousePressed(java.awt.event.MouseEvent evt) {
if (JOptionPane.showConfirmDialog(gamepanel, "Restart Game?", "", JOptionPane.YES_NO_OPTION) == 0) {
dispose();
new buttonarray().setVisible(true);
}

}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(buttonarray.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(buttonarray.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(buttonarray.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(buttonarray.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new buttonarray().setVisible(true);
}
});
}

private void initArray() {
Random rand = new Random();
array = new int[gridsize];

for (int i = 0; i < gridsize / 2; i++) {
array = (i + 1);
array[i + (gridsize / 2)] = (i + 1);
}

//System.out.println(Arrays.toString(array));
for (int i = 0; i < array.length; i++) {
int randomIndexToSwap = rand.nextInt(array.length);
int temp = array[randomIndexToSwap];
array[randomIndexToSwap] = array;
array = temp;
}

//System.out.println(Arrays.toString(array));
}

private void initButtons() {

buttons = new JButton[gridsize];
for (int i = 0; i < gridsize; i++) {
buttons = new JButton("");
final int j = i;
buttons.setBackground(new java.awt.Color(204, 204, 204));
buttons.setFont(new Font("Cooper Black", 1, 18));
buttons.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
buttons.setContentAreaFilled(false);
buttons.setFocusPainted(false);
buttons.setFocusable(false);
buttons.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
button_click(buttons[j], array[j]);
click++;
}
});
jPanel1.add(buttons);

}
jPanel1.setLayout(new GridLayout(gamelevel, gamelevel));
}

private void button_click(JButton button, int arrayVal) {
setButton(button, false, "" + arrayVal);

if (count == 0) {
if (reset) {
reset();
setButton(button, false, "" + arrayVal);
}
mem = arrayVal;
membt = button;
count = 1;
} else if (count == 1) {

count = 0;
if (mem == arrayVal) {
membt.setVisible(false);
button.setVisible(false);
fin++;
System.out.println(fin);
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(memory_game.class.getName()).log(Level.SEVERE, null, ex);
}
reset();
reset = false;
} else {
reset = true;
}
}

if (fin == gridsize / 2) {
int score = lev[jSlider1.getValue()] - 1 - click;
if (score < 0) {
System.out.println("SC: " + (0));
score1.setText("Your Score is: " + (0));
} else {
System.out.println("SC: " + (score));
score1.setText("Your Score is: " + (score));
}
//jPanel2.setVisible(false);

}

System.out.println(count);
}

private JButton setButton(JButton button, boolean visible, String title) {
button.setEnabled(visible);
button.setText(title);
return button;
}

private void reset() {
for (int i = 0; i < gridsize; i++) {
setButton(buttons, true, "");
}
}

void switchPanel(JPanel panel, JPanel addpane) {
panel.removeAll();
panel.add(addpane);
panel.repaint();
panel.revalidate();
}

// Variables declaration - do not modify
private javax.swing.JPanel gamepanel;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JSlider jSlider1;
private javax.swing.JLabel level_txt;
private javax.swing.JPanel levelpanel;
private javax.swing.JPanel rootpanel;
private javax.swing.JLabel score1;
// End of variables declaration

}




[/CODE]
 
Status
Not open for further replies.

About this Thread

  • 8
    Replies
  • 2K
    Views
  • 7
    Participants
Last reply from:
iyeah

Trending Topics

Online now

Members online
1,207
Guests online
2,080
Total visitors
3,287

Forum statistics

Threads
2,321,704
Posts
29,212,393
Members
1,177,060
Latest member
nanos0731
Back
Top