· 8 years ago · May 25, 2018, 01:14 AM
1import javax.swing.*;
2import java.sql.*;
3import java.util.Vector;
4
5public class HighscoreDB {
6
7 private static final String SCORE_TABLE = "scores";
8
9
10 private Connection conn;
11
12
13 /** Default constructor **/
14 public HighscoreDB() {
15
16 // connect to the database
17 createConnection();
18 // initialize the score table
19 initializeScoreTable();
20 }
21
22 /************************** Overridden Methods **************************/
23
24 /****************************** Accessors *******************************/
25
26 /****************************** Mutators ********************************/
27
28 /**************************** Other Methods *****************************/
29
30 /**
31 * Add a score to the database.
32 * @param name the person who got the score
33 * @param score the score value
34 * @param difficulty the game difficulty level. Must be one of <code>Game.EASY</code>, <code>Game.MEDIUM</code>,
35 * or <code>Game.HARD</code>.
36 * @return <code>true</code> if the score was successfully added, <code>false</code> otherwise.
37 */
38 public boolean addScore(String name, int score, int difficulty) {
39
40 try {
41
42 // prepare an sql statement to insert the score
43 PreparedStatement prep = conn.prepareStatement(String.format("INSERT INTO %s VALUES (?, ?, ?);", SCORE_TABLE));
44
45 // bind the correct values
46 prep.setString(1, name);
47 prep.setInt(2, score);
48 prep.setInt(3, difficulty);
49 prep.addBatch();
50
51 // execute the statement
52 conn.setAutoCommit(false);
53 prep.executeBatch();
54 conn.setAutoCommit(true);
55
56 return true;
57
58 } catch (SQLException e) {
59
60 // failed to add score
61 return false;
62 }
63 }
64
65 /**
66 * Gets a list of scores obtained on the specified difficulty.
67 * @param difficulty the game difficulty level. Must be one of <code>Game.EASY</code>, <code>Game.MEDIUM</code>,
68 * or <code>Game.HARD</code>.
69 * @return a <code>Vector</code> of <code>Vector</code>s of <code>Object</code>s
70 */
71 public Vector<Vector<Object>> getScores(int difficulty) {
72
73 try {
74
75 // create and execute a statement to find a list of scores matching the given difficulty, sorted in
76 // descending order by score.
77 Statement stat = conn.createStatement();
78 ResultSet rs = stat.executeQuery(String.format("SELECT * FROM %s WHERE difficulty = %d ORDER BY score DESC",
79 SCORE_TABLE, difficulty));
80
81 // create the vector to store the scores
82 Vector<Vector<Object>> scores = new Vector<Vector<Object>>();
83
84 // loop through all the results and add them to the scores vector
85 while (rs.next()) {
86 Vector<Object> row = new Vector<Object>();
87 row.add(rs.getString("name"));
88 row.add(rs.getInt("score"));
89 scores.add(row);
90 }
91
92 // return the vector
93 return scores;
94
95 } catch (SQLException e) {
96
97 // error getting the scores, return null
98 return null;
99 }
100 }
101
102 /**
103 * Create a connection to the scores db.
104 */
105 private void createConnection() {
106
107 try {
108
109 // attempt to load the sqlite manager class
110 Class.forName("org.sqlite.JDBC");
111 // create the connection
112 conn = DriverManager.getConnection("jdbc:sqlite:scores.db");
113
114 } catch (ClassNotFoundException e) {
115
116 // couldn't find the driver for sqlite
117 JOptionPane.showMessageDialog(null, "Failed to find sqlite driver. Cannot display highscores", "Error", JOptionPane.ERROR_MESSAGE);
118
119 } catch (SQLException e) {
120
121 // couldn't connect to database
122 JOptionPane.showMessageDialog(null, "Failed to connect to score database. Cannot display highscores", "Error", JOptionPane.ERROR_MESSAGE);
123 }
124 }
125
126 /**
127 * Create the scores table if it doesn't exist.
128 */
129 private void initializeScoreTable() {
130
131 try {
132 Statement stat = conn.createStatement();
133 stat.executeUpdate("CREATE TABLE IF NOT EXISTS " + SCORE_TABLE + " (name TEXT, score INTEGER, difficulty INTEGER);");
134
135 } catch (SQLException e) {
136
137 JOptionPane.showMessageDialog(null, "Could not create score table.", "Error", JOptionPane.ERROR_MESSAGE);
138 }
139 }
140}