ZBLOG

import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; import jav...

下面是修改后的代码,实现了对前两次点击的图片进行相同与不同的判断,并计算点击次数和游戏时长(秒):

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class GuessImageGame extends JFrame implements ActionListener {
    private ArrayList<String> images;
    private ArrayList<JLabel> labels;
    private int firstClickIndex = -1;
    private int secondClickIndex = -1;
    private int clickCount = 0;

    // 游戏开始时间
    private long startTime;

    public GuessImageGame() {
        setTitle("猜图游戏");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(4, 4));

        // 加载图片列表
        loadImages();

        // 随机排列图片位置
        Collections.shuffle(images);

        // 创建图片框
        labels = new ArrayList<>();
        for (int i = 0; i < 16; i++) {
            JLabel label = new JLabel();
            label.setPreferredSize(new Dimension(100, 100));
            label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            label.setOpaque(true);
            label.setBackground(Color.WHITE);
            label.addMouseListener(new ClickListener(i));
            add(label);
            labels.add(label);
        }

        pack();
        setLocationRelativeTo(null);
    }

    private void loadImages() {
        images = new ArrayList<>(Arrays.asList(
                "png-0201.png", "png-0202.png",
                "png-0203.png", "png-0204.png",
                "png-0205.png", "png-0206.png",
                "png-0207.png", "png-0208.png"
        ));
        images.addAll(images);
    }

    private void startNewGame() {
        firstClickIndex = -1;
        secondClickIndex = -1;
        clickCount = 0;
        loadImages();
        Collections.shuffle(images);

        for (JLabel label : labels) {
            label.setIcon(null);
            label.setBackground(Color.WHITE);
            label.putClientProperty("imagePath", null);
        }

        startTime = System.currentTimeMillis(); // 记录游戏开始时间
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if ("新游戏".equals(e.getActionCommand())) {
            startNewGame();
        }
    }

    private class ClickListener extends MouseAdapter {
        private int index;

        public ClickListener(int index) {
            this.index = index;
        }

		@Override
		public void mouseClicked(MouseEvent e) {
			JLabel currentLabel = labels.get(index);

			// 已经翻开的图片框,无响应
			if (currentLabel.getIcon() != null)
				return;

			clickCount++;

			// 第一次点击
			if (clickCount % 2 == 1) {
				firstClickIndex = index;
				ImageIcon imageIcon = new ImageIcon("imgs/" + images.get(index));
				currentLabel.setIcon(imageIcon);
				currentLabel.setBackground(Color.GRAY);
				currentLabel.putClientProperty("imagePath", images.get(index));
				
				if (clickCount == 1)
					startTime = System.currentTimeMillis(); // 第一次点击时记录游戏开始时间
			}

			// 第二次点击
			else if (clickCount % 2 == 0) {
				secondClickIndex = index;
				ImageIcon imageIcon = new ImageIcon("imgs/" + images.get(index));
				currentLabel.setIcon(imageIcon);

				// 图片相同,则保持显示状态,背景色设置为绿色
				if (images.get(firstClickIndex).equals(images.get(secondClickIndex))) {
					labels.get(firstClickIndex).setBackground(Color.GREEN);
					currentLabel.setBackground(Color.GREEN);
					
					// 判断是否所有图片都已经被翻开
					boolean allImagesOpened = true;
					for (JLabel label : labels) {
						if (label.getIcon() == null) {
							allImagesOpened = false;
							break;
						}
					}
					
					if (allImagesOpened) {
						long endTime = System.currentTimeMillis();
						long gameTimeSeconds = (endTime - startTime) / 1000; // 计算游戏时长(秒)
						
						JOptionPane.showMessageDialog(GuessImageGame.this, "游戏结束!\n点击次数:" + clickCount + "\n游戏时长:" + gameTimeSeconds + "秒");
					}
				}

				// 图片不同,则显示为空白,背景色设置为白色
				else {
					SwingUtilities.invokeLater(() -> {
						try {
							Thread.sleep(1000);
						} catch (InterruptedException ex) {
							ex.printStackTrace();
						}

						labels.get(firstClickIndex).setIcon(null);
						labels.get(secondClickIndex).setIcon(null);

						labels.get(firstClickIndex).setBackground(Color.WHITE);
						labels.get(secondClickIndex).setBackground(Color.WHITE);
					});
				}
			}
		}
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GuessImageGame game = new GuessImageGame();
            JMenuBar menuBar = new JMenuBar();
            JMenu menu = new JMenu("游戏");
            JMenuItem newGameMenuItem = new JMenuItem("新游戏");
            newGameMenuItem.addActionListener(game);
            menu.add(newGameMenuItem);
            menuBar.add(menu);

            game.setJMenuBar(menuBar);
            game.setVisible(true);
        });
    }
}

修改后的代码中,在所有图片都被翻开时,会弹出一个提示框显示点击次数和游戏时长(以秒为单位)。同时在第一次点击时记录游戏开始时间,并在所有图片都被翻开时计算游戏时长。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:http://sdn.0voice.com/?id=2660

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?