AI智能
改变未来

GUI实现猜数字游戏


GUI实现猜数字游戏

猜数字游戏:选手输入姓名进行测试,输入猜的数字,判断是否有姓名,有的话系统判断是否猜对,猜对了文字提示,并出现保存按钮(数据库),提示猜的次数,同样猜小了,猜大了都有弹窗提示,选手可以查询排行榜,有时间限制,到时间弹窗提示,点击确定退出程序。
程序涉及的技术栈有Java基础知识,MVC三层架构,JDBC,MySQL数据库等等 。

项目结构

原型图

mapper层

userMapper接口

public interface UserMapper {//添加比赛用户信息int addUser(Connection connection, String username, int count);//查询所有用户信息List<User> getUsers(Connection connection);}

userMapperImpl实现类

public class UserMapperImpl implements UserMapper {@Overridepublic int addUser(Connection connection, String username, int count) {PreparedStatement pstm = null;int execute = 0;try {connection.setAutoCommit(false);String sql = \"insert into user_two values (?,?,?)\";Object[] params = {null, username, count};execute = JdbcUtil.execute(connection, pstm, sql, params);if (execute>0){connection.commit();}} catch (SQLException e) {e.printStackTrace();try {connection.rollback();} catch (SQLException e1) {e1.printStackTrace();}}finally {JdbcUtil.closeResource(connection,pstm);}return execute;}@Overridepublic List<User> getUsers(Connection connection) {PreparedStatement pstm = null;ResultSet rs = null;ArrayList<User> userList = new ArrayList<>();User user;try {String sql = \"select id,username,count from user_two order by count asc\";Object[] params = {};rs = JdbcUtil.execute(connection, rs, pstm, sql, params);while (rs.next()){user = new User();user.setId(rs.getInt(\"id\"));user.setUserName(rs.getString(\"username\"));user.setCount(rs.getInt(\"count\"));userList.add(user);}} catch (SQLException e) {e.printStackTrace();}return userList;}}

service层

userService接口

public interface UserService {//添加比赛用户信息boolean addUser(String username, int count);//查询所有用户信息List<User> getUsers();}

userServiceImpl实现类

public class UserServiceImpl implements UserService {private UserMapper userMapper;public UserServiceImpl() {this.userMapper = new UserMapperImpl();}@Overridepublic boolean addUser(String username, int count) {boolean flag = false;Connection connection = JdbcUtil.getConnection();if (userMapper.addUser(connection, username, count) > 0) {flag = true;}JdbcUtil.closeResource(connection,null);return flag;}@Overridepublic List<User> getUsers() {Connection connection = JdbcUtil.getConnection();List<User> userList = userMapper.getUsers(connection);return userList;}}

controller层

public class UserController {UserServiceImpl userService = new UserServiceImpl();/*** 保存个人信息* @param username* @param count*/public boolean operation(String username,int count){return userService.addUser(username, count);}/*** 查询排行榜*/public List<User> getUser(){List<User> userList = userService.getUsers();return userList;}}

pojo实体类

public class User implements Serializable {private static final long serialVersionUID = 1L;private Integer id;private String userName;private Integer count;public User(Integer id, String userName, Integer count) {this.id = id;this.userName = userName;this.count = count;}public User() {}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public Integer getCount() {return count;}public void setCount(Integer count) {this.count = count;}@Overridepublic String toString() {return \"User{\" +\"id=\" + id +\", userName=\'\" + userName + \'\\\'\' +\", count=\" + count +\'}\';}}

JdbcUtil工具类

public class JdbcUtil {private static String driver;private static String url;private static String username;private static String password;//加载配置文件static {Properties properties = new Properties();InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream(\"db.properties\");try {properties.load(is);} catch (IOException e) {e.printStackTrace();}driver = properties.getProperty(\"driver\");url = properties.getProperty(\"url\");username = properties.getProperty(\"username\");password = properties.getProperty(\"password\");}/*** 获取数据库连接对象* @return*/public static Connection getConnection(){Connection connection = null;try {Class.forName(driver);connection = DriverManager.getConnection(url, username, password);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return connection;}/*** 查询公共类*/public static ResultSet execute(Connection connection, ResultSet resultSet, PreparedStatement preparedStatement,String sql,Object[] params) throws SQLException {preparedStatement = connection.prepareStatement(sql);for (int i = 0; i < params.length; i++) {preparedStatement.setObject(i+1,params[i]);}resultSet = preparedStatement.executeQuery();return resultSet;}/*** 增删改公共方法*/public static int execute(Connection connection, PreparedStatement preparedStatement,String sql,Object[] params) throws SQLException {preparedStatement = connection.prepareStatement(sql);for (int i = 0; i < params.length; i++) {preparedStatement.setObject(i+1,params[i]);}int updateRows = preparedStatement.executeUpdate();return updateRows;}/*** 释放资源*/public static boolean closeResource(Connection connection, ResultSet resultSet, PreparedStatement preparedStatement){boolean flag = true;if (connection!=null){try {connection.close();//GC回收connection=null;} catch (SQLException e) {e.printStackTrace();flag=false;}}if (resultSet!=null){try {resultSet.close();resultSet=null;} catch (SQLException e) {e.printStackTrace();flag=false;}}if (preparedStatement!=null){try {preparedStatement.close();preparedStatement=null;} catch (SQLException e) {e.printStackTrace();flag=false;}}return flag;}public static boolean closeResource(Connection connection, PreparedStatement preparedStatement){return closeResource(connection,null,preparedStatement);}}

view层

界面绘制

public class Game {public Game() {init();}//次数private int count=0;//随机数private int num = new Random().nextInt(101);private JFrame jFrame;//选手姓名private JTextField jTextField2;//时间内容private JLabel jLabel;private UserController controller = new UserController();//初始化界面public void init(){jFrame = new JFrame(\"猜数字游戏\");JPanel jPanel1 = new JPanel();JPanel jPanel2 = new JPanel();JPanel jPanel3 = new JPanel();JPanel jPanel4 = new JPanel();//倒计时jLabel = new JLabel();JButton button1 = new JButton(\"提交\");JButton button2 = new JButton(\"重置\");JButton jButton3 = new JButton(\"查询排行榜\");JTextField jTextField1 = new JTextField(10);jTextField2 = new JTextField(10);jPanel1.setLayout(new FlowLayout());jPanel2.setLayout(new GridLayout(2,1));jPanel3.setLayout(new GridLayout(2,1));jPanel4.setLayout(new FlowLayout());jFrame.setBounds(500,300,600,300);//设置布局jFrame.setLayout(new BorderLayout());jFrame.add(jPanel1,BorderLayout.NORTH);jFrame.add(jPanel2,BorderLayout.WEST);jFrame.add(jPanel3,BorderLayout.CENTER);jFrame.add(jPanel4,BorderLayout.SOUTH);//添加 组件jPanel1.add(new JLabel(\"欢迎来到猜数字游戏\"));jPanel1.add(jLabel);jPanel2.add(new JLabel(\"请输入你的姓名\"));jPanel2.add(new JLabel(\"请输入你猜的数字\"));jPanel3.add(jTextField2);jPanel3.add(jTextField1);jPanel4.add(button1);jPanel4.add(button2);jPanel4.add(jButton3);//重置猜的数字button2.addActionListener(new AbstractAction() {@Overridepublic void actionPerformed(ActionEvent e) {jTextField1.setText(\"\");}});//提交判断是否猜对button1.addActionListener(new AbstractAction() {@Overridepublic void actionPerformed(ActionEvent e) {if (jTextField2.getText().equals(\"\")){JOptionPane.showMessageDialog(null,\"请输入姓名\");}else{int num = Integer.parseInt(jTextField1.getText());count++;if (num== Game.this.num){setSucceedJDialog(\"恭喜您,猜对了\");}else if (num> Game.this.num){setSucceedJDialog(\"猜大了\");}else {setSucceedJDialog(\"猜小了\");}}}});//查询排行榜的事件jButton3.addActionListener(new AbstractAction() {@Overridepublic void actionPerformed(ActionEvent e) {//调用controller   获取数据List<User> userList = controller.getUser();setQueryJDialog(userList);}});jFrame.setResizable(false);jFrame.setVisible(true);jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);}//猜对了  弹窗public void setSucceedJDialog(String title){//true:依附于窗体,不取消弹窗不可以操作窗体JDialog succeedJDialog = new JDialog(jFrame,true);Container contentPane = succeedJDialog.getContentPane();JPanel jPanel1 = new JPanel();JPanel jPanel2 = new JPanel();JLabel jLabel = new JLabel();JButton jButton1 = new JButton(\"确定\");contentPane.setLayout(new BorderLayout());contentPane.add(jPanel1,BorderLayout.NORTH);contentPane.add(jPanel2,BorderLayout.SOUTH);jPanel1.setLayout(new GridLayout(3,1));jPanel2.setLayout(new FlowLayout());jPanel1.add(new JLabel(title));jPanel1.add(new JLabel(\"您猜了\"+count+\"次\"));jPanel1.add(jLabel);jPanel2.add(jButton1);//猜对了出现保存按钮并添加事件if (\"恭喜您,猜对了\".equals(title)){JButton jButton2 = new JButton(\"保存\");jPanel2.add(jButton2);jButton2.addActionListener(new AbstractAction() {@Overridepublic void actionPerformed(ActionEvent e) {String username = jTextField2.getText();boolean isSucceed = controller.operation(username, count);if (isSucceed){jLabel.setText(\"保存数据成功!\");}else{jLabel.setText(\"保存数据失败!\");}}});}//添加确定的关闭事件jButton1.addActionListener(new AbstractAction() {@Overridepublic void actionPerformed(ActionEvent e) {succeedJDialog.dispose();}});succeedJDialog.setResizable(false);succeedJDialog.setBounds(1100,300,300,150);succeedJDialog.setVisible(true);}//查询排行榜   表格弹窗public void setQueryJDialog(List<User> userList){//排名int rank = 1;Vector<String> head = new Vector<>();Vector<Vector<Object>> content = new Vector<>();head.add(\"编号\");head.add(\"姓名\");head.add(\"所用次数\");head.add(\"排名\");for (User user : userList) {Vector<Object> row = new Vector<>();row.add(user.getId());row.add(user.getUserName());row.add(user.getCount());row.add(\"第\"+rank+\"名\");rank++;content.add(row);}//弹窗JDialog queryJDialog = new JDialog(jFrame,true);//表格JTable jTable = new JTable(content,head);//可滚动面板JScrollPane jScrollPane = new JScrollPane(jTable);//获得容器Container contentPane = queryJDialog.getContentPane();contentPane.add(jScrollPane);queryJDialog.setResizable(false);queryJDialog.setBounds(1100,300,500,300);queryJDialog.setVisible(true);}//倒计时public void getTime() {long time = 1500; // 自定义倒计时间20分钟long hour = 0;long minute = 0;long seconds = 0;while (time >= 0) {hour = time / 3600;minute = (time - hour * 3600) / 60;seconds = time - hour * 3600 - minute * 60;jLabel.setText(\"       还剩\"+hour + \"时\"+minute + \"分\"+seconds + \"秒\");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}time--;}if (time<0){setTimeJDialog();}}//设置倒计时结束弹窗public void setTimeJDialog(){JDialog timeJDialog = new JDialog(jFrame,true);Container contentPane = timeJDialog.getContentPane();JPanel jPanel1 = new JPanel();JPanel jPanel2 = new JPanel();JButton jButton1 = new JButton(\"确定\");contentPane.setLayout(new BorderLayout());contentPane.add(jPanel1,BorderLayout.NORTH);contentPane.add(jPanel2,BorderLayout.SOUTH);jPanel1.setLayout(new FlowLayout());jPanel1.add(new JLabel(\"时间到,挑战失败\"));jPanel2.setLayout(new FlowLayout());jPanel2.add(jButton1);//添加确定的关闭事件jButton1.addActionListener(new AbstractAction() {@Overridepublic void actionPerformed(ActionEvent e) {System.exit(0);}});timeJDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);timeJDialog.setResizable(false);timeJDialog.setBounds(1100,300,300,150);timeJDialog.setVisible(true);}}

主启动类

public class Main {public static void main(String[] args) {new Game().getTime();}}

运行结果






赞(0) 打赏
未经允许不得转载:爱站程序员基地 » GUI实现猜数字游戏