Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
7.7 kB
2
Indexable
Never
package com.mycompany.memorytest;

import javax.swing.*;
import javax.sound.sampled.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.io.File;
import java.io.IOException;

public class MemoryTestApp extends JFrame {

    private final JPanel testArea;
    private ArrayList<Integer> numbers;
    private final ArrayList<JLabel> numberLabels;
    private final Map<JLabel, Integer> labelNumberMap;
    private int currentNumberIndex;
    private final JLabel timeLabel;
    private final JLabel dateTimeLabel;
    private final javax.swing.Timer timer;
    private long startTime;
    private final int numberCount = 9;  // Default count 9

    public MemoryTestApp() {
        setTitle("Memory Test Application");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        testArea = new JPanel();
        testArea.setLayout(new GridLayout(10, 10, 2, 2)); // 10x10 grid with 2px gaps
        add(testArea, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton newTestButton = new JButton("New Test");
        newTestButton.addActionListener((ActionEvent e) -> {
            playSound("click.wav");
            startNewTest();
        });
        buttonPanel.add(newTestButton);

        JButton hintButton = new JButton("Hint");
        hintButton.addActionListener((var e) -> {
            playSound("click.wav");
            showHint();
        });
        buttonPanel.add(hintButton);

        add(buttonPanel, BorderLayout.SOUTH);

        timeLabel = new JLabel("Time: 0 seconds");
        dateTimeLabel = new JLabel();
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(timeLabel, BorderLayout.WEST);
        topPanel.add(dateTimeLabel, BorderLayout.EAST);
        add(topPanel, BorderLayout.NORTH);

        javax.swing.Timer dateTimeTimer = new javax.swing.Timer(1000, e -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dateTimeLabel.setText(sdf.format(new Date()));
        });
        dateTimeTimer.start();

        numbers = new ArrayList<>();
        numberLabels = new ArrayList<>();
        labelNumberMap = new HashMap<>();
        currentNumberIndex = 0;
        timer = new javax.swing.Timer(1000, e -> {
            long elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
            timeLabel.setText("Time: " + elapsedTime + " seconds");
        });
    }

    private void startNewTest() {
        numbers.clear();
        numberLabels.clear();
        labelNumberMap.clear();
        testArea.removeAll();
        currentNumberIndex = 0;

        // Default range 1-9
        int numberRange = 9;
        for (int i = 1; i <= numberRange; i++) {
            numbers.add(i);
        }
        Collections.shuffle(numbers);
        numbers = new ArrayList<>(numbers.subList(0, numberCount));

        JLabel[] allLabels = new JLabel[100];
        for (int i = 0; i < 100; i++) {
            JLabel emptyLabel = new JLabel();
            emptyLabel.setSize(50, 50);
            emptyLabel.setOpaque(true);
            emptyLabel.setBackground(Color.LIGHT_GRAY);
            emptyLabel.setHorizontalAlignment(SwingConstants.CENTER);
            emptyLabel.setVerticalAlignment(SwingConstants.CENTER);
            emptyLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            allLabels[i] = emptyLabel;
            testArea.add(emptyLabel);
        }

        Random random = new Random();
        for (int i = 0; i < numberCount; i++) {
            int randomIndex;
            do {
                randomIndex = random.nextInt(100);
            } while (labelNumberMap.containsKey(allLabels[randomIndex]));

            JLabel numberLabel = allLabels[randomIndex];
            numberLabel.setText(String.valueOf(numbers.get(i)));
            numberLabel.setBackground(Color.YELLOW);
            numberLabel.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    handleBlockClick(numberLabel);
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                    numberLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    numberLabel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                }
            });
            numberLabels.add(numberLabel);
            labelNumberMap.put(numberLabel, numbers.get(i));
        }

        startTime = System.currentTimeMillis();
        timer.start();
        testArea.repaint();
    }

    private void handleBlockClick(JLabel numberLabel) {
        if (numberLabel.isVisible()) {
            int clickedNumber = labelNumberMap.get(numberLabel);
            playSound("click.wav");
            if (clickedNumber == currentNumberIndex + 1) {
                currentNumberIndex++;
                if (clickedNumber == 1) {
                    for (JLabel label : numberLabels) {
                        if (label != numberLabel) {
                            label.setText("");
                        }
                    }
                }
                numberLabel.setVisible(false);
                if (currentNumberIndex == numberCount) {
                    timer.stop();
                    playSound("congrats.wav");
                    long elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
                    JOptionPane.showMessageDialog(null, "Congratulations! You've completed the test in " + elapsedTime + " seconds!");
                }
            } else {
                playSound("sad.wav");
                numberLabel.setBackground(Color.RED);
                JOptionPane.showMessageDialog(null, "Sorry! You pressed the wrong number. Try again.");
                startNewTest();
            }
        }
    }

    private void showHint() {
        if (currentNumberIndex < numberCount) {
            JLabel nextLabel = null;
            for (Map.Entry<JLabel, Integer> entry : labelNumberMap.entrySet()) {
                if (entry.getValue() == currentNumberIndex + 1) {
                    nextLabel = entry.getKey();
                    break;
                }
            }

            if (nextLabel != null) {
                final JLabel finalNextLabel = nextLabel;
                finalNextLabel.setText(labelNumberMap.get(finalNextLabel).toString());
                javax.swing.Timer t = new javax.swing.Timer(3000, (ActionEvent e1) -> finalNextLabel.setText(""));
                t.setRepeats(false);
                t.start();
            }
        }
    }

    private void playSound(String soundFileName) {
        try {
            File soundFile = new File(soundFileName);
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.start();
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MemoryTestApp app = new MemoryTestApp();
            app.setVisible(true);
        });
    }
}
Leave a Comment