Skip to content

Commit bfdda05

Browse files
committed
Merge branch 'master' into release
2 parents 43a1f37 + b3ee459 commit bfdda05

17 files changed

Lines changed: 564 additions & 67 deletions

File tree

README.md

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
# Number Guessing Game
22

3-
A simple number guessing game where you try to guess a randomly generated number. The game will tell you if your guess is too high or too low until you find the correct number.
3+
A simple number guessing game where you try to guess a randomly generated number. The game features both a user-friendly graphical interface (GUI) and a classic console mode. The GUI provides visual feedback with color-coded hints and tracks your progress in real-time.
4+
5+
**Features:**
6+
- 🎮 Modern Swing-based GUI (default)
7+
- 💻 Classic console mode (use `--console` flag)
8+
- 🎯 Visual feedback with color coding
9+
- 📊 Real-time guess counter
10+
- ⌨️ Keyboard shortcuts for quick navigation
11+
- 🌍 Cross-platform compatible (Windows, macOS, Linux)
412

513
## Installation & Running
614

@@ -66,11 +74,40 @@ Run `run.sh`
6674

6775
### How to Play
6876

77+
The game now features both a graphical user interface (GUI) and a console mode.
78+
79+
#### GUI Mode (Default)
80+
6981
1. Start the game using one of the methods above
70-
2. Enter your guess when prompted
71-
3. The game will tell you if your guess is too high or too low
72-
4. Keep guessing until you find the correct number
73-
5. The game will display how many guesses it took you
82+
2. A window will appear with the game interface
83+
3. Enter your guess in the text field and click "Submit Guess" or press Enter
84+
4. The game will provide visual feedback:
85+
- Blue text indicates your guess was too low
86+
- Orange text indicates your guess was too high
87+
- Green text indicates you guessed correctly!
88+
5. The number of guesses is displayed and updated in real-time
89+
6. When you guess correctly, click "New Game" to play again
90+
7. Use the menu bar for additional options:
91+
- File → New Game (Ctrl+N): Start a new game
92+
- File → Exit: Close the application
93+
- Help → About: View game information
94+
95+
#### Console Mode
96+
97+
To run the classic console version, use the `--console` or `-c` flag:
98+
99+
```bash
100+
java -jar app.jar --console
101+
# or
102+
./run.sh --console # Linux/Mac
103+
run.bat --console # Windows
104+
```
105+
106+
In console mode:
107+
1. Enter your guess when prompted
108+
2. The game will tell you if your guess is too high or too low
109+
3. Keep guessing until you find the correct number
110+
4. The game will display how many guesses it took you
74111

75112
## Development
76113

app/src/main/java/io/github/project516/NumberGuessingGame/CheckGuess.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ void check(int guess) {
2020
void quit(int input) {
2121
// 0 is quit
2222
// 1 is continue
23-
if (input != 0 || input != 1) {
23+
if (input != 0 && input != 1) {
2424
throw new IllegalArgumentException("Invalid number!");
2525
}
2626
}
Lines changed: 285 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,306 @@
11
package io.github.project516.NumberGuessingGame;
22

33
import java.awt.*;
4+
import java.awt.event.*;
45
import javax.swing.*;
56

6-
// TODO
7-
87
/**
98
* Graphical User Interface for the Number Guessing Game. This class creates and manages the game's
10-
* window and UI components. Currently under development.
9+
* window and UI components using Java Swing. Provides a user-friendly interface for playing the
10+
* number guessing game with visual feedback and menu options.
1111
*/
12-
public class GUI {
12+
public class GUI extends JFrame {
13+
// Game state
14+
private int targetNumber;
15+
private int numberOfGuesses;
16+
private RandomNumber randomGenerator;
17+
private CheckGuess guessChecker;
18+
private GameInfo gameInfo;
19+
20+
// UI Components
21+
private JTextField guessField;
22+
private JButton submitButton;
23+
private JButton newGameButton;
24+
private JLabel feedbackLabel;
25+
private JLabel promptLabel;
26+
private JLabel guessCountLabel;
27+
private JPanel mainPanel;
28+
29+
/**
30+
* Constructs the GUI and initializes all components. Sets up the game window with proper layout
31+
* and starts a new game.
32+
*/
33+
public GUI() {
34+
super("Number Guessing Game");
35+
36+
// Initialize game objects
37+
randomGenerator = new RandomNumber();
38+
guessChecker = new CheckGuess();
39+
gameInfo = new GameInfo();
40+
41+
// Set up the frame
42+
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
43+
setSize(500, 400);
44+
setLocationRelativeTo(null); // Center on screen
45+
setResizable(false);
46+
47+
// Create menu bar
48+
createMenuBar();
49+
50+
// Create main panel
51+
createMainPanel();
52+
53+
// Start new game
54+
startNewGame();
55+
56+
setVisible(true);
57+
}
58+
59+
/** Creates and configures the menu bar with File and Help menus. */
60+
private void createMenuBar() {
61+
JMenuBar menuBar = new JMenuBar();
62+
63+
// File menu
64+
JMenu fileMenu = new JMenu("File");
65+
fileMenu.setMnemonic(KeyEvent.VK_F);
66+
67+
JMenuItem newGameItem = new JMenuItem("New Game", KeyEvent.VK_N);
68+
newGameItem.setAccelerator(
69+
KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK));
70+
newGameItem.addActionListener(e -> startNewGame());
71+
fileMenu.add(newGameItem);
72+
73+
fileMenu.addSeparator();
74+
75+
JMenuItem exitItem = new JMenuItem("Exit", KeyEvent.VK_X);
76+
exitItem.addActionListener(e -> System.exit(0));
77+
fileMenu.add(exitItem);
78+
79+
// Help menu
80+
JMenu helpMenu = new JMenu("Help");
81+
helpMenu.setMnemonic(KeyEvent.VK_H);
82+
83+
JMenuItem aboutItem = new JMenuItem("About", KeyEvent.VK_A);
84+
aboutItem.addActionListener(e -> showAboutDialog());
85+
helpMenu.add(aboutItem);
86+
87+
menuBar.add(fileMenu);
88+
menuBar.add(helpMenu);
89+
90+
setJMenuBar(menuBar);
91+
}
92+
93+
/** Creates and configures the main game panel with all UI components. */
94+
private void createMainPanel() {
95+
mainPanel = new JPanel();
96+
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
97+
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
98+
99+
// Title label
100+
JLabel titleLabel = new JLabel("Number Guessing Game");
101+
titleLabel.setFont(new Font("Arial", Font.BOLD, 24));
102+
titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
103+
mainPanel.add(titleLabel);
104+
105+
mainPanel.add(Box.createRigidArea(new Dimension(0, 20)));
106+
107+
// Instructions label
108+
JLabel instructionsLabel = new JLabel("Guess a number between 1 and 100!");
109+
instructionsLabel.setFont(new Font("Arial", Font.PLAIN, 14));
110+
instructionsLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
111+
mainPanel.add(instructionsLabel);
112+
113+
mainPanel.add(Box.createRigidArea(new Dimension(0, 30)));
114+
115+
// Guess count label
116+
guessCountLabel = new JLabel("Number of guesses: 0");
117+
guessCountLabel.setFont(new Font("Arial", Font.PLAIN, 12));
118+
guessCountLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
119+
mainPanel.add(guessCountLabel);
120+
121+
mainPanel.add(Box.createRigidArea(new Dimension(0, 20)));
122+
123+
// Prompt label
124+
promptLabel = new JLabel("Enter your guess:");
125+
promptLabel.setFont(new Font("Arial", Font.PLAIN, 14));
126+
promptLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
127+
mainPanel.add(promptLabel);
128+
129+
mainPanel.add(Box.createRigidArea(new Dimension(0, 10)));
130+
131+
// Input panel
132+
JPanel inputPanel = new JPanel();
133+
inputPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
134+
135+
guessField = new JTextField(10);
136+
guessField.setFont(new Font("Arial", Font.PLAIN, 16));
137+
guessField.addActionListener(e -> submitGuess());
138+
inputPanel.add(guessField);
139+
140+
submitButton = new JButton("Submit Guess");
141+
submitButton.setFont(new Font("Arial", Font.PLAIN, 14));
142+
submitButton.addActionListener(e -> submitGuess());
143+
inputPanel.add(submitButton);
144+
145+
mainPanel.add(inputPanel);
146+
147+
mainPanel.add(Box.createRigidArea(new Dimension(0, 20)));
148+
149+
// Feedback label
150+
feedbackLabel = new JLabel(" ");
151+
feedbackLabel.setFont(new Font("Arial", Font.BOLD, 16));
152+
feedbackLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
153+
mainPanel.add(feedbackLabel);
154+
155+
mainPanel.add(Box.createRigidArea(new Dimension(0, 30)));
156+
157+
// New game button
158+
newGameButton = new JButton("New Game");
159+
newGameButton.setFont(new Font("Arial", Font.PLAIN, 14));
160+
newGameButton.setAlignmentX(Component.CENTER_ALIGNMENT);
161+
newGameButton.addActionListener(e -> startNewGame());
162+
newGameButton.setVisible(false);
163+
mainPanel.add(newGameButton);
164+
165+
add(mainPanel);
166+
}
167+
168+
/** Starts a new game by resetting the game state and UI components. */
169+
private void startNewGame() {
170+
targetNumber = randomGenerator.number(100);
171+
numberOfGuesses = 0;
172+
173+
guessField.setEnabled(true);
174+
submitButton.setEnabled(true);
175+
newGameButton.setVisible(false);
176+
177+
guessField.setText("");
178+
feedbackLabel.setText(" ");
179+
feedbackLabel.setForeground(Color.BLACK);
180+
updateGuessCount();
181+
182+
guessField.requestFocus();
183+
}
184+
185+
/** Processes the user's guess and updates the UI with feedback. */
186+
private void submitGuess() {
187+
String input = guessField.getText().trim();
188+
189+
if (input.isEmpty()) {
190+
showFeedback("Please enter a number!", Color.RED);
191+
return;
192+
}
193+
194+
int guess;
195+
try {
196+
guess = Integer.parseInt(input);
197+
} catch (NumberFormatException e) {
198+
showFeedback("Invalid input! Please enter a valid number.", Color.RED);
199+
guessField.setText("");
200+
return;
201+
}
202+
203+
try {
204+
guessChecker.check(guess);
205+
} catch (IllegalArgumentException e) {
206+
showFeedback(e.getMessage(), Color.RED);
207+
guessField.setText("");
208+
return;
209+
}
210+
211+
numberOfGuesses++;
212+
updateGuessCount();
213+
214+
if (guess > targetNumber) {
215+
showFeedback("Too high! Try a lower number.", new Color(255, 140, 0)); // Orange
216+
} else if (guess < targetNumber) {
217+
showFeedback("Too low! Try a higher number.", new Color(30, 144, 255)); // Blue
218+
} else {
219+
// Correct guess
220+
showFeedback("Congratulations! You guessed it!", new Color(0, 128, 0)); // Green
221+
guessField.setEnabled(false);
222+
submitButton.setEnabled(false);
223+
newGameButton.setVisible(true);
224+
newGameButton.requestFocus();
225+
226+
// Show congratulations dialog
227+
String message =
228+
String.format(
229+
"You guessed the number in %d %s!",
230+
numberOfGuesses, numberOfGuesses == 1 ? "guess" : "guesses");
231+
JOptionPane.showMessageDialog(
232+
this, message, "Congratulations!", JOptionPane.INFORMATION_MESSAGE);
233+
}
234+
235+
guessField.setText("");
236+
guessField.requestFocus();
237+
}
238+
13239
/**
14-
* Creates and displays the main game window. Sets up a JFrame with a centered label showing the
15-
* game title.
240+
* Updates the feedback label with the provided message and color.
241+
*
242+
* @param message the feedback message to display
243+
* @param color the color to use for the message
16244
*/
17-
void createWindow() {
18-
JFrame jframe = new JFrame("Number Guessing Game");
19-
JLabel jlabel = new JLabel("Number Guessing Game", SwingConstants.CENTER);
20-
// JButton jbutton = new JButton("Start game!");
245+
private void showFeedback(String message, Color color) {
246+
feedbackLabel.setText(message);
247+
feedbackLabel.setForeground(color);
248+
}
21249

22-
jframe.getContentPane().add(jlabel, BorderLayout.CENTER);
250+
/** Updates the guess count label to reflect the current number of guesses. */
251+
private void updateGuessCount() {
252+
guessCountLabel.setText("Number of guesses: " + numberOfGuesses);
253+
}
23254

24-
jframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // Exit on close
25-
jframe.setSize(300, 300);
255+
/** Displays the About dialog with game information. */
256+
private void showAboutDialog() {
257+
String message =
258+
String.format(
259+
"Number Guessing Game\n\n"
260+
+ "Version: %s\n"
261+
+ "Author: %s\n\n"
262+
+ "Project URL:\n%s\n\n"
263+
+ "Online Documentation:\n%s",
264+
getVersion(),
265+
gameInfo.author(),
266+
gameInfo.projectURL(),
267+
gameInfo.onlineJavadoc());
26268

27-
jframe.setVisible(true); // Set visible
269+
JOptionPane.showMessageDialog(
270+
this, message, "About Number Guessing Game", JOptionPane.INFORMATION_MESSAGE);
271+
}
272+
273+
/**
274+
* Gets the version of the application.
275+
*
276+
* @return the version string
277+
*/
278+
private String getVersion() {
279+
ReadVersionFile versionReader = new ReadVersionFile();
280+
try {
281+
return versionReader.readVersion();
282+
} catch (Exception e) {
283+
return "Unknown";
284+
}
285+
}
286+
287+
/**
288+
* Creates and displays the GUI window. This method should be called on the Event Dispatch
289+
* Thread for thread safety.
290+
*/
291+
public void createWindow() {
292+
// This method is kept for backwards compatibility
293+
// The constructor already makes the window visible
28294
}
29295

30296
/**
31-
* Test method for the GUI. Creates a GUI instance and displays the window for testing purposes.
297+
* Main method for testing the GUI. Creates and displays the game window on the Event Dispatch
298+
* Thread.
32299
*
33300
* @param args command line arguments (not used)
34301
*/
35-
public static void main(String[] args) { // Test GUI
36-
GUI GUI = new GUI();
37-
GUI.createWindow();
302+
public static void main(String[] args) {
303+
// Use SwingUtilities to ensure thread safety
304+
SwingUtilities.invokeLater(() -> new GUI());
38305
}
39306
}

0 commit comments

Comments
 (0)