2 - Wordle Clone¶
2024 September 11, 1.5 hours
We split up the team into two groups. The people who were new to Java worked on the Wordle clone. The people who were more familiar worked on the Brainf interpreter.
Final code¶
1import java.util.ArrayList;
2import java.util.Scanner;
3
4public class Main {
5 private static final int WORD_LENGTH = 3;
6 private static final int MAX_ATTEMPTS = 9999999;
7
8 public static void main(String[] args) {
9 WordleReader reader = new WordleReader();
10 String secretWord = reader.getRandomWord();
11 int attempts = 0;
12
13 Scanner inputScanner = new Scanner(System.in);
14
15 boolean isRunning = true;
16 while (isRunning) {
17 String userInput = inputScanner.nextLine();
18
19 if (userInput.equals(secretWord)) {
20 System.out.println("Congrats you guessed it !!! " + secretWord);
21 isRunning = false;
22 break;
23 }
24
25 attempts++;
26 if (attempts > MAX_ATTEMPTS) {
27 System.out.println("Out of attempts :(");
28 isRunning = false;
29 break;
30 }
31
32 String result = "";
33 ArrayList<Integer> matchingIndeces = new ArrayList<>();
34 for (int i = 0; i < WORD_LENGTH; i++) {
35 char letter = userInput.charAt(i);
36
37 if (letter == secretWord.charAt(i)) {
38 result += reader.turnGreen(letter);
39 matchingIndeces.add(i);
40 } else if (secretWord.indexOf(letter) == -1) {
41 result += letter;
42 } else if (!matchingIndeces.contains(secretWord.indexOf(letter))) {
43 result += reader.turnYellow(letter);
44 } else {
45 result += letter;
46 }
47 }
48
49 System.out.println(result);
50 }
51 }
52}
1import java.util.ArrayList;
2import java.util.Random;
3import java.io.*;
4
5public class WordleReader {
6 private ArrayList<String> words = new ArrayList<String>();
7 private Random randGen = new Random(System.currentTimeMillis());
8
9 public WordleReader() {
10 try {
11 FileInputStream fstream = new FileInputStream("words.txt");
12
13 DataInputStream in = new DataInputStream(fstream);
14 BufferedReader br = new BufferedReader(new InputStreamReader(in));
15
16 String strLine;
17
18 while ((strLine = br.readLine()) != null) {
19 words.add(strLine);
20 }
21
22 in.close();
23 } catch (Exception err) {
24 System.err.println(err);
25 }
26 }
27
28 public String getRandomWord() {
29 return words.get(randGen.nextInt(words.size())).toLowerCase();
30 }
31
32 public boolean wordExists(String word) {
33 return words.contains(word);
34 }
35
36 public String turnGreen(String text) {
37 return "\e[42m" + text + "\e[0m";
38 }
39
40 public String turnYellow(String text) {
41 return "\e[43m" + text + "\e[0m";
42 }
43
44 public String turnGreen(char text) {
45 return "\e[42m" + text + "\e[0m";
46 }
47
48 public String turnYellow(char text) {
49 return "\e[43m" + text + "\e[0m";
50 }
51}