-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProjectFileIO_v2.java~
480 lines (390 loc) · 18 KB
/
ProjectFileIO_v2.java~
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/*********************************************************************************************************************
* ProjectFileIO.java
*********************************************************************************************************************/
import java.io.*;
import java.util.*;
public class ProjectFileIO_v2 {
//Global Constants
private static String FILE_NAME = "FileTest-1.txt";
private static String EOF_MARKER = "-";
private static String PLAYER_MARKER = "=";
private static String GLOBAL_SETTINGS_MARKER = ">";
private static String COMMENT_MARKER = "*";
private static boolean DEBUG = false;
private static String VERSION_NUMBER = "1.0";
//Global Variables related to file IO
private static FileReader fr;
private static BufferedReader br;
private static FileWriter fw;
private static PrintWriter pw;
//Data related to the Player objects
private static ArrayList<Player> playerArrayList = new ArrayList<Player>();
//================================================================================================================
public static void main(String[] args) throws IOException {
try {
readFile();
} catch(IOException io) {
System.out.println("IOException " + io.getMessage());
}
// Get username input from user
String user = IR4.getString("Please enter your username");
// Create object and add username to it
Player newPlayer = new Player();
newPlayer.setName(user);
// Check for user in File
boolean userCreated = addNewPlayer(newPlayer);
//===================== NEW USER ===========================/
if (userCreated) {
System.out.println("User " + user + " created.");
// Get a new password for new user (No spaces and > 8 chars)
String newPass = IR4.getString("Please set a password.");
while (newPass.length() < 8 || newPass.contains(" ")) {
System.out.println("Error. Password must be at least 8 characters long and contain no spaces.");
newPass = IR4.getString("Please set a password.");
}
newPlayer.setPassword(newPass);
// Update player with new password
updatePlayer(newPlayer);
}
//=================== END NEW USER =========================/
//=================== EXISTING USER ========================/
if (!userCreated) {
System.out.println("User " + user + " found.");
// Set existing user to reference variable
Player existingPlayer = new Player();
for (int i = 0; i < playerArrayList.size(); i++) {
if (playerArrayList.get(i).getName().equals(newPlayer.getName())) {
existingPlayer = playerArrayList.get(i);
break;
}
}
// Loop for getting correct password
String existingPass = IR4.getString("Please enter password for user " + user + " (or q to quit).");
while (!existingPass.equals(existingPlayer.getPassword()) && !existingPass.equals("q")) {
existingPass = IR4.getString("Incorrect password for user " + user + ". Please enter password (or q to quit).");
}
// Password correct
if (!existingPass.equals("q")) {
System.out.println("Password authenticated.");
}
}
//================= END EXISTING USER ======================/
try {
writeFile();
} catch(IOException io) {
System.out.println("IOException " + io.getMessage());
}
}
//================================================================================================================
public static void readFile() throws IOException {
System.out.println("Reading File...\n");
playerArrayList.clear();
try {
boolean keepGoing = true;
fr = new FileReader(FILE_NAME);
br = new BufferedReader(fr);
//The Priming Read
String entireLine = getLine();
//Loop through the File Header data ------------------------------
while (entireLine.substring(0,1).equals(COMMENT_MARKER)){
//System.out.println(entireLine);
entireLine = getLine();
}
//Loop through the Global Settings -------------------------------
if (entireLine.equals(GLOBAL_SETTINGS_MARKER)){
keepGoing = true;
do {
readAllGlobalSettings(entireLine);
entireLine = getLine();
//Look for last line of Global Settings
if (entireLine.substring(0,1).equals(GLOBAL_SETTINGS_MARKER)){
keepGoing = false;
}
} while (keepGoing);
}
//Loop through the Player data ------------------------------------
keepGoing = true;
do {
if (entireLine.substring(0,1).equals(PLAYER_MARKER)) {
readPlayerData(entireLine);
}
entireLine = getLine();
//Look for last line in the file
if (entireLine.substring(0,1).equals(EOF_MARKER)){
keepGoing = false;
}
} while (keepGoing);
br.close();
}
catch (FileNotFoundException e) {
System.out.println(FILE_NAME + " not found. Creating new file with sample player data.");
writeNewPlayer("Test", "pw123", 0, 0);
writeFile();
//readFile();
}
catch (EOFException e) {
System.out.println("Unexpected End of File found");
}
catch (Exception e) {
System.out.println("Unexpected Exception found");
}
}
//ADJUST AS NECESSARY!
private static void readAllGlobalSettings(String entireLine) {
//Add a file IO read of all the global settings for the game. 1 for each line
String setting1 = getLine();
String setting2 = getLine();
}
//ADJUST AS NECESSARY!
//In this example, the player has 3 pieces of data. You will change this to suite your game.
private static void readPlayerData(String entireLine){
//Get 1st line.
String name = getLine();
//Get 2nd line.
String password = getLine();
//Get 3rd line
String highScoreString = getLine();
//Get 4th line
String numberOfTimesPlayedString = getLine();
writeNewPlayer(name, password, Integer.parseInt(highScoreString), Integer.parseInt(numberOfTimesPlayedString));
}
//ADJUST AS NECESSARY!
private static void writeNewPlayer(String name, String password, int highScore, int numberOfTimesPlayed){
Player playerNew = new Player(name, password, highScore, numberOfTimesPlayed);
playerArrayList.add(playerNew);
}
//----------------------------------------------------------------------------------------------------------------
private static String getLine(){
String entireLine ="";
try {
entireLine = br.readLine();
if (DEBUG) {
System.out.println(entireLine);
}
}
catch (FileNotFoundException e) {
System.out.println(FILE_NAME + " not found. Creating new file.");
}
catch (EOFException e) {
System.out.println("Unexpected End of File found");
}
catch (Exception e) {
System.out.println("Unexpected Exception found");
}
return entireLine;
}
//================================================================================================================
public static void writeFile() throws IOException {
System.out.println("\nWriting File...");
fw = new FileWriter(FILE_NAME);
pw = new PrintWriter(fw);
writeHeaderLines();
writeGlobalSettingsLines();
writePlayerLines();
writeEOFline();
pw.close();
System.out.println("File written successfully.");
}
//ADJUST AS NECESSARY!
private static void writeHeaderLines(){
pw.println("***********************************");
pw.println("* Honest Hangman " + getVersionNumber());
pw.println("* Authors: Michael Bennett, John Gumm, Victoria Isles");
pw.println("* Add as many lines of comments as you want...");
pw.println("***********************************");
pw.flush();
}
//ADJUST AS NECESSARY!
private static void writeGlobalSettingsLines(){
String settingsMarker = GLOBAL_SETTINGS_MARKER + GLOBAL_SETTINGS_MARKER + GLOBAL_SETTINGS_MARKER;
pw.println(settingsMarker + " Global Settings " + settingsMarker);
pw.println("The 1st setting would go here...");
pw.println("The 2nd setting would go here...");
pw.println(settingsMarker + " End of Global Settings " + settingsMarker);
pw.flush();
}
//ADJUST AS NECESSARY!
private static void writePlayerLines(){
if (playerArrayList.size() == 0) {
System.out.println("The playerArrayList is empty!");
return;
}
for (int i = 0; i < playerArrayList.size(); i++){
String playerMarker = PLAYER_MARKER + PLAYER_MARKER + PLAYER_MARKER + PLAYER_MARKER + PLAYER_MARKER;
pw.println(playerMarker + " Player#" + i + " " + playerMarker);
pw.println(playerArrayList.get(i).getName());
pw.println(playerArrayList.get(i).getPassword());
pw.println(playerArrayList.get(i).getHighScore());
pw.println(playerArrayList.get(i).getNumberOfTimesPlayed());
pw.flush();
}
}
private static void writeEOFline() {
pw.println(EOF_MARKER + EOF_MARKER + EOF_MARKER + " End of File " + EOF_MARKER + EOF_MARKER + EOF_MARKER);
}
//================================================================================================================
public static String getVersionNumber() {
return VERSION_NUMBER;
}
public static String getFileName() {
return FILE_NAME;
}
public static ArrayList getPlayerArrayList(){
return playerArrayList;
}
public static void setPlayerArrayList(ArrayList<Player> newPlayerArrayList){
playerArrayList = newPlayerArrayList;
}
//Returns a Player object
public static Player getPlayer(String name, String password){
for (int i = 0; i < playerArrayList.size(); i++){
if (playerArrayList.get(i).getName().equals(name)
&& playerArrayList.get(i).getPassword().equals(password))
{
return playerArrayList.get(i);
}
}
return null; //player was not found
}
//Finds the specific Player object, deletes it, and adds the new Player object
public static void updatePlayer(Player newPlayer){
for (int i = 0; i < playerArrayList.size(); i++){
if (playerArrayList.get(i).getName().equals(newPlayer.getName())
&& playerArrayList.get(i).getPassword().equals(newPlayer.getPassword()))
{
playerArrayList.remove(i);
playerArrayList.add(newPlayer);
return;
}
}
System.out.println("Error in updatePlayer. Player not found.");
System.exit(-1);
}
//Adds the new Player object if there is no duplicate name and password
public static boolean addNewPlayer(Player newPlayer){
for (int i = 0; i < playerArrayList.size(); i++){
if (playerArrayList.get(i).getName().equals(newPlayer.getName())
/*&& playerArrayList.get(i).getPassword().equals(newPlayer.getPassword())*/)
{
return false; //indicates the player could not be added due to a duplcate player name and password.
}
}
playerArrayList.add(newPlayer);
return true; //the player was added successfully.
}
public static void runFileIO() {
try {
readFile();
} catch(IOException io) {
System.out.println("IOException " + io.getMessage());
}
// Get username input from user
String user = IR4.getString("Please enter your username");
// Create object and add username to it
Player newPlayer = new Player();
newPlayer.setName(user);
// Check for user in File
boolean userCreated = addNewPlayer(newPlayer);
//===================== NEW USER ===========================/
if (userCreated) {
System.out.println("User " + user + " created.");
// Get a new password for new user (No spaces and > 8 chars)
String newPass = IR4.getString("Please set a password.");
while (newPass.length() < 8 || newPass.contains(" ")) {
System.out.println("Error. Password must be at least 8 characters long and contain no spaces.");
newPass = IR4.getString("Please set a password.");
}
newPlayer.setPassword(newPass);
// Update player with new password
updatePlayer(newPlayer);
}
//=================== END NEW USER =========================/
//=================== EXISTING USER ========================/
if (!userCreated) {
System.out.println("User " + user + " found.");
// Set existing user to reference variable
Player existingPlayer = new Player();
for (int i = 0; i < playerArrayList.size(); i++) {
if (playerArrayList.get(i).getName().equals(newPlayer.getName())) {
existingPlayer = playerArrayList.get(i);
break;
}
}
// Loop for getting correct password
String existingPass = IR4.getString("Please enter password for user " + user);
while (!existingPass.equals(existingPlayer.getPassword())) {
existingPass = IR4.getString("Incorrect password for user " + user + ". Please enter password.");
}
}
//================= END EXISTING USER ======================/
try {
writeFile();
} catch(IOException io) {
System.out.println("IOException " + io.getMessage());
}
}
// Get top ten high scores
public static ArrayList<Player> getTopTen() {
// Read file
try {
readFile();
} catch(IOException io) {
System.out.println("IOException " + io.getMessage());
}
// Copy contents of player array to temp array
ArrayList<Player> tempPlayers = new ArrayList<Player>();
for (int i = 0; i < playerArrayList.size(); i++) {
tempPlayers.add(playerArrayList.get(i));
}
// Add top ten from temp players to top ten arraylist
ArrayList<Player> topTen = new ArrayList<Player>();
int counter = 0;
while (tempPlayers.size() > 0 && counter < 10) {
int topPlayerIndex = 0;
for (int i = 0; i < tempPlayers.size(); i++) {
if (tempPlayers.get(i).getHighScore() > tempPlayers.get(topPlayerIndex).getHighScore()) {
topPlayerIndex = i;
}
}
topTen.add(tempPlayers.get(topPlayerIndex));
tempPlayers.remove(topPlayerIndex);
counter++;
}
return topTen;
}
// Display top ten with names and high scores
public static void displayTopTen() {
ArrayList<Player> topTen = new ArrayList<Player>();
topTen = getTopTen();
System.out.println("********************************");
System.out.println(" High Scores ");
System.out.println("********************************");
System.out.println("Player Score");
System.out.println("********************************");
// 16/16
for (int i = 0; i < topTen.size(); i++) {
System.out.printf("%-16s%16d", topTen.get(i).getName(), topTen.get(i).getHighScore());
System.out.println();
}
}
// Get arraylist of words from specified .txt file
public static ArrayList<String> getDictionary(String txt) {
// Declare arraylist
ArrayList<String> WordArrayList = new ArrayList<String>();
// Create file instance
java.io.File file = new java.io.File(txt);
// Create scanner
try (Scanner input = new Scanner(file)) {
// Loop through .txt file
while (input.hasNext()) {
String word = input.nextLine();
WordArrayList.add(word);
}
// Close the file
input.close();
} catch (FileNotFoundException e) {
System.out.println("File not found exception: " + e.getMessage());
}
return WordArrayList;
}
}