-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseManager.java
More file actions
265 lines (236 loc) · 10.3 KB
/
DatabaseManager.java
File metadata and controls
265 lines (236 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import java.sql.*;
public class DatabaseManager {
private static final String DB_URL = "jdbc:sqlite:lexiguess.db";
private Connection conn;
public void connect() {
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(DB_URL);
try (Statement st = conn.createStatement()) {
st.execute("PRAGMA journal_mode=WAL;");
st.execute("PRAGMA foreign_keys=ON;");
}
createTables();
System.out.println("[DB] Connected to " + DB_URL);
} catch (ClassNotFoundException e) {
System.err.println("[DB] sqlite-jdbc driver not found. "
+ "Add sqlite-jdbc.jar to your classpath.");
} catch (SQLException e) {
System.err.println("[DB] Connection error: " + e.getMessage());
}
}
/** Cleanly closes the database connection. Call on application exit. */
public void disconnect() {
if (conn != null) {
try {
conn.close();
System.out.println("[DB] Connection closed.");
} catch (SQLException e) {
System.err.println("[DB] Error closing connection: " + e.getMessage());
}
}
}
public boolean isConnected() {
try {
return conn != null && !conn.isClosed();
} catch (SQLException e) {
return false;
}
}
private void createTables() throws SQLException {
try (Statement st = conn.createStatement()) {
st.execute("""
CREATE TABLE IF NOT EXISTS players (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
""");
st.execute("""
CREATE TABLE IF NOT EXISTS leaderboard (
id INTEGER PRIMARY KEY AUTOINCREMENT,
player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
score INTEGER NOT NULL DEFAULT 0,
stage INTEGER NOT NULL DEFAULT 1,
recorded_at TEXT NOT NULL DEFAULT (datetime('now'))
);
""");
st.execute("""
CREATE TABLE IF NOT EXISTS level_progress (
id INTEGER PRIMARY KEY AUTOINCREMENT,
player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
difficulty TEXT NOT NULL CHECK(difficulty IN ('EASY','MEDIUM','HARD')),
highest_unlocked INTEGER NOT NULL DEFAULT 1,
UNIQUE(player_id, difficulty)
);
""");
}
System.out.println("[DB] Tables verified / created.");
}
public int getOrCreatePlayer(String name) {
if (!isConnected()) return -1;
try {
try (PreparedStatement ps = conn.prepareStatement(
"SELECT id FROM players WHERE name = ? COLLATE NOCASE")) {
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
if (rs.next()) return rs.getInt("id");
}
try (PreparedStatement ps = conn.prepareStatement(
"INSERT INTO players (name) VALUES (?)")) {
ps.setString(1, name);
ps.executeUpdate();
}
try (Statement st = conn.createStatement()) {
ResultSet rs = st.executeQuery("SELECT last_insert_rowid()");
if (rs.next()) {
int id = rs.getInt(1);
System.out.println("[DB] New player '" + name + "' created with id=" + id);
return id;
}
}
} catch (SQLException e) {
System.err.println("[DB] getOrCreatePlayer error: " + e.getMessage());
}
return -1;
}
public void saveScore(String playerName, int score, int stage) {
if (!isConnected()) return;
int playerId = getOrCreatePlayer(playerName);
if (playerId == -1) return;
try {
try (PreparedStatement ps = conn.prepareStatement(
"SELECT id, score FROM leaderboard WHERE player_id = ?")) {
ps.setInt(1, playerId);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int existingScore = rs.getInt("score");
if (score > existingScore) {
try (PreparedStatement upd = conn.prepareStatement(
"UPDATE leaderboard SET score=?, stage=?, recorded_at=datetime('now') WHERE player_id=?")) {
upd.setInt(1, score);
upd.setInt(2, stage);
upd.setInt(3, playerId);
upd.executeUpdate();
System.out.println("[DB] Leaderboard updated for '" + playerName
+ "': " + existingScore + " -> " + score);
}
}
} else {
try (PreparedStatement ins = conn.prepareStatement(
"INSERT INTO leaderboard (player_id, score, stage) VALUES (?,?,?)")) {
ins.setInt(1, playerId);
ins.setInt(2, score);
ins.setInt(3, stage);
ins.executeUpdate();
System.out.println("[DB] Leaderboard entry created for '"
+ playerName + "' score=" + score);
}
}
}
} catch (SQLException e) {
System.err.println("[DB] saveScore error: " + e.getMessage());
}
}
/**
* Returns the top {@code limit} leaderboard entries sorted by score descending.
*
* @param limit Maximum number of rows to return (e.g. 10).
* @return Array of {@link LeaderboardRow}; empty array on error.
*/
public LeaderboardRow[] getTopScores(int limit) {
if (!isConnected()) return new LeaderboardRow[0];
try (PreparedStatement ps = conn.prepareStatement("""
SELECT p.name, l.score, l.stage, l.recorded_at
FROM leaderboard l
JOIN players p ON p.id = l.player_id
ORDER BY l.score DESC
LIMIT ?
""")) {
ps.setInt(1, limit);
ResultSet rs = ps.executeQuery();
java.util.List<LeaderboardRow> rows = new java.util.ArrayList<>();
while (rs.next()) {
rows.add(new LeaderboardRow(
rs.getString("name"),
rs.getInt("score"),
rs.getInt("stage"),
rs.getString("recorded_at")));
}
return rows.toArray(new LeaderboardRow[0]);
} catch (SQLException e) {
System.err.println("[DB] getTopScores error: " + e.getMessage());
return new LeaderboardRow[0];
}
}
/** Wipes all leaderboard rows (keeps player records intact). */
public void clearLeaderboard() {
if (!isConnected()) return;
try (Statement st = conn.createStatement()) {
st.execute("DELETE FROM leaderboard;");
System.out.println("[DB] Leaderboard cleared.");
} catch (SQLException e) {
System.err.println("[DB] clearLeaderboard error: " + e.getMessage());
}
}
public int getProgress(String playerName, String difficulty) {
if (!isConnected()) return 1;
int playerId = getOrCreatePlayer(playerName);
if (playerId == -1) return 1;
try (PreparedStatement ps = conn.prepareStatement(
"SELECT highest_unlocked FROM level_progress WHERE player_id=? AND difficulty=?")) {
ps.setInt(1, playerId);
ps.setString(2, difficulty.toUpperCase());
ResultSet rs = ps.executeQuery();
if (rs.next()) return rs.getInt("highest_unlocked");
} catch (SQLException e) {
System.err.println("[DB] getProgress error: " + e.getMessage());
}
return 1;
}
public void saveProgress(String playerName, String difficulty, int highestUnlocked) {
if (!isConnected()) return;
int playerId = getOrCreatePlayer(playerName);
if (playerId == -1) return;
try {
try (PreparedStatement ps = conn.prepareStatement("""
INSERT INTO level_progress (player_id, difficulty, highest_unlocked)
VALUES (?, ?, ?)
ON CONFLICT(player_id, difficulty) DO UPDATE
SET highest_unlocked = MAX(excluded.highest_unlocked, highest_unlocked)
""")) {
ps.setInt(1, playerId);
ps.setString(2, difficulty.toUpperCase());
ps.setInt(3, highestUnlocked);
ps.executeUpdate();
System.out.println("[DB] Progress saved: " + playerName
+ " / " + difficulty + " -> level " + highestUnlocked);
}
} catch (SQLException e) {
System.err.println("[DB] saveProgress error: " + e.getMessage());
}
}
public java.util.Map<String, Integer> loadAllProgress(String playerName) {
java.util.Map<String, Integer> map = new java.util.HashMap<>();
map.put("EASY", getProgress(playerName, "EASY"));
map.put("MEDIUM", getProgress(playerName, "MEDIUM"));
map.put("HARD", getProgress(playerName, "HARD"));
return map;
}
public static class LeaderboardRow {
public final String name;
public final int score;
public final int stage;
public final String recordedAt;
LeaderboardRow(String name, int score, int stage, String recordedAt) {
this.name = name;
this.score = score;
this.stage = stage;
this.recordedAt = recordedAt;
}
@Override
public String toString() {
return name + " score=" + score + " stage=" + stage + " @" + recordedAt;
}
}
}