This repository has been archived by the owner on May 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Wordle.java
83 lines (72 loc) · 2.7 KB
/
Wordle.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
/*
* File: Wordle.java
* -----------------
* This module is the starter file for the Wordle assignment.
* BE SURE TO UPDATE THIS COMMENT WHEN YOU COMPLETE THE CODE.
*/
import edu.willamette.cs1.wordle.WordleDictionary;
import edu.willamette.cs1.wordle.WordleGWindow;
import java.util.Arrays;
import java.util.Random;
public class Wordle {
private static String wordChoice;
private WordleGWindow gw;
private int row;
/*
* Called when the user hits the RETURN key or clicks the ENTER button,
* passing in the string of characters on the current row.
*/
public static void main(String[] args) {
new Wordle().run();
}
/* Startup code */
private static boolean checkWin(String s) {
char[] answer = s.toCharArray();
char[] correct = wordChoice.toCharArray();
for (int i = 0; i < 5; i++) {
if (answer[i] != correct[i]) {
return false;
}
}
return true;
}
/* Private instance variables */
public void run() {
gw = new WordleGWindow();
gw.addEnterListener((s) -> enterAction(s));
Random random = new Random();
wordChoice = WordleDictionary.FIVE_LETTER_WORDS[random.nextInt(WordleDictionary.FIVE_LETTER_WORDS.length - 1)];
System.out.println(wordChoice);
/*for (int i = 0; i < 5; i++) {
gw.setSquareLetter(0, i, String.valueOf(wordChoice.charAt(i)));
}*/
}
public void enterAction(String s) {
boolean win = false;
row = gw.getCurrentRow();
s = s.toLowerCase();
if (Arrays.asList(WordleDictionary.FIVE_LETTER_WORDS).contains(s)) {
char[] correctLetters = wordChoice.toCharArray();
char[] answerLetters = s.toCharArray();
for (int i = 0; i < 5; i++) {
if (answerLetters[i] == correctLetters[i]) {
gw.setSquareColor(row, i, WordleGWindow.CORRECT_COLOR);
} else if (wordChoice.indexOf(answerLetters[i]) != -1) {
gw.setSquareColor(row, i, WordleGWindow.PRESENT_COLOR);
} else {
gw.setSquareColor(row, i, WordleGWindow.MISSING_COLOR);
gw.setKeyColor(Character.toString(answerLetters[i]).toUpperCase(), WordleGWindow.MISSING_COLOR);
}
}
if (checkWin(s)) {
gw.showMessage("You Win. :-), it only took " + (row + 1) + " tries.");
} else if (row < 6) {
gw.setCurrentRow(row + 1);
} else {
gw.showMessage("The correct word is:" + wordChoice);
}
} else {
gw.showMessage("Not in word list.");
}
}
}