day01借助ai体验编程的快乐

昨天突发奇想,以前有一个很爱玩的小游戏2048,相信很多人都玩过。

然后自己想能不能做一个出来,正巧最近在学java,想到jdk自带的Gui也许能实现,但是自己对Gui编程确实不熟,于是借助chatgpt完成了实现。

import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.*;

public class Game2048demo extends JFrame {
    private JPanel gamePanel;
    private JLabel[][] gridLabels;
    private int[][] grid;
    private boolean gameOver;
    private static final int MAXSCORE;
    private int max;

    static {
        try {
            MAXSCORE = JdbcUtils.get2048maxScore();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Game2048demo() {
        setTitle("2048 Game");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setPreferredSize(new Dimension(800, 600));


        gamePanel = new JPanel(new GridLayout(4, 4));
        gridLabels = new JLabel[4][4];
        grid = new int[4][4];
        gameOver = false;

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                gridLabels[i][j] = new JLabel("", SwingConstants.CENTER);
                gridLabels[i][j].setFont(new Font("Arial", Font.BOLD, 50));
                gridLabels[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK));
                gamePanel.add(gridLabels[i][j]);
            }
        }
        JPanel jPanel = new JPanel();
        JLabel gridLabels5 = new JLabel("MaxScore=" + MAXSCORE, SwingConstants.CENTER);
        gridLabels5.setFont(new Font("Arial", Font.BOLD, 50));
        jPanel.add(gridLabels5);


        add(gamePanel, BorderLayout.CENTER);
        add(jPanel, BorderLayout.SOUTH);
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                isGameOver();
                if (!gameOver) {
                    if (e.getKeyCode() == KeyEvent.VK_UP) {
                        moveUp();
                    } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                        moveDown();
                    } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                        moveLeft();
                    } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                        moveRight();
                    }
                } else {
                    max = grid[0][0];
                    for (int i = 0; i < 4; i++) {
                        for (int j = 0; j < 4; j++) {
                            if (grid[i][j] > max) {
                                max = grid[i][j];
                            }
                        }
                    }

                    try {
                        JdbcUtils.set2048MaxScore(max);
                    } catch (ClassNotFoundException | SQLException ex) {
                        throw new RuntimeException(ex);
                    }
                    JLabel message = new JLabel("GAME OVER!");
                    message.setFont(new Font("Dialog", Font.BOLD, 60));
                    JOptionPane.showInputDialog(gamePanel,message);


                }
            }
        });

        generateNewNumber();
        generateNewNumber();

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private int isGameOver() {
        int emptyCells = 0;

        // Count the number of empty cells
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if (grid[i][j] == 0) {
                    emptyCells++;
                }
            }
        }

        if (emptyCells == 0) {
            // No empty cells, game over
            gameOver = true;

        }
        return emptyCells;
    }

    private void generateNewNumber() {


        // Generate a new number (2 or 4) at a random empty cell
        int randomCell = (int) (Math.random() * isGameOver()) + 1;
        int count = 0;

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if (grid[i][j] == 0) {
                    count++;

                    if (count == randomCell) {
                        grid[i][j] = Math.random() < 0.9 ? 2 : 4;
                        updateGridLabels();
                        return;
                    }
                }
            }
        }
    }

    private void updateGridLabels() {
        // Update the labels to reflect the current grid state
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if (grid[i][j] == 0) {
                    gridLabels[i][j].setText("");
                } else {
                    gridLabels[i][j].setText(Integer.toString(grid[i][j]));
                }
            }
        }
    }

    private void moveUp() {
        boolean moved = false;

        for (int j = 0; j < 4; j++) {
            for (int i = 1; i < 4; i++) {
                if (grid[i][j] != 0) {
                    int k = i;

                    while (k > 0 && grid[k - 1][j] == 0) {
                        grid[k - 1][j] = grid[k][j];
                        grid[k][j] = 0;
                        k--;
                        moved = true;
                    }

                    if (k > 0 && grid[k - 1][j] == grid[k][j]) {
                        grid[k - 1][j] *= 2;
                        grid[k][j] = 0;
                        moved = true;
                    }
                }
            }
        }

        if (moved) {
            generateNewNumber();
        }
    }

    private void moveDown() {
        boolean moved = false;

        for (int j = 0; j < 4; j++) {
            for (int i = 2; i >= 0; i--) {
                if (grid[i][j] != 0) {
                    int k = i;

                    while (k < 3 && grid[k + 1][j] == 0) {
                        grid[k + 1][j] = grid[k][j];
                        grid[k][j] = 0;
                        k++;
                        moved = true;
                    }

                    if (k < 3 && grid[k + 1][j] == grid[k][j]) {
                        grid[k + 1][j] *= 2;
                        grid[k][j] = 0;
                        moved = true;
                    }
                }
            }
        }

        if (moved) {
            generateNewNumber();
        }
    }

    private void moveLeft() {
        boolean moved = false;

        for (int i = 0; i < 4; i++) {
            for (int j = 1; j < 4; j++) {
                if (grid[i][j] != 0) {
                    int k = j;

                    while (k > 0 && grid[i][k - 1] == 0) {
                        grid[i][k - 1] = grid[i][k];
                        grid[i][k] = 0;
                        k--;
                        moved = true;
                    }

                    if (k > 0 && grid[i][k - 1] == grid[i][k]) {
                        grid[i][k - 1] *= 2;
                        grid[i][k] = 0;
                        moved = true;
                    }
                }
            }
        }

        if (moved) {
            generateNewNumber();
        }
    }

    private void moveRight() {
        boolean moved = false;

        for (int i = 0; i < 4; i++) {
            for (int j = 2; j >= 0; j--) {
                if (grid[i][j] != 0) {
                    int k = j;

                    while (k < 3 && grid[i][k + 1] == 0) {
                        grid[i][k + 1] = grid[i][k];
                        grid[i][k] = 0;
                        k++;
                        moved = true;
                    }

                    if (k < 3 && grid[i][k + 1] == grid[i][k]) {
                        grid[i][k + 1] *= 2;
                        grid[i][k] = 0;
                        moved = true;
                    }
                }
            }
        }

        if (moved) {
            generateNewNumber();
        }
    }

//    @Override
//    protected void paintComponent(Graphics g) {
//        super.paintComponent(g);
//
//        // 绘制方块
//        for (int i = 0; i < 4; i++) {
//            for (int j = 0; j < 4; j++) {
//                int value = grid[i][j];
//                int x = j * 100 + 50;
//                int y = i * 100 + 50;
//
//                // 根据方块的值选择不同的颜色
//                Color color;
//                switch (value) {
//                    case 2:
//                        color = Color.YELLOW;
//                        break;
//                    case 4:
//                        color = Color.ORANGE;
//                        break;
//                    case 8:
//                        color = Color.RED;
//                        break;
//                    // 其他值的颜色...
//                    default:
//                        color = Color.GRAY;
//                        break;
//                }
//
//                // 绘制方块
//                g.setColor(color);
//                g.fillRect(x, y, 100, 100);
//
//                // 绘制方块的值
//                g.setColor(Color.BLACK);

//                g.setFont(new Font("Arial", Font.BOLD, 40));
//                g.drawString(String.valueOf(value), x + 40, y + 60);
//            }
//        }
//    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Game2048demo();
            }
        });
    }
}

我还用mysqlJdbc做了最好成绩的持久化

只需要导入mysql-connector的jar包,并创建JdbcUtils工具类,编写对应的方法即可,以下是我的实现:

public class JdbcUtils {
    public static int get2048maxScore() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://192.168.205.129:3306/students?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8", "root", "123456");
        PreparedStatement preparedStatement = connection.prepareStatement("select max(score) as score from table2048");
        ResultSet resultSet = preparedStatement.executeQuery();
        int score = 0;
        while (resultSet.next()) {
            score = resultSet.getInt("score");
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();
        return score;
    }

    public static void set2048MaxScore(int score) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://192.168.205.129:3306/students?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8", "root", "123456");
        PreparedStatement preparedStatement = connection.prepareStatement("insert into table2048 values (?,?)");
        preparedStatement.setTimestamp(1, java.sql.Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())));
        preparedStatement.setInt(2, score);
        preparedStatement.execute();
        preparedStatement.close();
        connection.close();
    }
}

修改主机名,创建对应的数据库和表即可

posted @ 2023-11-03 10:12  Nightblow  阅读(20)  评论(0)    收藏  举报